@plimsollmark/client 0.15.0 → 0.16.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
@@ -76,6 +76,15 @@ conversation
76
76
  ([what a session gives up](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#what-a-session-gives-up)).
77
77
  The tool's calls are cells, which carry no grant, so no API access is shared between them.
78
78
 
79
+ **The key decides who shares a sandbox, so derive it from identities you verified.** A
80
+ sandbox holds one trust domain: everything one call leaves there, later calls with the same
81
+ key see. plimsoll ties a session to the credential that opened it, not to the users behind
82
+ that credential, so if your service runs many users' code through one plimsoll credential,
83
+ two users with the same key share one sandbox, files and variables included. Build the key
84
+ from your own authenticated user and conversation (or job) IDs, never from a string a user
85
+ or the model supplies, or give each customer a plimsoll credential of their own
86
+ ([who may share a session](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#who-may-share-a-session)).
87
+
79
88
  `CodeSandboxes` keeps one sandbox per conversation key. With `sessions: "auto"` (the
80
89
  default) it asks the daemon once whether it keeps sessions:
81
90
 
@@ -111,10 +120,14 @@ mismatch means the daemon counted a call the client has no answer for (one that
111
120
  abort, a timeout, a dropped connection or a proxy's error), or, if none did, that someone
112
121
  else held the session ID. It goes to `onCloseError` (by default a warning) rather than being
113
122
  dropped at teardown. A call that may have run but ended in an error comes with its record
114
- (`PlimsollError.unanswered`, a version 3 record); the session checks it, keeps it in its
115
- chain and goes on. A call whose answer never arrived carries none, so the client sends
116
- nothing more on that session, and the conversation's next call opens a new sandbox and
117
- reports `freshSandbox: true`.
123
+ (`PlimsollError.unanswered`, a version 3 record); the session checks it, hands it back as
124
+ `PlimsollError.record`, keeps it in its chain and goes on, and so does the conversation's
125
+ sandbox. A call whose answer never arrived carries none, so the client sends nothing more
126
+ on that session (`Session.stopped` says why), and the conversation's next call opens a new
127
+ sandbox and reports `freshSandbox: true`. A session call aborted while it waits its turn
128
+ was never sent: it is refused, marked not dispatched, and the session goes on. The
129
+ `.plimsoll/` directory is the runner's: a file under it is refused before anything is
130
+ sent.
118
131
 
119
132
  The session ID is a capability. It lives in the client's memory and nowhere else: not in
120
133
  a log line, not in a record, not in Trigger.dev's `chat.local` (which is serialized into
@@ -150,6 +163,12 @@ export const codeChat = chat.agent({
150
163
  The full example, with a test that drives real turns through Trigger.dev's `mockChatAgent`:
151
164
  [examples/trigger-chat](https://github.com/plimsollmark/plimsoll/tree/main/examples/trigger-chat/).
152
165
 
166
+ What the hooks cannot cover: a run that dies without reaching `onChatSuspend` or
167
+ `onComplete` (its process killed, a crash) leaves its sandbox open until the add-on's idle
168
+ close (`idleCloseMs`, default 10 minutes) or, if the process is gone too, the daemon's own
169
+ idle suspend and session lifetime (`SANDBOX_SESSION_IDLE`, `SANDBOX_SESSION_LIFETIME`). A
170
+ worker shutting down can close every sandbox it holds with `sandbox.sandboxes.disposeAll()`.
171
+
153
172
  ## Mastra
154
173
 
155
174
  ```ts
@@ -166,8 +185,12 @@ export const analyst = new Agent({ id: "analyst", name: "analyst", instructions:
166
185
  ```
167
186
 
168
187
  The sandbox is keyed by Mastra's thread and resource (a thread ID is unique only within
169
- its user). Mastra has no hook for "this conversation is going to sleep", so a thread's
170
- sandbox closes on `dispose`, or after `idleCloseMs` (default 10 minutes) without a call.
188
+ its user). A call without a `resourceId` runs in a fresh sandbox every time: under an empty
189
+ resource, every user without one would share a sandbox with anyone whose thread ID
190
+ collided. Set the resource from your authenticated user, not from anything the user
191
+ typed. Mastra has no hook for "this conversation is going to sleep", so a thread's
192
+ sandbox closes on `dispose(threadId, resourceId)`, or after `idleCloseMs` (default 10
193
+ minutes) without a call.
171
194
 
172
195
  ## Tests
173
196
 
package/dist/client.d.ts CHANGED
@@ -157,6 +157,8 @@ export type Info = {
157
157
  supportsSessions: boolean;
158
158
  sessionLifetimeMs: number;
159
159
  sessionIdleTimeoutMs: number;
160
+ /** Where a session's calls run (on docker the project image), stated with supportsSessions. */
161
+ sessionEnvironment: PayloadEnvironment;
160
162
  environments: {
161
163
  javascript: PayloadEnvironment;
162
164
  project: PayloadEnvironment;
@@ -247,10 +249,17 @@ export declare class Session {
247
249
  /** The tier the daemon measured when the session opened. */
248
250
  readonly isolation: string;
249
251
  readonly sandbox: string;
252
+ /** The selected software the daemon stated at open. */
253
+ readonly softwareIdentity: string;
250
254
  readonly expiresAtMs: number;
251
255
  readonly idleTimeoutMs: number;
252
256
  /** @internal */
253
- constructor(client: PlimsollClient, m: WireOpenSessionResponse, rule: WireSoftwareRule | undefined);
257
+ constructor(client: PlimsollClient, m: WireOpenSessionResponse, rule: WireSoftwareRule | undefined, floor?: Exclude<Isolation, "none">);
258
+ /**
259
+ * Why this client sends nothing more on the session, once a call ended without an
260
+ * answer it could check (the call may have run); undefined while it is usable.
261
+ */
262
+ get stopped(): string | undefined;
254
263
  /** The session's end once a response reported it, else undefined. */
255
264
  get ended(): {
256
265
  reason: SessionEnd;
package/dist/client.js CHANGED
@@ -17,7 +17,9 @@ const TIERS = ["none", "process", "container", "kernel", "vm"];
17
17
  /** Whether a tier the daemon reported meets a floor. An unknown tier meets nothing. */
18
18
  export function meets(actual, floor) {
19
19
  const a = TIERS.indexOf(actual);
20
- return a >= 0 && a >= TIERS.indexOf(floor);
20
+ const f = TIERS.indexOf(floor);
21
+ // A floor is process, container, kernel or vm; anything else is met by nothing.
22
+ return a >= 0 && f >= 1 && a >= f;
21
23
  }
22
24
  const DEFAULT_REQUEST_TIMEOUT_MS = 6 * 60_000;
23
25
  function validateBaseUrl(raw, insecureHttp) {
@@ -199,6 +201,10 @@ export class PlimsollClient {
199
201
  }
200
202
  /** @internal One unary Connect call with the JSON codec. */
201
203
  async call(method, body, signal) {
204
+ // Aborted before it was sent (a session call waiting its turn, say): nothing left
205
+ // this process, so it is a refusal, not a call that may have run.
206
+ if (signal?.aborted)
207
+ throw new PlimsollError("canceled", `plimsoll: ${method} was canceled before it was sent`, { notDispatched: "request", cause: signal.reason });
202
208
  const headers = { "Content-Type": "application/json", "Connect-Protocol-Version": "1" };
203
209
  if (this.token)
204
210
  headers["Authorization"] = `Bearer ${this.token}`;
@@ -268,6 +274,7 @@ export class PlimsollClient {
268
274
  supportsSessions: m.supportsSessions ?? false,
269
275
  sessionLifetimeMs: m.sessionLifetimeMs ?? 0,
270
276
  sessionIdleTimeoutMs: m.sessionIdleTimeoutMs ?? 0,
277
+ sessionEnvironment: env(m.sessionEnvironment),
271
278
  environments: {
272
279
  javascript: env(m.javascriptEnvironment),
273
280
  project: env(m.projectEnvironment),
@@ -307,9 +314,11 @@ export class PlimsollClient {
307
314
  idleTimeoutMs: durationMs(opts.idleTimeoutMs) || undefined,
308
315
  softwareRule: rule,
309
316
  }, opts.signal);
310
- const s = new Session(this, m, rule);
317
+ const s = new Session(this, m, rule, opts.minimumIsolation);
311
318
  if (s.fingerprint !== sessionFingerprint(m.sessionId ?? "")) {
312
- throw new PlimsollError("data_loss", "plimsoll: the daemon's session fingerprint does not match its session ID");
319
+ // The session exists on the daemon either way, and nothing else holds its ID.
320
+ await s.close().catch(() => undefined);
321
+ throw new PlimsollError("data_loss", "plimsoll: the daemon's session fingerprint does not match its session ID; the session was closed");
313
322
  }
314
323
  if (opts.minimumIsolation && !meets(s.isolation, opts.minimumIsolation)) {
315
324
  await s.close().catch(() => undefined);
@@ -382,12 +391,16 @@ export class Session {
382
391
  /** The tier the daemon measured when the session opened. */
383
392
  isolation;
384
393
  sandbox;
394
+ /** The selected software the daemon stated at open. */
395
+ softwareIdentity;
385
396
  expiresAtMs;
386
397
  idleTimeoutMs;
387
398
  // The session ID is a capability: it goes to the daemon and nowhere else.
388
399
  #id;
389
400
  #client;
390
401
  #rule;
402
+ // The floor given at open: every call carries it unless the call asks for more.
403
+ #floor;
391
404
  #calls = 0n;
392
405
  #last = "";
393
406
  #end;
@@ -397,16 +410,25 @@ export class Session {
397
410
  #unknown;
398
411
  #queue = Promise.resolve();
399
412
  /** @internal */
400
- constructor(client, m, rule) {
413
+ constructor(client, m, rule, floor) {
401
414
  this.#client = client;
402
415
  this.#id = m.sessionId ?? "";
403
416
  this.#rule = rule;
417
+ this.#floor = floor;
404
418
  this.fingerprint = m.session ?? "";
405
419
  this.isolation = m.isolation ?? "";
406
420
  this.sandbox = m.sandbox ?? "";
421
+ this.softwareIdentity = m.softwareIdentity ?? "";
407
422
  this.expiresAtMs = num(m.expiresUnixMs);
408
423
  this.idleTimeoutMs = m.idleTimeoutMs ?? 0;
409
424
  }
425
+ /**
426
+ * Why this client sends nothing more on the session, once a call ended without an
427
+ * answer it could check (the call may have run); undefined while it is usable.
428
+ */
429
+ get stopped() {
430
+ return this.#unknown;
431
+ }
410
432
  /** The session's end once a response reported it, else undefined. */
411
433
  get ended() {
412
434
  return this.#end;
@@ -416,11 +438,13 @@ export class Session {
416
438
  return { calls: this.#calls, lastRecordSha256: this.#last };
417
439
  }
418
440
  async runJavaScript(code, opts = {}) {
441
+ opts = this.#withFloor(opts);
419
442
  const run = await this.#call({ javascript: { code, grantProfile: this.#client.jsGrant || undefined } }, opts);
420
443
  return finish(run.run, run.record, javascriptResult, "javascript", opts.minimumIsolation);
421
444
  }
422
445
  /** Runs a project in the session; its files persist for later calls. */
423
446
  async runProject(req, opts = {}) {
447
+ opts = this.#withFloor(opts);
424
448
  const run = await this.#call(projectPayload(req, this.#client.projectGrant), opts);
425
449
  return finish(run.run, run.record, projectResult, "project", opts.minimumIsolation);
426
450
  }
@@ -434,10 +458,19 @@ export class Session {
434
458
  if (req.language !== "javascript" && req.language !== "python") {
435
459
  throw new PlimsollError("invalid_argument", `plimsoll: unknown cell language ${JSON.stringify(req.language)}`, { notDispatched: "request" });
436
460
  }
461
+ opts = this.#withFloor(opts);
437
462
  const files = (req.files ?? []).map((f) => ({ path: f.path, content: f.content }));
438
463
  const run = await this.#call({ cell: { language: req.language, code: req.code, files } }, opts);
439
464
  return finish(run.run, run.record, cellResult, "cell", opts.minimumIsolation);
440
465
  }
466
+ // The call's options with the session's floor, unless the call asks for more.
467
+ #withFloor(opts) {
468
+ const a = this.#floor;
469
+ const b = opts.minimumIsolation;
470
+ if (!a || (b && TIERS.indexOf(b) >= TIERS.indexOf(a)))
471
+ return opts;
472
+ return { ...opts, minimumIsolation: a };
473
+ }
441
474
  #serial(f) {
442
475
  const next = this.#queue.then(f, f);
443
476
  this.#queue = next.catch(() => undefined);
@@ -460,13 +493,24 @@ export class Session {
460
493
  if (e instanceof PlimsollError && e.unanswered) {
461
494
  // The call may have run, and the daemon chained its record: check it and keep
462
495
  // it in the chain, so the session goes on and the call is not hidden.
463
- const checked = checkUnanswered(digest, rule, e.unanswered, this.fingerprint, this.#calls, this.#last);
496
+ let checked = checkUnanswered(digest, env.minimumIsolation ?? "", rule, e.unanswered, this.fingerprint, this.#calls, this.#last);
497
+ if ("record" in checked) {
498
+ // With no response to compare it with, the record's evidence must be what the
499
+ // session stated at open.
500
+ const r = checked.record;
501
+ if (r.provider !== this.sandbox || r.isolation !== this.isolation || r.softwareIdentity !== this.softwareIdentity) {
502
+ checked = {
503
+ problem: `the unanswered call's record names ${r.provider} at "${r.isolation}" running "${r.softwareIdentity}", the session opened as ${this.sandbox} at "${this.isolation}" running "${this.softwareIdentity}"`,
504
+ };
505
+ }
506
+ }
464
507
  if ("problem" in checked) {
465
508
  this.#unknown = checked.problem;
466
509
  throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { cause: e });
467
510
  }
468
511
  this.#calls = checked.record.sequence;
469
512
  this.#last = checked.record.sha256;
513
+ e.record = checked.record; // the checked record, as Go's UnansweredCallError carries it
470
514
  throw e;
471
515
  }
472
516
  this.#unknown = e instanceof Error ? e.message : String(e);
package/dist/errors.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { RunRecord } from "./record.ts";
1
2
  import type { WireError, WireRecord } from "./wire.ts";
2
3
  /** Why a request was refused before any code ran (plimsoll.v1.NotDispatchedReason). */
3
4
  export type Refusal = "request" | "permission" | "protocol" | "unsupported" | "isolation" | "capacity" | "environment" | "unknown";
@@ -33,6 +34,11 @@ export declare class PlimsollError extends Error {
33
34
  * and keeps it in its chain, so the session goes on; the call's outcome is unknown.
34
35
  */
35
36
  readonly unanswered: WireRecord | undefined;
37
+ /**
38
+ * That record once the Session has checked it against the call and its chain (Go:
39
+ * UnansweredCallError.Record); undefined otherwise.
40
+ */
41
+ record: RunRecord | undefined;
36
42
  constructor(code: Code, message: string, opts?: {
37
43
  notDispatched?: Refusal;
38
44
  sessionEnded?: {
package/dist/errors.js CHANGED
@@ -23,6 +23,11 @@ export class PlimsollError extends Error {
23
23
  * and keeps it in its chain, so the session goes on; the call's outcome is unknown.
24
24
  */
25
25
  unanswered;
26
+ /**
27
+ * That record once the Session has checked it against the call and its chain (Go:
28
+ * UnansweredCallError.Record); undefined otherwise.
29
+ */
30
+ record;
26
31
  constructor(code, message, opts = {}) {
27
32
  super(message, opts.cause === undefined ? undefined : { cause: opts.cause });
28
33
  this.name = "PlimsollError";
package/dist/mastra.d.ts CHANGED
@@ -21,7 +21,7 @@ export declare function plimsollExecuteCode(opts: PlimsollExecuteCodeOptions): {
21
21
  freshSandbox?: true | undefined;
22
22
  isolation: string;
23
23
  }, unknown, unknown, import("@mastra/core/tools").ToolExecutionContext<unknown, unknown, unknown>, "executeCode", unknown>;
24
- /** Closes a thread's sandbox, e.g. when the conversation ends. */
25
- dispose: (threadId: string, resourceId?: string) => Promise<void>;
24
+ /** Closes a user's thread's sandbox, e.g. when the conversation ends. */
25
+ dispose: (threadId: string, resourceId: string) => Promise<void>;
26
26
  sandboxes: CodeSandboxes;
27
27
  };
package/dist/mastra.js CHANGED
@@ -5,8 +5,11 @@
5
5
  import { createTool } from "@mastra/core/tools";
6
6
  import { CodeSandboxes } from "./sandboxes.js";
7
7
  import { executeCodeDescription, executeCodeInput, executeCodeOutput } from "./tool.js";
8
- // A thread id is unique only within its resource (the user), so the key is both.
9
- const threadKey = (threadId, resourceId = "") => `${resourceId}\u0000${threadId}`;
8
+ // A thread id is unique only within its resource (the user), so the key is both, and a
9
+ // call without either has no key and runs fresh. An empty resource would put every user
10
+ // without one whose thread id collided into one sandbox, with each other's files and
11
+ // variables.
12
+ const threadKey = (threadId, resourceId) => threadId && resourceId ? `${resourceId}\u0000${threadId}` : undefined;
10
13
  export function plimsollExecuteCode(opts) {
11
14
  const sandboxes = new CodeSandboxes(opts);
12
15
  const executeCode = createTool({
@@ -14,17 +17,19 @@ export function plimsollExecuteCode(opts) {
14
17
  description: executeCodeDescription(sandboxes.languages),
15
18
  inputSchema: executeCodeInput(sandboxes.languages),
16
19
  outputSchema: executeCodeOutput,
17
- // The thread scopes the sandbox. A call outside a thread runs fresh: one
18
- // sandbox shared across conversations would show one user another's files.
19
- execute: async (input, ctx) => {
20
- const thread = ctx?.agent?.threadId;
21
- return sandboxes.run(thread ? threadKey(thread, ctx?.agent?.resourceId) : undefined, input, ctx?.abortSignal);
22
- },
20
+ // The user's thread scopes the sandbox. A call outside a thread, or without a
21
+ // resource, runs fresh: one sandbox shared across conversations would show one user
22
+ // another's files.
23
+ execute: async (input, ctx) => sandboxes.run(threadKey(ctx?.agent?.threadId, ctx?.agent?.resourceId), input, ctx?.abortSignal),
23
24
  });
24
25
  return {
25
26
  executeCode,
26
- /** Closes a thread's sandbox, e.g. when the conversation ends. */
27
- dispose: (threadId, resourceId) => sandboxes.dispose(threadKey(threadId, resourceId)),
27
+ /** Closes a user's thread's sandbox, e.g. when the conversation ends. */
28
+ dispose: async (threadId, resourceId) => {
29
+ const key = threadKey(threadId, resourceId);
30
+ if (key !== undefined)
31
+ await sandboxes.dispose(key);
32
+ },
28
33
  sandboxes,
29
34
  };
30
35
  }
package/dist/record.d.ts CHANGED
@@ -73,10 +73,11 @@ export declare function softwareRuleAllows(rule: WireSoftwareRule | undefined, i
73
73
  /**
74
74
  * Checks the record the daemon sends with an unanswered session call's error
75
75
  * (record.CheckUnanswered): version 3, no result digest, a Connect code, the digest of
76
- * the request sent, its software rule, its own digest, and its place in the chain.
76
+ * the request sent, its software rule and that its software is in it, its own digest,
77
+ * its tier against the call's floor, and its place in the chain.
77
78
  * Returns the reason it does not check, or the record.
78
79
  */
79
- export declare function checkUnanswered(reqDigest: string, rule: WireSoftwareRule | undefined, m: WireRecord, fingerprint: string, prevSeq: bigint, prev: string): {
80
+ export declare function checkUnanswered(reqDigest: string, floor: string, rule: WireSoftwareRule | undefined, m: WireRecord, fingerprint: string, prevSeq: bigint, prev: string): {
80
81
  record: RunRecord;
81
82
  } | {
82
83
  problem: string;
package/dist/record.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // SHA-256 over a length-prefixed encoding, never over protobuf or JSON bytes.
3
3
  // The golden vectors in record/record_test.go are checked in test/record.test.ts.
4
4
  import { createHash } from "node:crypto";
5
+ import { PlimsollError } from "./errors.js";
5
6
  /** The record encoding version of an answered call, which this client computes and checks. */
6
7
  export const RECORD_VERSION = 2;
7
8
  /** The record encoding version of a session call that may have run but ended in an error. */
@@ -27,6 +28,10 @@ class Encoder {
27
28
  this.value(v);
28
29
  }
29
30
  str(name, v) {
31
+ // A lone surrogate (JSON can escape one) has no UTF-8 form: Buffer would put
32
+ // U+FFFD in its place and digest other bytes than the daemon did.
33
+ if (!v.isWellFormed())
34
+ throw new PlimsollError("data_loss", `plimsoll: ${name} is not well-formed text (a lone surrogate)`);
30
35
  this.bytes(name, Buffer.from(v, "utf8"));
31
36
  }
32
37
  // Integers are decimal ASCII; callers pass bigint for 64-bit values so no
@@ -162,6 +167,16 @@ export function resultDigest(resp) {
162
167
  }
163
168
  return e.sum();
164
169
  }
170
+ // big reads a 64-bit integer field the JSON codec sends as a decimal string (or a
171
+ // number). Anything else is an answer this client cannot read, a PlimsollError,
172
+ // never BigInt's own SyntaxError or RangeError.
173
+ function big(v, name) {
174
+ if (v === undefined)
175
+ return 0n;
176
+ if ((typeof v === "string" && /^-?[0-9]{1,20}$/.test(v)) || (typeof v === "number" && Number.isSafeInteger(v)))
177
+ return BigInt(v);
178
+ throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not an integer`);
179
+ }
165
180
  export function recordFromWire(m) {
166
181
  return {
167
182
  version: m.version ?? 0,
@@ -173,10 +188,10 @@ export function recordFromWire(m) {
173
188
  policy: m.policy ?? "",
174
189
  softwareIdentity: m.softwareIdentity ?? "",
175
190
  softwareRuleId: m.softwareRuleId ?? "",
176
- startedUnixMs: BigInt(m.startedUnixMs ?? 0),
177
- endedUnixMs: BigInt(m.endedUnixMs ?? 0),
191
+ startedUnixMs: big(m.startedUnixMs, "startedUnixMs"),
192
+ endedUnixMs: big(m.endedUnixMs, "endedUnixMs"),
178
193
  session: m.session ?? "",
179
- sequence: BigInt(m.sequence ?? 0),
194
+ sequence: big(m.sequence, "sequence"),
180
195
  previousSha256: m.previousSha256 ?? "",
181
196
  unanswered: m.unanswered ?? "",
182
197
  sha256: m.recordSha256 ?? "",
@@ -226,13 +241,16 @@ export function softwareRuleAllows(rule, identity) {
226
241
  return true;
227
242
  return identity !== "" && rule.identities.includes(identity);
228
243
  }
244
+ // The tiers, weakest first, as client.ts's TIERS (which imports this module).
245
+ const TIER_ORDER = ["none", "process", "container", "kernel", "vm"];
229
246
  /**
230
247
  * Checks the record the daemon sends with an unanswered session call's error
231
248
  * (record.CheckUnanswered): version 3, no result digest, a Connect code, the digest of
232
- * the request sent, its software rule, its own digest, and its place in the chain.
249
+ * the request sent, its software rule and that its software is in it, its own digest,
250
+ * its tier against the call's floor, and its place in the chain.
233
251
  * Returns the reason it does not check, or the record.
234
252
  */
235
- export function checkUnanswered(reqDigest, rule, m, fingerprint, prevSeq, prev) {
253
+ export function checkUnanswered(reqDigest, floor, rule, m, fingerprint, prevSeq, prev) {
236
254
  const r = recordFromWire(m);
237
255
  if (r.version !== UNANSWERED_RECORD_VERSION)
238
256
  return { problem: `an unanswered call's record is version ${r.version}` };
@@ -240,10 +258,14 @@ export function checkUnanswered(reqDigest, rule, m, fingerprint, prevSeq, prev)
240
258
  return { problem: "an unanswered call's record states a result or no error code" };
241
259
  if (r.requestSha256 !== reqDigest)
242
260
  return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
243
- if (r.softwareRuleId !== softwareRuleId(rule))
244
- return { problem: "the record's software rule is not the request's" };
261
+ if (r.softwareRuleId !== softwareRuleId(rule) || !softwareRuleAllows(rule, r.softwareIdentity)) {
262
+ return { problem: "the record's software rule is not the request's, or its software is not in it" };
263
+ }
245
264
  if (r.sha256 !== recordDigest(r))
246
265
  return { problem: `record digest ${r.sha256}, its fields digest to ${recordDigest(r)}` };
266
+ if (floor !== "" && !(TIER_ORDER.indexOf(r.isolation) >= TIER_ORDER.indexOf(floor) && TIER_ORDER.indexOf(r.isolation) >= 0)) {
267
+ return { problem: `the unanswered call's record states ${r.isolation || "unknown"}, below the call's minimum ${floor}; execution may have occurred` };
268
+ }
247
269
  if (r.session !== fingerprint || r.sequence !== prevSeq + 1n || r.previousSha256 !== prev) {
248
270
  return { problem: `the session's chain is broken: call ${r.sequence} after "${r.previousSha256}", this client's last was call ${prevSeq}, "${prev}"` };
249
271
  }
@@ -265,6 +287,8 @@ export function checkRecord(reqDigest, protocol, rule, resp) {
265
287
  return { problem: `protocol ${protocol} requires record version ${RECORD_VERSION}` };
266
288
  if (r.version === 1 && (r.softwareIdentity !== "" || r.softwareRuleId !== ""))
267
289
  return { problem: "a version 1 record cannot carry software fields" };
290
+ if (r.unanswered !== "")
291
+ return { problem: `an answered call's record states an unanswered code, which version ${r.version} does not cover` };
268
292
  if (r.requestSha256 !== reqDigest)
269
293
  return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
270
294
  if (r.resultSha256 !== result)
package/dist/sandboxes.js CHANGED
@@ -51,25 +51,25 @@ export const RUNNERS = {
51
51
  path: ".plimsoll/run.py",
52
52
  file: ".plimsoll/cell.py",
53
53
  step: "python3 -I .plimsoll/run.py",
54
+ // As the session kernel runs a cell: at module level, an event loop only for code
55
+ // that awaits at the top level, so the cell's own asyncio.run works.
54
56
  source: [
55
- "import ast, asyncio, inspect, sys",
57
+ "import ast, asyncio, inspect, linecache, sys",
56
58
  "sys.path.insert(0, '')",
57
59
  "src = open('.plimsoll/cell.py').read()",
60
+ "linecache.cache['cell'] = (len(src), None, src.splitlines(True), 'cell')",
58
61
  "tree = ast.parse(src, 'cell', 'exec')",
59
62
  "last = ast.Expression(tree.body.pop().value) if tree.body and isinstance(tree.body[-1], ast.Expr) else None",
60
- "ns = {'__name__': '__main__'}",
63
+ "ns = {'__name__': '__main__', '__builtins__': __builtins__}",
61
64
  "flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT",
62
- "async def main():",
63
- " r = eval(compile(tree, 'cell', 'exec', flags=flags), ns)",
64
- " if inspect.iscoroutine(r):",
65
- " await r",
66
- " if last is not None:",
67
- " value = eval(compile(last, 'cell', 'eval', flags=flags), ns)",
68
- " if inspect.iscoroutine(value):",
69
- " value = await value",
70
- " if value is not None:",
71
- " print(repr(value))",
72
- "asyncio.run(main())",
65
+ "loop = asyncio.new_event_loop()",
66
+ "def settle(r):",
67
+ " return loop.run_until_complete(r) if inspect.isawaitable(r) else r",
68
+ "settle(eval(compile(tree, 'cell', 'exec', flags=flags), ns))",
69
+ "if last is not None:",
70
+ " value = settle(eval(compile(last, 'cell', 'eval', flags=flags), ns))",
71
+ " if value is not None:",
72
+ " print(repr(value))",
73
73
  "",
74
74
  ].join("\n"),
75
75
  },
@@ -79,7 +79,10 @@ export const RUNNERS = {
79
79
  step: "node --expose-internals .plimsoll/run.cjs",
80
80
  source: [
81
81
  "const fs = require('node:fs'), util = require('node:util'), vm = require('node:vm');",
82
+ // The names a cell in the session's `node -e` interpreter sees as globals.
82
83
  "globalThis.require = require('node:module').createRequire(process.cwd() + '/');",
84
+ "globalThis.module = { exports: {} }; globalThis.exports = globalThis.module.exports;",
85
+ "globalThis.__dirname = '.'; globalThis.__filename = '[eval]';",
83
86
  "let tla = null;",
84
87
  "try { tla = require('internal/repl/await').processTopLevelAwait; } catch {}",
85
88
  "const src = fs.readFileSync('.plimsoll/cell.js', 'utf8');",
@@ -143,6 +146,14 @@ export class CodeSandboxes {
143
146
  }
144
147
  /** Runs one call of the tool under the key. */
145
148
  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
+ });
156
+ }
146
157
  const language = input.language ?? this.languages[0];
147
158
  if (!this.languages.includes(language)) {
148
159
  throw new PlimsollError("invalid_argument", `plimsoll: this tool runs ${this.languages.join(" or ")}, not ${language}`, { notDispatched: "request" });
@@ -171,8 +182,10 @@ export class CodeSandboxes {
171
182
  let session;
172
183
  try {
173
184
  session = await entry.session;
174
- const first = !entry.answered;
175
185
  const r = await session.runCell({ language, code: input.code, files }, opts);
186
+ // Read once the call has answered: the session runs its calls in order, so of
187
+ // calls made at once only the first to answer finds the sandbox new.
188
+ const first = !entry.answered;
176
189
  entry.answered = true;
177
190
  // What the call defined, and the files it wrote, can be there for the next call
178
191
  // only if its interpreter, and the sandbox, outlived it; the next call's fresh
@@ -197,10 +210,11 @@ export class CodeSandboxes {
197
210
  this.#drop(key, session);
198
211
  continue;
199
212
  }
200
- // A call that may have run without an answer leaves the session unusable
201
- // (the Session refuses its later calls), so the next call opens a new
202
- // sandbox and says so with freshSandbox.
203
- if (session && !(e instanceof PlimsollError && e.notDispatched))
213
+ // A call that may have run without an answer this client could check leaves
214
+ // the session unusable (the Session refuses its later calls), so the next call
215
+ // opens a new sandbox and says so with freshSandbox. One whose record the
216
+ // Session checked and chained (e.record) leaves it usable, and so does a refusal.
217
+ if (session && (session.stopped !== undefined || session.ended !== undefined))
204
218
  this.#drop(key, session);
205
219
  throw e;
206
220
  }
package/dist/tool.js CHANGED
@@ -6,7 +6,7 @@ const NAMES = { python: "Python", javascript: "JavaScript (Node.js)" };
6
6
  /** The tool's description for the languages it offers. */
7
7
  export function executeCodeDescription(languages = DEFAULT_LANGUAGES) {
8
8
  const names = languages.map((l) => NAMES[l]).join(" or ");
9
- return (`Run ${names} in an isolated sandbox with no network access and return its exit code, stdout and stderr. ` +
9
+ 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
10
  "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
11
  "Within one conversation the sandbox usually keeps an interpreter per language between calls, so variables, functions, imports and loaded data " +
12
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 " +
package/dist/wire.d.ts CHANGED
@@ -153,6 +153,7 @@ export type WireDescribeResponse = {
153
153
  supportsSessions?: boolean;
154
154
  sessionLifetimeMs?: number;
155
155
  sessionIdleTimeoutMs?: number;
156
+ sessionEnvironment?: WirePayloadEnvironment;
156
157
  };
157
158
  export type WireOpenSessionRequest = {
158
159
  protocol: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plimsollmark/client",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "TypeScript client for plimsolld, with 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",
@@ -36,6 +36,9 @@
36
36
  "files": [
37
37
  "dist"
38
38
  ],
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
39
42
  "engines": {
40
43
  "node": ">=22.18"
41
44
  },
@@ -46,10 +49,10 @@
46
49
  "test": "cd ../.. && go test ./clients/typescript/"
47
50
  },
48
51
  "peerDependencies": {
49
- "@mastra/core": ">=1.0.0",
50
- "@trigger.dev/sdk": ">=4.5.0",
51
- "ai": ">=6.0.0",
52
- "zod": ">=3.25.0"
52
+ "@mastra/core": ">=1.0.0 <2",
53
+ "@trigger.dev/sdk": ">=4.5.0 <5",
54
+ "ai": ">=6.0.0 <8",
55
+ "zod": ">=3.25.0 <5"
53
56
  },
54
57
  "peerDependenciesMeta": {
55
58
  "@mastra/core": {