@plimsollmark/client 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
@@ -313,7 +322,8 @@ set, caps the sandboxes one worker holds.
313
322
  What the hooks cannot cover: a run that dies without reaching `onChatSuspend` or
314
323
  `onComplete` (its process killed, a crash) leaves its sandbox open until the add-on's idle
315
324
  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
325
+ idle suspend and session lifetime (`SANDBOX_SESSION_IDLE`, `SANDBOX_SESSION_LIFETIME`); a
326
+ sandbox no call ever used is closed at the daemon's first idle timeout. A
317
327
  worker shutting down can close every sandbox it holds with `sandbox.sandboxes.disposeAll()`.
318
328
 
319
329
  ## 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plimsollmark/client",
3
- "version": "0.20.0",
3
+ "version": "0.21.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",