@plimsollmark/client 0.20.0 → 0.22.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
@@ -18,7 +18,11 @@ protocol over `fetch` and keeps the promises the Go client keeps:
18
18
  - in a **session** it tracks the chain of records, so a call made by anyone else who holds
19
19
  the session ID is caught at the next call, and at close;
20
20
  - an error says whether anything ran: `notDispatched` is set only when the daemon stated
21
- that nothing did, and only then is a retry safe.
21
+ that nothing did, and only then is a retry safe;
22
+ - every request carries a fresh `Plimsoll-Request-Id` and an answer counts only if it
23
+ carries the ID back: one that does not (another request's answer, served by an
24
+ intermediary, or a daemon older than protocol 3) has `answerNotBound` set and no
25
+ `notDispatched`, and a success of that kind is a `data_loss` error.
22
26
 
23
27
  The tier it reports is configuration and provider evidence, never runtime attestation
24
28
  (the README's provider table says what each tier means).
@@ -201,7 +205,12 @@ one user, or one app, from holding them all:
201
205
  A `warm` is a guess (Trigger.dev's recipe warms in every new run's `onTurnStart`, a chat the
202
206
  user opened and never typed in included), so it never closes a sandbox to make room: when
203
207
  either cap is reached it does nothing, and the conversation's first call opens its sandbox,
204
- closing the least recently used idle one as any call does.
208
+ closing the least recently used idle one as any call does. The daemon closes a session no
209
+ request has named by its first idle timeout (`SANDBOX_SESSION_IDLE`, default 5 minutes), since
210
+ that is what a session whose open answer was lost looks like; a warmed sandbox its
211
+ conversation does not use by then is closed that way, and the first call is refused with the
212
+ end `unclaimed` (not dispatched) and runs once more in a new sandbox, saying
213
+ `freshSandbox: true`.
205
214
 
206
215
  Both caps count what one process holds. A host that runs many processes (serverless
207
216
  functions, several Trigger.dev workers) keeps one count per process, so set the daemon's
@@ -227,6 +236,13 @@ The digest names that record; it is not a signature or a proof that the guest
227
236
  computed honestly. See the [Trigger.dev feature and deployment guide](https://github.com/plimsollmark/plimsoll/blob/main/docs/trigger-dev.md)
228
237
  for the three properties together.
229
238
 
239
+ The model sees only a run record's digest (`recordSha256`). The record itself, checked by
240
+ the client, goes to `onRecord(record, key)`, once for every call that ran: an answered call's,
241
+ and the version 3 record a session call that may have run carries on its error. That is where an
242
+ application keeps receipts (a store, or a signer such as plimsoll's `attest` harness); a refusal
243
+ calls nothing, since nothing ran. An `onRecord` that throws, or returns a promise that rejects, is
244
+ logged and never changes the result the model gets.
245
+
230
246
  Closing a sandbox checks the daemon's count of calls against the chain the client saw; a
231
247
  mismatch means the daemon counted a call the client has no answer for (one that ended in an
232
248
  abort, a timeout, a dropped connection or a proxy's error), or, if none did, that someone
@@ -313,7 +329,8 @@ set, caps the sandboxes one worker holds.
313
329
  What the hooks cannot cover: a run that dies without reaching `onChatSuspend` or
314
330
  `onComplete` (its process killed, a crash) leaves its sandbox open until the add-on's idle
315
331
  close (`idleCloseMs`, default 10 minutes) or, if the process is gone too, the daemon's own
316
- idle suspend and session lifetime (`SANDBOX_SESSION_IDLE`, `SANDBOX_SESSION_LIFETIME`). A
332
+ idle suspend and session lifetime (`SANDBOX_SESSION_IDLE`, `SANDBOX_SESSION_LIFETIME`); a
333
+ sandbox no call ever used is closed at the daemon's first idle timeout. A
317
334
  worker shutting down can close every sandbox it holds with `sandbox.sandboxes.disposeAll()`.
318
335
 
319
336
  ## Mastra
package/dist/client.d.ts CHANGED
@@ -2,7 +2,7 @@ import { type RunRecord } from "./record.ts";
2
2
  import { type SessionEnd } from "./errors.ts";
3
3
  import type { WireCellRun, WireEnvelope, WireOpenSessionResponse, WireSoftwareRule } from "./wire.ts";
4
4
  /** The wire protocol number this client speaks (protocol.Number in Go). */
5
- export declare const PROTOCOL = 2;
5
+ export declare const PROTOCOL = 3;
6
6
  /** How strong the boundary is, weakest first. */
7
7
  export type Isolation = "none" | "process" | "container" | "kernel" | "vm";
8
8
  /** Whether a tier the daemon reported meets a floor. An unknown tier meets nothing. */
package/dist/client.js CHANGED
@@ -4,12 +4,12 @@
4
4
  // checks every run record against what it sent and received, checks the
5
5
  // isolation evidence against the caller's floor, and tracks a session's chain of
6
6
  // records so a call it did not make is caught.
7
- import { createHash, createHmac } from "node:crypto";
7
+ import { createHash, createHmac, randomBytes } from "node:crypto";
8
8
  import { isIP } from "node:net";
9
9
  import { checkRecord, checkUnanswered, requestDigest, sessionFingerprint, softwareRuleAllows, } from "./record.js";
10
- import { errorFromWire, PlimsollError, sessionEndFromWire } from "./errors.js";
10
+ import { errorFromWire, NOT_DISPATCHED_HEADER, PlimsollError, REQUEST_ID_HEADER, sessionEndFromWire, unboundSuccess } from "./errors.js";
11
11
  /** The wire protocol number this client speaks (protocol.Number in Go). */
12
- export const PROTOCOL = 2;
12
+ export const PROTOCOL = 3;
13
13
  const SERVICE = "plimsoll.v1.SandboxService";
14
14
  // Above the largest legitimate project response, so a misbehaving daemon cannot
15
15
  // make the client buffer without bound (the Go client's maxResponseBytes).
@@ -225,6 +225,19 @@ function digestPayload(p) {
225
225
  return { kind: "cell", language: p.cell.language, code: p.cell.code, files: p.cell.files };
226
226
  return { kind: "project", grantProfile: p.project.grantProfile ?? "", files: p.project.files, steps: p.project.steps, artifacts: p.project.artifacts };
227
227
  }
228
+ // Only codes reproduced before any HTTP request was sent by Node's bundled fetch.
229
+ // No prefixes: other TLS errors can come from reading an answer after dispatch.
230
+ function fetchDidNotSend(error) {
231
+ const seen = new Set();
232
+ while (error !== null && typeof error === "object" && !seen.has(error)) {
233
+ seen.add(error);
234
+ const cause = error;
235
+ if (cause.code === "ECONNREFUSED" || cause.code === "ERR_SSL_WRONG_VERSION_NUMBER" || cause.code === "DEPTH_ZERO_SELF_SIGNED_CERT")
236
+ return true;
237
+ error = cause.cause;
238
+ }
239
+ return false;
240
+ }
228
241
  export class PlimsollClient {
229
242
  base;
230
243
  token;
@@ -251,7 +264,9 @@ export class PlimsollClient {
251
264
  if (signal?.aborted)
252
265
  throw new PlimsollError("canceled", `plimsoll: ${method} was canceled before it was sent`, { notDispatched: "request", cause: signal.reason });
253
266
  refuseIllFormed(body, "the request");
254
- const headers = { "Content-Type": "application/json", "Connect-Protocol-Version": "1" };
267
+ // A fresh ID per request; an answer counts only if it carries the ID back.
268
+ const requestId = randomBytes(16).toString("hex");
269
+ const headers = { "Content-Type": "application/json", "Connect-Protocol-Version": "1", [REQUEST_ID_HEADER]: requestId };
255
270
  if (this.token)
256
271
  headers["Authorization"] = `Bearer ${this.token}`;
257
272
  const deadline = AbortSignal.timeout(this.requestTimeoutMs);
@@ -272,7 +287,9 @@ export class PlimsollClient {
272
287
  res = await this.fetchImpl(`${this.base}/${SERVICE}/${method}`, { method: "POST", headers, body: JSON.stringify(body), signal: both, redirect: "manual" });
273
288
  }
274
289
  catch (e) {
275
- throw cut(e) ?? new PlimsollError("unavailable", `plimsoll: ${e.message}`, { cause: e });
290
+ throw cut(e) ?? new PlimsollError("unavailable", `plimsoll: ${e.message}`, {
291
+ cause: e, notDispatched: fetchDidNotSend(e) ? "environment" : undefined,
292
+ });
276
293
  }
277
294
  if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
278
295
  void res.body?.cancel().catch(() => undefined);
@@ -294,8 +311,15 @@ export class PlimsollClient {
294
311
  catch {
295
312
  parsed = undefined;
296
313
  }
314
+ // What an answer says about the call holds only for the request it answers: one
315
+ // without this request's ID (a daemon older than protocol 3, or an intermediary that
316
+ // served another request's answer or dropped the header) is believed in nothing.
317
+ // Two echoes come back joined, which never equals one ID.
318
+ const bound = res.headers.get(REQUEST_ID_HEADER) === requestId;
297
319
  if (!res.ok)
298
- throw errorFromWire(res.status, parsed);
320
+ throw errorFromWire(res.status, parsed, { bound, mark: res.headers.get(NOT_DISPATCHED_HEADER) });
321
+ if (!bound)
322
+ throw unboundSuccess(method);
299
323
  if (parsed === undefined || typeof parsed !== "object")
300
324
  throw new PlimsollError("internal", "plimsoll: the daemon's answer is not a JSON message");
301
325
  return parsed;
package/dist/errors.d.ts CHANGED
@@ -7,7 +7,7 @@ export type Refusal = "request" | "permission" | "protocol" | "unsupported" | "i
7
7
  * an end this client has no name for (a daemon newer than the client): the session
8
8
  * ended, for a reason it cannot name.
9
9
  */
10
- export type SessionEnd = "open" | "closed" | "expired" | "disk_exceeded" | "main_process_ended" | "boundary_failed" | "sandbox_changed" | "shutdown" | "replaced" | "not_found" | "unknown";
10
+ export type SessionEnd = "open" | "closed" | "expired" | "disk_exceeded" | "main_process_ended" | "boundary_failed" | "sandbox_changed" | "shutdown" | "replaced" | "not_found" | "unclaimed" | "unknown";
11
11
  /**
12
12
  * Connect's status codes, plus the two this client raises itself:
13
13
  * "data_loss" for an answer that does not check (the run may have executed),
@@ -44,6 +44,13 @@ export declare class PlimsollError extends Error {
44
44
  * UnansweredCallError.Record); undefined otherwise.
45
45
  */
46
46
  record: RunRecord | undefined;
47
+ /**
48
+ * True when the error comes from an answer that did not carry this request's
49
+ * Plimsoll-Request-Id back (Go: client.ErrAnswerNotBound): nothing it said about the
50
+ * call was believed, so it has no notDispatched, sessionEnded or unanswered. On a
51
+ * success the code is "data_loss": the call may have run.
52
+ */
53
+ readonly answerNotBound: boolean;
47
54
  constructor(code: Code, message: string, opts?: {
48
55
  notDispatched?: Refusal;
49
56
  sessionEnded?: {
@@ -52,8 +59,18 @@ export declare class PlimsollError extends Error {
52
59
  };
53
60
  result?: unknown;
54
61
  unanswered?: WireRecord;
62
+ answerNotBound?: boolean;
55
63
  cause?: unknown;
56
64
  });
57
65
  }
66
+ /** The request ID a client sends and the daemon echoes (Go: protocol.RequestIDHeader). */
67
+ export declare const REQUEST_ID_HEADER = "Plimsoll-Request-Id";
68
+ /** The daemon's mark on an answer written before any handler ran (Go: protocol.NotDispatchedHeader). */
69
+ export declare const NOT_DISPATCHED_HEADER = "Plimsoll-Not-Dispatched";
70
+ /** The error for a success answer that is not bound to its request: the call may have run. */
71
+ export declare function unboundSuccess(method: string): PlimsollError;
58
72
  export declare function sessionEndFromWire(v: string | number | undefined): SessionEnd;
59
- export declare function errorFromWire(httpStatus: number, body: WireError | undefined): PlimsollError;
73
+ export declare function errorFromWire(httpStatus: number, body: WireError | undefined, answer: {
74
+ bound: boolean;
75
+ mark?: string | null;
76
+ }): PlimsollError;
package/dist/errors.js CHANGED
@@ -29,6 +29,13 @@ export class PlimsollError extends Error {
29
29
  * UnansweredCallError.Record); undefined otherwise.
30
30
  */
31
31
  record;
32
+ /**
33
+ * True when the error comes from an answer that did not carry this request's
34
+ * Plimsoll-Request-Id back (Go: client.ErrAnswerNotBound): nothing it said about the
35
+ * call was believed, so it has no notDispatched, sessionEnded or unanswered. On a
36
+ * success the code is "data_loss": the call may have run.
37
+ */
38
+ answerNotBound;
32
39
  constructor(code, message, opts = {}) {
33
40
  super(message, opts.cause === undefined ? undefined : { cause: opts.cause });
34
41
  this.name = "PlimsollError";
@@ -37,8 +44,19 @@ export class PlimsollError extends Error {
37
44
  this.sessionEnded = opts.sessionEnded;
38
45
  this.result = opts.result;
39
46
  this.unanswered = opts.unanswered;
47
+ this.answerNotBound = opts.answerNotBound ?? false;
40
48
  }
41
49
  }
50
+ /** The request ID a client sends and the daemon echoes (Go: protocol.RequestIDHeader). */
51
+ export const REQUEST_ID_HEADER = "Plimsoll-Request-Id";
52
+ /** The daemon's mark on an answer written before any handler ran (Go: protocol.NotDispatchedHeader). */
53
+ export const NOT_DISPATCHED_HEADER = "Plimsoll-Not-Dispatched";
54
+ const NOT_BOUND = "the answer does not carry this request's Plimsoll-Request-Id back (a daemon older than protocol 3, or an intermediary " +
55
+ "that answered with another request's answer or dropped the header), so what it says about the call is ignored";
56
+ /** The error for a success answer that is not bound to its request: the call may have run. */
57
+ export function unboundSuccess(method) {
58
+ return new PlimsollError("data_loss", `plimsoll: ${method}: ${NOT_BOUND}; the call may have run`, { answerNotBound: true });
59
+ }
42
60
  const REFUSALS = ["unknown", "request", "permission", "protocol", "unsupported", "isolation", "capacity", "environment"];
43
61
  const SESSION_ENDS = [
44
62
  "open",
@@ -51,6 +69,7 @@ const SESSION_ENDS = [
51
69
  "shutdown",
52
70
  "replaced",
53
71
  "not_found",
72
+ "unclaimed",
54
73
  ];
55
74
  // Only an absent or unspecified end means open. Any other value says the session
56
75
  // ended, so one this client has no name for is "unknown", never "open": read as open,
@@ -187,10 +206,14 @@ const CODES = new Set([
187
206
  ]);
188
207
  // The body is whatever the daemon sent, so each field is used only in the shape Connect
189
208
  // gives it, and a code outside Connect's set is "unknown".
190
- export function errorFromWire(httpStatus, body) {
209
+ // An answer that is not bound to its request keeps only its code and message; a bound
210
+ // one without a NotDispatched detail is marked by the daemon's header (mark).
211
+ export function errorFromWire(httpStatus, body, answer) {
191
212
  const wire = body !== null && typeof body === "object" && !Array.isArray(body) ? body : undefined;
192
213
  const code = wire?.code === undefined ? httpStatusCode(httpStatus) : CODES.has(wire.code) ? wire.code : "unknown";
193
214
  const message = typeof wire?.message === "string" ? wire.message : `HTTP ${httpStatus}`;
215
+ if (!answer.bound)
216
+ return new PlimsollError(code, `${message} (${NOT_BOUND})`, { answerNotBound: true });
194
217
  let notDispatched;
195
218
  let sessionEnded;
196
219
  let unanswered;
@@ -214,6 +237,11 @@ export function errorFromWire(httpStatus, body) {
214
237
  // An undecodable detail states nothing; in particular not that nothing ran.
215
238
  }
216
239
  }
240
+ if (notDispatched === undefined && answer.mark) {
241
+ const named = REFUSALS.find((r) => r !== "unknown" && r === answer.mark);
242
+ if (named)
243
+ notDispatched = named;
244
+ }
217
245
  return new PlimsollError(code, message, { notDispatched, sessionEnded, unanswered: notDispatched ? undefined : unanswered });
218
246
  }
219
247
  // Connect's mapping for a response without a Connect error body.
@@ -1,4 +1,5 @@
1
1
  import { PlimsollClient, type Isolation, type Language } from "./client.ts";
2
+ import type { RunRecord } from "./record.ts";
2
3
  export type SessionMode = "auto" | "always" | "never";
3
4
  /** The languages a tool offers, the first being the default. */
4
5
  export type ToolLanguages = readonly [Language, ...Language[]];
@@ -76,6 +77,14 @@ export type CodeSandboxesOptions = {
76
77
  * rejects, is logged the same way; it never stops a close or the next open.
77
78
  */
78
79
  onCloseError?: (key: SandboxKey, err: unknown) => void;
80
+ /**
81
+ * Called with every run record this instance checked: an answered call's, and the one
82
+ * a session call that may have run carries on its error. The tool's result gives the
83
+ * model only the record's digest, so this is where an application keeps the receipt
84
+ * (a store, a signer). Never called for a refusal: nothing ran. A callback that
85
+ * throws, or returns a promise that rejects, is logged; it never changes the result.
86
+ */
87
+ onRecord?: (record: RunRecord, key: SandboxKey | undefined) => void | Promise<void>;
79
88
  };
80
89
  /** What the executeCode tool takes. */
81
90
  export type ExecuteCodeInput = {
package/dist/sandboxes.js CHANGED
@@ -305,7 +305,7 @@ export class CodeSandboxes {
305
305
  });
306
306
  const opts = { timeoutMs: this.#opts.timeoutMs, minimumIsolation: this.#floor, signal };
307
307
  if (key === undefined || !persistent) {
308
- return this.#fresh(info, language, input.code, files, opts);
308
+ return this.#fresh(key, info, language, input.code, files, opts);
309
309
  }
310
310
  let retried = false;
311
311
  for (;;) {
@@ -324,6 +324,7 @@ export class CodeSandboxes {
324
324
  session = await beforeDispatch(() => untilAborted(entry.session, signal));
325
325
  // From here the cell may have been sent: an unmarked error stays unmarked.
326
326
  const r = await session.runCell({ language, code: input.code, files }, opts);
327
+ this.#record(r.record, key);
327
328
  // Read once the call has answered: the session runs its calls in order, so of
328
329
  // calls made at once only the first to answer finds the sandbox new.
329
330
  const first = !entry.answered;
@@ -345,6 +346,8 @@ export class CodeSandboxes {
345
346
  };
346
347
  }
347
348
  catch (e) {
349
+ if (e instanceof PlimsollError && e.record)
350
+ this.#record(e.record, key);
348
351
  // Aborted while its sandbox opened: nothing was sent, and a sandbox no call has
349
352
  // used is not kept for a call that has gone (the open finishes, then closes).
350
353
  if (!session && signal?.aborted) {
@@ -400,7 +403,7 @@ export class CodeSandboxes {
400
403
  }
401
404
  // A fresh sandbox for one call: the files, the code and a runner that prints the
402
405
  // last expression, as one project.
403
- async #fresh(info, language, code, files, opts) {
406
+ async #fresh(key, info, language, code, files, opts) {
404
407
  if (!info.supportsProject) {
405
408
  // A snippet is all this daemon runs (wasm): JavaScript, without files.
406
409
  if (language !== "javascript") {
@@ -414,6 +417,7 @@ export class CodeSandboxes {
414
417
  });
415
418
  }
416
419
  const r = await this.client.runJavaScript(snippetRunner(code), opts);
420
+ this.#record(r.record, key);
417
421
  return {
418
422
  ...this.#cut(language, r.exitCode, r.timedOut, r.stdout, r.stderr, r.stdoutTruncated || r.stderrTruncated),
419
423
  stateKept: false,
@@ -427,6 +431,7 @@ export class CodeSandboxes {
427
431
  files: [...files, { path: runner.file, content: code }, { path: runner.path, content: runner.source }],
428
432
  steps: [runner.step],
429
433
  }, opts);
434
+ this.#record(r.record, key);
430
435
  const step = r.steps[0];
431
436
  if (!step) {
432
437
  // No step report: the outcome says what ended the run (a timeout, a lost report),
@@ -555,6 +560,20 @@ export class CodeSandboxes {
555
560
  callbackFailed(e);
556
561
  }
557
562
  }
563
+ // Never throws, for the same reason: a receipt store's failure must not turn a
564
+ // result the model should see into an error.
565
+ #record(record, key) {
566
+ const callback = this.#opts.onRecord;
567
+ if (!callback)
568
+ return;
569
+ const failed = (e) => console.warn(`plimsoll: onRecord failed for record ${record.sha256}:`, errorText(e));
570
+ try {
571
+ void Promise.resolve(callback(record, key)).catch(failed);
572
+ }
573
+ catch (e) {
574
+ failed(e);
575
+ }
576
+ }
558
577
  #touch(id) {
559
578
  const entry = this.#entries.get(id);
560
579
  const ms = this.#opts.idleCloseMs ?? 10 * 60_000;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plimsollmark/client",
3
- "version": "0.20.0",
3
+ "version": "0.22.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",