@plimsollmark/client 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,8 @@ protocol over `fetch` and keeps the promises the Go client keeps:
11
11
 
12
12
  - it states the protocol number on every request;
13
13
  - it checks every answer's **run record**: it recomputes the request and result digests
14
- from what it sent and received ([run-records.md](https://github.com/plimsollmark/plimsoll/blob/main/docs/run-records.md)), and an
14
+ from what it sent and received ([run-records.md](https://github.com/plimsollmark/plimsoll/blob/main/docs/run-records.md)), refuses a
15
+ result of another kind than the request's and a record that ends before it starts, and an
15
16
  answer that does not check, or has no record, is a `data_loss` error with the result
16
17
  attached, because the code may have run;
17
18
  - it checks the reported isolation tier against the caller's floor the same way;
@@ -74,7 +75,7 @@ directory, before the code runs. Its result adds `interpreterStarted` (this call
74
75
  a fresh interpreter, so nothing defined earlier exists) and `interpreterEnded`; its exit code
75
76
  is 0 when the code ran, 1 when it raised and 124 at the deadline. Python needs `python3` in
76
77
  the daemon's image (`plimsoll/sandbox-python` has it, with NumPy and SciPy);
77
- `describe()` lists the languages the daemon proved on `environments.project.languages`.
78
+ `describe()` lists the languages a session's cells run in on `sessionEnvironment.languages`.
78
79
 
79
80
  `close()` sends one `CloseSession` however many times it is called, and every later call
80
81
  gets the first one's summary or error: the daemon forgets a session at its first close and
@@ -176,8 +177,22 @@ exists, and `freshSandbox` whenever the call is the first answered one in a newl
176
177
  sandbox, so no earlier file is there either. That covers a sandbox that `dispose`, the
177
178
  idle close or a session cap (below) let go, one that ended by itself (its lifetime, its disk
178
179
  budget), and a conversation resumed in another process, which this instance cannot tell
179
- from a first call. A call without a key (no thread, no run) always runs fresh: one sandbox
180
- shared across conversations would show one user another's files. A language the daemon's
180
+ from a first call. A call without a key (no thread, no run) never shares a sandbox: one
181
+ sandbox shared across conversations would show one user another's files. It is one cell
182
+ the daemon runs by itself (`client.runCell(cell, { preferWarm: true })`; no `preferWarm`
183
+ with `sessions: "never"`): on a daemon that keeps a warm pool (`describe()` states
184
+ `sessionPool`, the operator's `SANDBOX_SESSION_POOL`) a waiting sandbox that has run only
185
+ plimsoll's own programs answers it and is deleted after, so the call is as alone as a
186
+ fresh one and answers without a sandbox being made for it; with no pool, or none waiting
187
+ (a burst larger than the pool), the daemon runs it in a sandbox made for it, and a miss
188
+ costs nothing more. Measured on one laptop on 2026-10-28 for the client-side form this
189
+ replaced (an open, the cell, a close; plimsolld on docker under runc, a pool of 2): 38 ms
190
+ (Python) and 43 ms (JavaScript) against 651 and 631 ms fresh (medians of 15 calls, 3 s
191
+ apart); the daemon's form sends one request instead of two and was not measured
192
+ separately. The answer reads as a fresh run's: `stateKept` and `filesPersist` false, and
193
+ `runCell`'s result says `warm`. What it costs: a pool sandbox runs the cell in the session's
194
+ image (on docker the project image, which a fresh cell uses too); the run record is a
195
+ single run's either way and does not cover `warm`. A language the daemon's
181
196
  image cannot run is refused before anything is sent. Output past `maxOutputChars` (each of
182
197
  stdout and stderr) is cut and marked truncated, and a cut never ends on the first half of a
183
198
  surrogate pair (the two UTF-16 code units that encode one character such as an emoji): a
package/dist/client.d.ts CHANGED
@@ -3,7 +3,7 @@ import { LANGUAGES, OUTCOME_NAMES, TIERS } from "./tables.gen.ts";
3
3
  import { type SessionEnd } from "./errors.ts";
4
4
  import type { WireCellRun, WireEnvelope, WireOpenSessionResponse, WireSoftwareRule } from "./wire.ts";
5
5
  /** The wire protocol number this client speaks (protocol.Number in Go). */
6
- export declare const PROTOCOL = 4;
6
+ export declare const PROTOCOL = 5;
7
7
  /** How strong the boundary is, weakest first. */
8
8
  export type Isolation = (typeof TIERS)[number];
9
9
  /** Whether a tier the daemon reported meets a floor. An unknown tier meets nothing. */
@@ -153,6 +153,13 @@ export type CellResult = Evidence & {
153
153
  interpreterStarted: boolean;
154
154
  /** The interpreter ended during this call; the next cell starts a fresh one. */
155
155
  interpreterEnded: boolean;
156
+ /**
157
+ * A waiting pool member ran the cell: a sandbox made before the call that had run only
158
+ * plimsoll's own programs, handed to this call alone and deleted after it (runCell with
159
+ * preferWarm). False for a session's cell and for one run in a sandbox made for it. The
160
+ * record does not cover it.
161
+ */
162
+ warm: boolean;
156
163
  };
157
164
  export type Info = {
158
165
  sandbox: string;
@@ -174,6 +181,12 @@ export type Info = {
174
181
  */
175
182
  maxSessionsPerCaller: number;
176
183
  maxSessionsPerOwner: number;
184
+ /**
185
+ * How many sandboxes the daemon keeps ready for sessions, 0 when it keeps none: with
186
+ * one, a cell run with runCell's preferWarm, or a session opened with warmOnly, can
187
+ * answer without a sandbox being made for it. Stated with supportsSessions.
188
+ */
189
+ sessionPool: number;
177
190
  environments: {
178
191
  javascript: PayloadEnvironment;
179
192
  project: PayloadEnvironment;
@@ -209,6 +222,15 @@ export type SessionOptions = {
209
222
  * refused before anything is sent.
210
223
  */
211
224
  owner?: string;
225
+ /**
226
+ * A waiting pool member or nothing: on a daemon with none to hand over the open is
227
+ * refused, not dispatched, reason capacity, and no sandbox is made, so the caller can
228
+ * run fresh instead. It never closes another session of the owner to make room. A
229
+ * daemon that predates the field would have ignored it and made a sandbox, so it came
230
+ * with protocol 5, which such a daemon refuses before reading the open. A cell for one
231
+ * call needs no session of its own: runCell with preferWarm.
232
+ */
233
+ warmOnly?: boolean;
212
234
  signal?: AbortSignal;
213
235
  };
214
236
  /**
@@ -266,6 +288,26 @@ export declare class PlimsollClient {
266
288
  runJavaScript(code: string, opts?: RunOptions): Promise<JavaScriptResult>;
267
289
  /** Writes a multi-file project into a fresh sandbox and runs its steps in order. */
268
290
  runProject(req: ProjectRequest, opts?: RunOptions): Promise<ProjectResult>;
291
+ /**
292
+ * Runs a cell by itself: code for an interpreter of its language, its files written
293
+ * into the work directory first, its final expression's value printed, in a sandbox
294
+ * of its own that keeps nothing after the call (interpreterStarted and
295
+ * interpreterEnded are both true). Files under .plimsoll/, where the code and its
296
+ * runner go, are refused.
297
+ *
298
+ * preferWarm lets the daemon run it in a sandbox it keeps ready for sessions
299
+ * (Info.sessionPool): one that has run only plimsoll's own programs, with the
300
+ * interpreter already running, claimed for this call alone and deleted after it, so
301
+ * the call answers without a sandbox being made for it. When none fits the cell runs
302
+ * in a sandbox made for it, as without the flag: a miss is never a refusal. The
303
+ * result's warm says which ran. What it costs: a pool member runs the cell in the
304
+ * session image (on docker the project image, which a fresh cell uses too), in a
305
+ * sandbox that waited with plimsoll's interpreters in it. The record is a single
306
+ * run's either way, and does not cover warm.
307
+ */
308
+ runCell(req: CellRequest, opts?: RunOptions & {
309
+ preferWarm?: boolean;
310
+ }): Promise<CellResult>;
269
311
  /**
270
312
  * Opens a session: one sandbox kept for many calls, files persisting, and of
271
313
  * processes only the interpreters runCell keeps. Only on a daemon whose Describe
package/dist/client.js CHANGED
@@ -9,8 +9,9 @@ import { isIP } from "node:net";
9
9
  import { checkRecord, checkUnanswered, requestDigest, sessionFingerprint, softwareRuleAllows, } from "./record.js";
10
10
  import { LANGUAGES, OUTCOME_NAMES, TIERS } from "./tables.gen.js";
11
11
  import { errorFromWire, NOT_DISPATCHED_HEADER, PlimsollError, REQUEST_ID_HEADER, sessionEndFromWire, unboundSuccess } from "./errors.js";
12
+ import { wireBytes } from "./wire.js";
12
13
  /** The wire protocol number this client speaks (protocol.Number in Go). */
13
- export const PROTOCOL = 4;
14
+ export const PROTOCOL = 5;
14
15
  const SERVICE = "plimsoll.v1.SandboxService";
15
16
  // Above the largest legitimate project response, so a misbehaving daemon cannot
16
17
  // make the client buffer without bound (the Go client's maxResponseBytes).
@@ -98,7 +99,7 @@ function mergeRules(a, b) {
98
99
  return { mode: ids.length === 1 ? "exact" : "approved", identities: ids };
99
100
  }
100
101
  const num = (v) => Number(v ?? 0);
101
- const bytes = (s) => new Uint8Array(Buffer.from(s ?? "", "base64"));
102
+ const bytes = (s) => new Uint8Array(wireBytes(s));
102
103
  const text = (b) => Buffer.from(b).toString("utf8");
103
104
  function adviceFromWire(a) {
104
105
  return (a ?? []).map((f) => ({
@@ -186,6 +187,7 @@ function cellResult(resp, record) {
186
187
  stderrTruncated: c.stderrTruncated ?? false,
187
188
  interpreterStarted: c.interpreterStarted ?? false,
188
189
  interpreterEnded: c.interpreterEnded ?? false,
190
+ warm: resp.warm ?? false,
189
191
  };
190
192
  }
191
193
  // A lone surrogate has no UTF-8 form, so no protobuf string can hold one, though JSON
@@ -354,6 +356,7 @@ export class PlimsollClient {
354
356
  sessionEnvironment: env(m.sessionEnvironment),
355
357
  maxSessionsPerCaller: m.maxSessionsPerCaller ?? 0,
356
358
  maxSessionsPerOwner: m.maxSessionsPerOwner ?? 0,
359
+ sessionPool: m.sessionPool ?? 0,
357
360
  environments: {
358
361
  javascript: env(m.javascriptEnvironment),
359
362
  project: env(m.projectEnvironment),
@@ -378,6 +381,35 @@ export class PlimsollClient {
378
381
  const resp = await this.exchange("Run", this.envelope(opts, validateRule(opts.software)), projectPayload(req, this.projectGrant), opts);
379
382
  return decoded(() => finish(resp.run, resp.record, projectResult, "project", opts.minimumIsolation));
380
383
  }
384
+ /**
385
+ * Runs a cell by itself: code for an interpreter of its language, its files written
386
+ * into the work directory first, its final expression's value printed, in a sandbox
387
+ * of its own that keeps nothing after the call (interpreterStarted and
388
+ * interpreterEnded are both true). Files under .plimsoll/, where the code and its
389
+ * runner go, are refused.
390
+ *
391
+ * preferWarm lets the daemon run it in a sandbox it keeps ready for sessions
392
+ * (Info.sessionPool): one that has run only plimsoll's own programs, with the
393
+ * interpreter already running, claimed for this call alone and deleted after it, so
394
+ * the call answers without a sandbox being made for it. When none fits the cell runs
395
+ * in a sandbox made for it, as without the flag: a miss is never a refusal. The
396
+ * result's warm says which ran. What it costs: a pool member runs the cell in the
397
+ * session image (on docker the project image, which a fresh cell uses too), in a
398
+ * sandbox that waited with plimsoll's interpreters in it. The record is a single
399
+ * run's either way, and does not cover warm.
400
+ */
401
+ async runCell(req, opts = {}) {
402
+ if (req.language !== "javascript" && req.language !== "python") {
403
+ throw new PlimsollError("invalid_argument", `plimsoll: unknown cell language ${JSON.stringify(req.language)}`, { notDispatched: "request" });
404
+ }
405
+ if (opts.preferWarm !== undefined && typeof opts.preferWarm !== "boolean") {
406
+ throw new PlimsollError("invalid_argument", "plimsoll: preferWarm must be a boolean", { notDispatched: "request" });
407
+ }
408
+ const files = (req.files ?? []).map((f) => ({ path: f.path, content: f.content }));
409
+ const env = { ...this.envelope(opts, validateRule(opts.software)), preferWarm: opts.preferWarm || undefined };
410
+ const resp = await this.exchange("Run", env, { cell: { language: req.language, code: req.code, files } }, opts);
411
+ return decoded(() => finish(resp.run, resp.record, cellResult, "cell", opts.minimumIsolation));
412
+ }
381
413
  /**
382
414
  * Opens a session: one sandbox kept for many calls, files persisting, and of
383
415
  * processes only the interpreters runCell keeps. Only on a daemon whose Describe
@@ -395,6 +427,9 @@ export class PlimsollClient {
395
427
  if (opts.owner !== undefined && (typeof opts.owner !== "string" || opts.owner === "")) {
396
428
  throw new PlimsollError("invalid_argument", "plimsoll: owner must be a nonempty string, or omitted for none", { notDispatched: "request" });
397
429
  }
430
+ if (opts.warmOnly !== undefined && typeof opts.warmOnly !== "boolean") {
431
+ throw new PlimsollError("invalid_argument", "plimsoll: warmOnly must be a boolean", { notDispatched: "request" });
432
+ }
398
433
  const m = await this.call("OpenSession", {
399
434
  protocol: PROTOCOL,
400
435
  minimumIsolation: opts.minimumIsolation,
@@ -404,6 +439,7 @@ export class PlimsollClient {
404
439
  softwareRule: rule,
405
440
  languages: opts.languages?.length ? [...new Set(opts.languages)] : undefined,
406
441
  owner: opts.owner === undefined ? undefined : ownerDigest(this.token, opts.owner),
442
+ warmOnly: opts.warmOnly || undefined,
407
443
  }, opts.signal);
408
444
  const s = decoded(() => new Session(this, m, rule, opts.minimumIsolation));
409
445
  if (decoded(() => s.fingerprint !== sessionFingerprint(m.sessionId ?? ""))) {
@@ -437,7 +473,7 @@ export class PlimsollClient {
437
473
  return decoded(() => this.checked(env, payload, resp));
438
474
  }
439
475
  checked(env, payload, resp) {
440
- const checked = checkRecord(requestDigest({ protocol: env.protocol, minimumIsolation: env.minimumIsolation ?? "", timeoutMs: env.timeoutMs ?? 0, softwareRule: env.softwareRule, payload: digestPayload(payload) }), env.softwareRule, resp);
476
+ const checked = checkRecord(requestDigest({ protocol: env.protocol, minimumIsolation: env.minimumIsolation ?? "", timeoutMs: env.timeoutMs ?? 0, softwareRule: env.softwareRule, payload: digestPayload(payload) }), "javascript" in payload ? "javascript" : "project" in payload ? "project" : "cell", env.softwareRule, resp);
441
477
  if ("problem" in checked)
442
478
  throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { result: resp });
443
479
  const r = checked.record;
@@ -625,16 +661,16 @@ export class Session {
625
661
  this.#end = e.sessionEnded;
626
662
  throw e;
627
663
  }
628
- return decoded(() => this.#chained(m, env, rule, digest));
664
+ return decoded(() => this.#chained(m, env, rule, digest, "javascript" in payload ? "javascript" : "project" in payload ? "project" : "cell"));
629
665
  }
630
- #chained(m, env, rule, digest) {
666
+ #chained(m, env, rule, digest, kind) {
631
667
  const run = m.run;
632
668
  if (!run)
633
669
  throw new PlimsollError("data_loss", "plimsoll: the session call's answer carries no run");
634
670
  const end = sessionEndFromWire(m.ended);
635
671
  if (end !== "open")
636
672
  this.#end = { reason: end, detail: m.endDetail ?? "" };
637
- const checked = checkRecord(digest, rule, run);
673
+ const checked = checkRecord(digest, kind, rule, run);
638
674
  if ("problem" in checked)
639
675
  throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { result: run });
640
676
  const r = checked.record;
package/dist/errors.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { RunRecord } from "./record.ts";
2
2
  import { REFUSAL_NAMES, SESSION_END_NAMES } from "./tables.gen.ts";
3
- import type { WireError, WireRecord } from "./wire.ts";
3
+ import { type WireError, type WireRecord } from "./wire.ts";
4
4
  /** Why a request was refused before any code ran (plimsoll.v1.NotDispatchedReason). */
5
5
  export type Refusal = (typeof REFUSAL_NAMES)[number];
6
6
  /**
@@ -38,6 +38,7 @@ export declare class PlimsollError extends Error {
38
38
  * The record the daemon sends with a session call that may have run but ended in
39
39
  * an error (an unanswered record, as it came off the wire). The Session checks it
40
40
  * and keeps it in its chain, so the session goes on; the call's outcome is unknown.
41
+ * On a single run's error it is kept as it came and checked by nothing.
41
42
  */
42
43
  readonly unanswered: WireRecord | undefined;
43
44
  /**
package/dist/errors.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // and comes back with notDispatched set; anything else may have followed
4
4
  // execution and is never a safe automatic retry (docs/run-results.md).
5
5
  import { REFUSAL_NAMES, SESSION_END_NAMES } from "./tables.gen.js";
6
+ import { wireBytes } from "./wire.js";
6
7
  export class PlimsollError extends Error {
7
8
  code;
8
9
  /**
@@ -23,6 +24,7 @@ export class PlimsollError extends Error {
23
24
  * The record the daemon sends with a session call that may have run but ended in
24
25
  * an error (an unanswered record, as it came off the wire). The Session checks it
25
26
  * and keeps it in its chain, so the session goes on; the call's outcome is unknown.
27
+ * On a single run's error it is kept as it came and checked by nothing.
26
28
  */
27
29
  unanswered;
28
30
  /**
@@ -145,12 +147,37 @@ function decodeUnanswered(b) {
145
147
  let rec;
146
148
  for (let i = 0; i < b.length;) {
147
149
  const [tag, j] = varint(b, i);
148
- const [n, k] = varint(b, j);
149
- if ((tag & 7) !== 2 || k + n > b.length)
150
- throw new Error("bad detail");
151
- if (tag >>> 3 === 1)
150
+ const field = tag >>> 3;
151
+ const wire = tag & 7;
152
+ if (field === 1) {
153
+ if (wire !== 2)
154
+ throw new Error("UnansweredCall.record is not length-delimited");
155
+ const [n, k] = varint(b, j);
156
+ if (k + n > b.length)
157
+ throw new Error("bad detail");
152
158
  rec = decodeRecord(b.subarray(k, k + n));
153
- i = k + n;
159
+ i = k + n;
160
+ }
161
+ else if (wire === 0) {
162
+ // A field this client does not know is skipped by its wire type, as Go and Python
163
+ // skip it; every field used to be read as length-delimited, so a scalar a newer
164
+ // daemon adds dropped the record and stopped the session (review, 2026-10-26).
165
+ i = varint(b, j)[1];
166
+ }
167
+ else if (wire === 2) {
168
+ const [n, k] = varint(b, j);
169
+ if (k + n > b.length)
170
+ throw new Error("bad detail");
171
+ i = k + n;
172
+ }
173
+ else if (wire === 1 || wire === 5) {
174
+ i = j + (wire === 1 ? 8 : 4);
175
+ if (i > b.length)
176
+ throw new Error("bad detail");
177
+ }
178
+ else {
179
+ throw new Error("unexpected wire type");
180
+ }
154
181
  }
155
182
  return rec;
156
183
  }
@@ -214,7 +241,7 @@ export function errorFromWire(httpStatus, body, answer) {
214
241
  let unanswered;
215
242
  for (const d of Array.isArray(wire?.details) ? wire.details : []) {
216
243
  try {
217
- const bytes = Buffer.from(d.value ?? "", "base64");
244
+ const bytes = wireBytes(d.value);
218
245
  if (d.type === "plimsoll.v1.NotDispatched") {
219
246
  notDispatched = REFUSAL_NAMES[decodeDetail(bytes).reason] ?? "unknown";
220
247
  }
package/dist/record.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { WireRecord, WireRunResponse, WireSoftwareRule } from "./wire.ts";
1
+ import { type WireRecord, type WireRunResponse, type WireSoftwareRule } from "./wire.ts";
2
2
  /** The record encoding version this client computes and checks: every field, every time, for an answered call and an unanswered session call alike. */
3
3
  export declare const RECORD_VERSION = 4;
4
4
  /** A record's instance: "" (the provider names none) or a typed reference such as `k8s-pod-uid:` and a pod's UID. */
@@ -89,7 +89,7 @@ export declare function checkUnanswered(reqDigest: string, floor: string, rule:
89
89
  * both digests, the evidence the response repeats, the software rule and the
90
90
  * record's own digest. Returns the reason it does not check, or undefined.
91
91
  */
92
- export declare function checkRecord(reqDigest: string, rule: WireSoftwareRule | undefined, resp: WireRunResponse): {
92
+ export declare function checkRecord(reqDigest: string, kind: "javascript" | "project" | "cell", rule: WireSoftwareRule | undefined, resp: WireRunResponse): {
93
93
  record: RunRecord;
94
94
  } | {
95
95
  problem: string;
package/dist/record.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import { createHash } from "node:crypto";
5
5
  import { PlimsollError } from "./errors.js";
6
6
  import { OUTCOMES, TIERS } from "./tables.gen.js";
7
+ import { wireBytes, WireShapeError } from "./wire.js";
7
8
  /** The record encoding version this client computes and checks: every field, every time, for an answered call and an unanswered session call alike. */
8
9
  export const RECORD_VERSION = 4;
9
10
  const INSTANCE_FORM = /^[a-z][a-z0-9-]{0,31}:[A-Za-z0-9._:-]{1,127}$/;
@@ -118,7 +119,7 @@ export function outcomeNumber(name) {
118
119
  return name;
119
120
  return OUTCOMES[name];
120
121
  }
121
- const b64 = (s) => Buffer.from(s ?? "", "base64");
122
+ const b64 = wireBytes;
122
123
  /** The result digest of a Run response as it arrived on the wire. */
123
124
  export function resultDigest(resp) {
124
125
  const e = new Encoder("plimsoll.run-result.v1");
@@ -169,8 +170,9 @@ export function resultDigest(resp) {
169
170
  e.bool("interpreter_ended", c.interpreterEnded ?? false);
170
171
  }
171
172
  else {
172
- // A module result, or none: this client sends neither, so the kind check
173
- // refuses the response before its digest matters.
173
+ // A module result, or none: this client sends neither, so the record check
174
+ // refuses the response as not of the request's kind, after this digest is
175
+ // computed and found not to match.
174
176
  e.str("kind", "");
175
177
  }
176
178
  return e.sum();
@@ -314,15 +316,33 @@ export function checkUnanswered(reqDigest, floor, rule, m, fingerprint, prevSeq,
314
316
  * both digests, the evidence the response repeats, the software rule and the
315
317
  * record's own digest. Returns the reason it does not check, or undefined.
316
318
  */
317
- export function checkRecord(reqDigest, rule, resp) {
319
+ export function checkRecord(reqDigest, kind, rule, resp) {
318
320
  if (!resp.record)
319
321
  return { problem: "the response carries no run record" };
320
322
  const r = recordFromWire(resp.record);
321
- const result = resultDigest(resp);
323
+ let result;
324
+ try {
325
+ result = resultDigest(resp);
326
+ }
327
+ catch (e) {
328
+ if (e instanceof WireShapeError)
329
+ return { problem: `the answer is malformed: ${e.message}` };
330
+ throw e;
331
+ }
322
332
  if (r.version !== RECORD_VERSION)
323
333
  return { problem: versionProblem(r.version) };
324
334
  if (r.unanswered !== "")
325
335
  return { problem: "an answered call's record states an unanswered code" };
336
+ // The kind, inside the check as in Go's record.check since 2026-10-26: a result of
337
+ // another kind fails here, before a session's chain moves on, so a daemon caught
338
+ // answering the wrong kind is not used further (review, 2026-10-26).
339
+ const kinds = ["javascript", "project", "module", "cell"].filter((k) => resp[k] !== undefined && resp[k] !== null);
340
+ if (kinds.length > 1)
341
+ return { problem: `the answer holds ${kinds.length} results; a run has one` };
342
+ if (kinds.length !== 1 || kinds[0] !== kind)
343
+ return { problem: `the daemon answered a ${kind} request with ${kinds.length === 1 ? kinds[0] : "no"} result` };
344
+ if (r.endedUnixMs < r.startedUnixMs)
345
+ return { problem: "the record ends before it starts" };
326
346
  if (r.requestSha256 !== reqDigest)
327
347
  return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
328
348
  if (r.resultSha256 !== result)
@@ -26,7 +26,7 @@ export type CodeSandboxesOptions = {
26
26
  /**
27
27
  * "auto" (default) keeps a session per key when the daemon supports sessions,
28
28
  * else runs each call fresh. "always" fails when it does not; "never" always
29
- * runs fresh.
29
+ * runs fresh, and never in a sandbox the daemon kept ready (no preferWarm).
30
30
  */
31
31
  sessions?: SessionMode;
32
32
  /** The languages the tool offers, the first being the default. Default python, then javascript. */
@@ -133,21 +133,6 @@ export type ExecuteCodeOutput = {
133
133
  /** SHA-256 of the run record checked by the client before this result was returned. */
134
134
  recordSha256: string;
135
135
  };
136
- /** @internal A fresh call on a daemon without projects: the code as a snippet, its last value printed. Node and QuickJS alike. */
137
- export declare function snippetRunner(code: string): string;
138
- /**
139
- * @internal A fresh run prints its last expression as a cell does, through these
140
- * runners, and takes what a cell takes: top-level await, and imports from the work
141
- * directory (Python's own imports first, in isolated mode, as the session kernel
142
- * does; Node's require resolving from the work directory, and the image's baked
143
- * packages above it).
144
- */
145
- export declare const RUNNERS: Record<Language, {
146
- path: string;
147
- file: string;
148
- step: string;
149
- source: string;
150
- }>;
151
136
  export declare class CodeSandboxes {
152
137
  #private;
153
138
  constructor(opts: CodeSandboxesOptions);
package/dist/sandboxes.js CHANGED
@@ -9,11 +9,15 @@
9
9
  // cell: code run in an interpreter the session keeps alive, so variables and
10
10
  // loaded data survive between calls as they do in a notebook, and the files a call
11
11
  // is given or writes stay in the work directory. On any other daemon, and for a
12
- // call without a key, each call runs in a fresh sandbox through a small runner that
13
- // prints the last expression the same way; nothing persists. The tool's output says
14
- // which, so the model is never told state survived when it did not. A daemon without
15
- // projects (wasm) runs a fresh call as a JavaScript snippet, and refuses Python and
16
- // files before sending anything.
12
+ // call without a key, each call is one cell the daemon runs by itself (runCell), in a
13
+ // sandbox of its own: nothing persists. The tool's output says which, so the model is
14
+ // never told state survived when it did not. The call asks for a sandbox the daemon
15
+ // keeps ready (preferWarm, unless sessions is "never"): on a daemon with a warm pool a
16
+ // waiting one that has run nothing answers it and is deleted after; otherwise, and
17
+ // when none is waiting, the daemon runs it in a sandbox made for it, through a runner
18
+ // that prints the last expression the same way. A daemon without projects (wasm) runs
19
+ // it as a JavaScript snippet, and this instance refuses Python and files there before
20
+ // sending anything.
17
21
  //
18
22
  // Whether earlier state exists is something only the sandbox knows: this instance
19
23
  // forgets a key when it is disposed or idles out, and a conversation that resumes
@@ -98,96 +102,6 @@ function untilAborted(p, signal) {
98
102
  export function keyDigest(key) {
99
103
  return createHash("sha256").update(keyId(key), "utf8").digest("hex").slice(0, 12);
100
104
  }
101
- /** @internal A fresh call on a daemon without projects: the code as a snippet, its last value printed. Node and QuickJS alike. */
102
- export function snippetRunner(code) {
103
- return [
104
- "(() => {",
105
- " const show = (v) => {",
106
- ' if (typeof require === "function") { try { return require("node:util").inspect(v, { depth: 4 }); } catch (_) {} }',
107
- " try { const s = JSON.stringify(v); if (s !== undefined) return s; } catch (_) {}",
108
- " return String(v);",
109
- " };",
110
- ` const v = (0, eval)(${JSON.stringify(code)});`,
111
- " Promise.resolve(v).then((v) => { if (v !== undefined) console.log(show(v)); });",
112
- "})();",
113
- "",
114
- ].join("\n");
115
- }
116
- /**
117
- * @internal A fresh run prints its last expression as a cell does, through these
118
- * runners, and takes what a cell takes: top-level await, and imports from the work
119
- * directory (Python's own imports first, in isolated mode, as the session kernel
120
- * does; Node's require resolving from the work directory, and the image's baked
121
- * packages above it).
122
- */
123
- export const RUNNERS = {
124
- python: {
125
- path: ".plimsoll/run.py",
126
- file: ".plimsoll/cell.py",
127
- step: "python3 -I .plimsoll/run.py",
128
- // As the session kernel runs a cell: at module level, an event loop only for code
129
- // that awaits at the top level, so the cell's own asyncio.run works.
130
- source: [
131
- "import ast, asyncio, inspect, linecache, sys",
132
- "sys.path.insert(0, '')",
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()",
136
- "linecache.cache['cell'] = (len(src), None, src.splitlines(True), 'cell')",
137
- "tree = ast.parse(src, 'cell', 'exec')",
138
- "last = ast.Expression(tree.body.pop().value) if tree.body and isinstance(tree.body[-1], ast.Expr) else None",
139
- "ns = {'__name__': '__main__', '__builtins__': __builtins__}",
140
- "flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT",
141
- "loop = asyncio.new_event_loop()",
142
- "def settle(r):",
143
- " return loop.run_until_complete(r) if inspect.isawaitable(r) else r",
144
- "settle(eval(compile(tree, 'cell', 'exec', flags=flags), ns))",
145
- "if last is not None:",
146
- " value = settle(eval(compile(last, 'cell', 'eval', flags=flags), ns))",
147
- " if value is not None:",
148
- " print(repr(value))",
149
- "",
150
- ].join("\n"),
151
- },
152
- javascript: {
153
- path: ".plimsoll/run.cjs",
154
- file: ".plimsoll/cell.js",
155
- step: "node --expose-internals .plimsoll/run.cjs",
156
- source: [
157
- "const fs = require('node:fs'), util = require('node:util'), vm = require('node:vm');",
158
- // The names a cell in the session's `node -e` interpreter sees as globals.
159
- "globalThis.require = require('node:module').createRequire(process.cwd() + '/');",
160
- "globalThis.module = { exports: {} }; globalThis.exports = globalThis.module.exports;",
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.
171
- "let tla = null;",
172
- "try { tla = require('internal/repl/await').processTopLevelAwait; } catch {}",
173
- "const src = fs.readFileSync('.plimsoll/cell.js', 'utf8');",
174
- "let wrapped = null;",
175
- "if (tla) { try { wrapped = tla(src); } catch {} }",
176
- "(async () => {",
177
- " let v;",
178
- " if (wrapped) {",
179
- " const out = await vm.runInThisContext(wrapped, { filename: 'cell.js' });",
180
- " v = out === undefined ? undefined : out.value;",
181
- " } else {",
182
- " v = vm.runInThisContext(src, { filename: 'cell.js' });",
183
- " if (v instanceof Promise) v = await v;",
184
- " }",
185
- " if (v !== undefined) console.log(util.inspect(v, { depth: 4 }));",
186
- "})().catch((e) => { console.error(e); process.exitCode = 1; });",
187
- "",
188
- ].join("\n"),
189
- },
190
- };
191
105
  export class CodeSandboxes {
192
106
  #opts;
193
107
  #entries = new Map();
@@ -404,8 +318,8 @@ export class CodeSandboxes {
404
318
  get #floor() {
405
319
  return this.#opts.minimumIsolation ?? "kernel";
406
320
  }
407
- // A fresh sandbox for one call: the files, the code and a runner that prints the
408
- // last expression, as one project.
321
+ // A sandbox of its own for one call: one cell the daemon runs by itself, in a sandbox
322
+ // it kept ready when one is waiting (preferWarm), else in one made for it.
409
323
  async #fresh(key, info, language, code, files, opts) {
410
324
  if (!info.supportsProject) {
411
325
  // A snippet is all this daemon runs (wasm): JavaScript, without files.
@@ -419,31 +333,12 @@ export class CodeSandboxes {
419
333
  notDispatched: "unsupported",
420
334
  });
421
335
  }
422
- const r = await this.client.runJavaScript(snippetRunner(code), opts);
423
- this.#record(r.record, key);
424
- return {
425
- ...this.#cut(language, r.exitCode, r.timedOut, r.stdout, r.stderr, r.stdoutTruncated || r.stderrTruncated),
426
- stateKept: false,
427
- filesPersist: false,
428
- isolation: r.isolation,
429
- recordSha256: r.record.sha256,
430
- };
431
336
  }
432
- const runner = RUNNERS[language];
433
- const r = await this.client.runProject({
434
- files: [...files, { path: runner.file, content: code }, { path: runner.path, content: runner.source }],
435
- steps: [runner.step],
436
- }, opts);
337
+ const preferWarm = (this.#opts.sessions ?? "auto") !== "never";
338
+ const r = await this.client.runCell({ language, code, files }, { ...opts, preferWarm });
437
339
  this.#record(r.record, key);
438
- const step = r.steps[0];
439
- if (!step) {
440
- // No step report: the outcome says what ended the run (a timeout, a lost report),
441
- // not whether the code had started, so there is no exit code to give. Unmarked,
442
- // as anything that may have run is; the checked result rides on the error.
443
- 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 });
444
- }
445
340
  return {
446
- ...this.#cut(language, step.exitCode, step.timedOut || r.outcome === "timed_out", step.stdout, step.stderr, step.stdoutTruncated || step.stderrTruncated),
341
+ ...this.#cut(language, r.exitCode, r.timedOut, r.stdout, r.stderr, r.stdoutTruncated || r.stderrTruncated),
447
342
  stateKept: false,
448
343
  filesPersist: false,
449
344
  isolation: r.isolation,
package/dist/wire.d.ts CHANGED
@@ -21,6 +21,8 @@ export type WireEnvelope = {
21
21
  traceId?: string;
22
22
  timeoutMs?: number;
23
23
  softwareRule?: WireSoftwareRule;
24
+ /** Run only, with a cell: the daemon may run it in a waiting pool member. */
25
+ preferWarm?: boolean;
24
26
  };
25
27
  /** A session's call to its interpreter (sessions.md, "Interpreters"). */
26
28
  export type WireCellRun = {
@@ -34,6 +36,7 @@ export type WireCellRun = {
34
36
  export type WireRunRequest = WireEnvelope & {
35
37
  javascript?: WireJavaScriptRun;
36
38
  project?: WireProjectRun;
39
+ cell?: WireCellRun;
37
40
  };
38
41
  export type WireSessionRunRequest = WireRunRequest & {
39
42
  sessionId: string;
@@ -118,6 +121,7 @@ export type WireRunResponse = {
118
121
  softwareIdentity?: string;
119
122
  environment?: string;
120
123
  instance?: string;
124
+ warm?: boolean;
121
125
  javascript?: WireJavaScriptResult;
122
126
  project?: WireProjectResult;
123
127
  module?: unknown;
@@ -158,6 +162,7 @@ export type WireDescribeResponse = {
158
162
  maxSessionsPerCaller?: number;
159
163
  maxSessionsPerOwner?: number;
160
164
  sessionEnvironment?: WirePayloadEnvironment;
165
+ sessionPool?: number;
161
166
  };
162
167
  export type WireOpenSessionRequest = {
163
168
  protocol: number;
@@ -167,6 +172,8 @@ export type WireOpenSessionRequest = {
167
172
  idleTimeoutMs?: number;
168
173
  softwareRule?: WireSoftwareRule;
169
174
  languages?: string[];
175
+ owner?: string;
176
+ warmOnly?: boolean;
170
177
  };
171
178
  export type WireOpenSessionResponse = {
172
179
  sessionId?: string;
@@ -192,3 +199,14 @@ export type WireError = {
192
199
  value?: string;
193
200
  }[];
194
201
  };
202
+ /** A bytes field that is not base64 text: the answer is not the protocol's. */
203
+ export declare class WireShapeError extends Error {
204
+ }
205
+ /**
206
+ * Decodes a bytes field of the daemon's answer. Only a string (or an absent field) is
207
+ * accepted: the answer is parsed JSON, and Buffer.from given an object with a
208
+ * "length" allocates that many bytes and reads each index, so a 30-byte
209
+ * {"length":2000000000} would cost 2 GB and a blocked event loop past the
210
+ * response's 32 MiB cap (Claude Security scan, 2026-10-27).
211
+ */
212
+ export declare function wireBytes(v: unknown): Buffer;
package/dist/wire.js CHANGED
@@ -3,4 +3,20 @@
3
3
  // JSON names; bytes are base64; 64-bit integers arrive as strings; enums as their
4
4
  // names; a field at its zero value is omitted, which is why everything read is
5
5
  // optional.
6
- export {};
6
+ /** A bytes field that is not base64 text: the answer is not the protocol's. */
7
+ export class WireShapeError extends Error {
8
+ }
9
+ /**
10
+ * Decodes a bytes field of the daemon's answer. Only a string (or an absent field) is
11
+ * accepted: the answer is parsed JSON, and Buffer.from given an object with a
12
+ * "length" allocates that many bytes and reads each index, so a 30-byte
13
+ * {"length":2000000000} would cost 2 GB and a blocked event loop past the
14
+ * response's 32 MiB cap (Claude Security scan, 2026-10-27).
15
+ */
16
+ export function wireBytes(v) {
17
+ if (v === undefined || v === null)
18
+ return Buffer.alloc(0);
19
+ if (typeof v !== "string")
20
+ throw new WireShapeError(`a bytes field holds a ${Array.isArray(v) ? "list" : typeof v}, not base64 text`);
21
+ return Buffer.from(v, "base64");
22
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plimsollmark/client",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "TypeScript client for plimsolld, with AI SDK, Trigger.dev and Mastra executeCode add-ons",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/plimsollmark/plimsoll/tree/main/clients/typescript#readme",