@plimsollmark/client 0.21.0 → 0.23.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
@@ -236,6 +236,13 @@ The digest names that record; it is not a signature or a proof that the guest
236
236
  computed honestly. See the [Trigger.dev feature and deployment guide](https://github.com/plimsollmark/plimsoll/blob/main/docs/trigger-dev.md)
237
237
  for the three properties together.
238
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 record a session call that may have run carries on its error (no result, the error's code). 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
+
239
246
  Closing a sandbox checks the daemon's count of calls against the chain the client saw; a
240
247
  mismatch means the daemon counted a call the client has no answer for (one that ended in an
241
248
  abort, a timeout, a dropped connection or a proxy's error), or, if none did, that someone
@@ -246,7 +253,7 @@ object for a pair). Without `onCloseError`, a `console.warn` names the key only
246
253
  another's, never by its IDs, because a key can hold a user's ID (an email address, in some
247
254
  apps). An `onCloseError` that throws, or returns a promise that rejects, is logged the same
248
255
  way: an app's reporting never stops a close, or the open that waited for one to make room. A call that may have run but ended in an error comes with its record
249
- (`PlimsollError.unanswered`, a version 3 record); the session checks it, hands it back as
256
+ (`PlimsollError.unanswered`, a record with no result and the error's code); the session checks it, hands it back as
250
257
  `PlimsollError.record`, keeps it in its chain and goes on, and so does the conversation's
251
258
  sandbox. A call whose answer never arrived carries none, so the client sends nothing more
252
259
  on that session (`Session.stopped` says why), and the conversation's next call opens a new
package/dist/client.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { type RunRecord } from "./record.ts";
2
+ import { LANGUAGES, OUTCOME_NAMES, TIERS } from "./tables.gen.ts";
2
3
  import { type SessionEnd } from "./errors.ts";
3
4
  import type { WireCellRun, WireEnvelope, WireOpenSessionResponse, WireSoftwareRule } from "./wire.ts";
4
5
  /** The wire protocol number this client speaks (protocol.Number in Go). */
5
- export declare const PROTOCOL = 3;
6
+ export declare const PROTOCOL = 4;
6
7
  /** How strong the boundary is, weakest first. */
7
- export type Isolation = "none" | "process" | "container" | "kernel" | "vm";
8
+ export type Isolation = (typeof TIERS)[number];
8
9
  /** Whether a tier the daemon reported meets a floor. An unknown tier meets nothing. */
9
10
  export declare function meets(actual: string, floor: Isolation): boolean;
10
11
  /** A caller's rule for the selected software: one exact identity, or 1 to 32 approved ones. */
@@ -23,7 +24,12 @@ export type ClientOptions = {
23
24
  javascriptGrantProfile?: string;
24
25
  /** Named server-side grant profile for projects. */
25
26
  projectGrantProfile?: string;
26
- /** A fetch implementation; defaults to the global one. */
27
+ /**
28
+ * A fetch implementation; defaults to the global one. It must not retry a request: a
29
+ * retried call can run twice. A failure through a fetch given here is never marked
30
+ * not dispatched, since its error describes only the last attempt it made, and an
31
+ * earlier one may have delivered the code.
32
+ */
27
33
  fetch?: typeof fetch;
28
34
  /**
29
35
  * Bounds each HTTP exchange, sending and reading the answer, in milliseconds.
@@ -48,6 +54,8 @@ export type Evidence = {
48
54
  isolation: string;
49
55
  softwareIdentity: string;
50
56
  environment: string;
57
+ /** The sandbox instance that ran it, as a typed reference (`k8s-pod-uid:` and a pod's UID), or "" when the provider names none. */
58
+ instance: string;
51
59
  durationMs: number;
52
60
  /** The checked run record. */
53
61
  record: RunRecord;
@@ -88,7 +96,7 @@ export type ProjectRequest = {
88
96
  /** Relative paths to capture and return. */
89
97
  artifacts?: string[];
90
98
  };
91
- export type ProjectOutcome = "unspecified" | "completed" | "setup_failed" | "timed_out" | "protocol_error";
99
+ export type ProjectOutcome = (typeof OUTCOME_NAMES)[number];
92
100
  export type StepResult = {
93
101
  command: string;
94
102
  stdout: string;
@@ -111,7 +119,7 @@ export type ProjectResult = Evidence & {
111
119
  advice: AdviceFinding[];
112
120
  };
113
121
  /** An interpreter language: a cell's, and one an environment states. */
114
- export type Language = "javascript" | "python";
122
+ export type Language = (typeof LANGUAGES)[number];
115
123
  /**
116
124
  * Where one payload kind runs. languages are the interpreters the daemon's startup
117
125
  * checks proved: what a project's steps can invoke, and in a session what a cell may use.
@@ -244,6 +252,7 @@ export declare class PlimsollClient {
244
252
  private readonly base;
245
253
  private readonly token;
246
254
  private readonly fetchImpl;
255
+ private readonly ownFetch;
247
256
  private readonly requestTimeoutMs;
248
257
  /** @internal */ readonly jsGrant: string;
249
258
  /** @internal */ readonly projectGrant: string;
package/dist/client.js CHANGED
@@ -7,14 +7,14 @@
7
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 { LANGUAGES, OUTCOME_NAMES, TIERS } from "./tables.gen.js";
10
11
  import { errorFromWire, NOT_DISPATCHED_HEADER, PlimsollError, REQUEST_ID_HEADER, sessionEndFromWire, unboundSuccess } from "./errors.js";
11
12
  /** The wire protocol number this client speaks (protocol.Number in Go). */
12
- export const PROTOCOL = 3;
13
+ export const PROTOCOL = 4;
13
14
  const SERVICE = "plimsoll.v1.SandboxService";
14
15
  // Above the largest legitimate project response, so a misbehaving daemon cannot
15
16
  // make the client buffer without bound (the Go client's maxResponseBytes).
16
17
  const MAX_RESPONSE_BYTES = 32 << 20;
17
- const TIERS = ["none", "process", "container", "kernel", "vm"];
18
18
  /** Whether a tier the daemon reported meets a floor. An unknown tier meets nothing. */
19
19
  export function meets(actual, floor) {
20
20
  const a = TIERS.indexOf(actual);
@@ -121,6 +121,7 @@ function evidence(resp, record) {
121
121
  isolation: resp.isolation ?? "",
122
122
  softwareIdentity: resp.softwareIdentity ?? "",
123
123
  environment: resp.environment ?? "",
124
+ instance: resp.instance ?? "",
124
125
  durationMs: num(resp.durationMs),
125
126
  record,
126
127
  };
@@ -143,11 +144,10 @@ function javascriptResult(resp, record) {
143
144
  };
144
145
  }
145
146
  function outcomeFromWire(v) {
146
- const names = ["unspecified", "completed", "setup_failed", "timed_out", "protocol_error"];
147
147
  if (typeof v === "number")
148
- return names[v] ?? "unspecified";
148
+ return OUTCOME_NAMES[v] ?? "unspecified";
149
149
  const name = (v ?? "").replace(/^PROJECT_OUTCOME_/, "").toLowerCase();
150
- return names.includes(name) ? name : "unspecified";
150
+ return OUTCOME_NAMES.includes(name) ? name : "unspecified";
151
151
  }
152
152
  function projectResult(resp, record) {
153
153
  const p = resp.project ?? {};
@@ -242,6 +242,9 @@ export class PlimsollClient {
242
242
  base;
243
243
  token;
244
244
  fetchImpl;
245
+ // Only Node's own fetch, which makes one attempt per POST, has errors that prove a
246
+ // request unsent.
247
+ ownFetch;
245
248
  requestTimeoutMs;
246
249
  /** @internal */ jsGrant;
247
250
  /** @internal */ projectGrant;
@@ -249,6 +252,7 @@ export class PlimsollClient {
249
252
  this.base = validateBaseUrl(opts.baseUrl, opts.insecureHttp ?? false);
250
253
  this.token = opts.token;
251
254
  this.fetchImpl = opts.fetch ?? fetch;
255
+ this.ownFetch = opts.fetch === undefined;
252
256
  const rt = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
253
257
  if (typeof rt !== "number" || !(rt > 0) || rt > 2 ** 31 - 1) {
254
258
  throw new PlimsollError("invalid_argument", "plimsoll: requestTimeoutMs must be a positive number of milliseconds");
@@ -288,7 +292,7 @@ export class PlimsollClient {
288
292
  }
289
293
  catch (e) {
290
294
  throw cut(e) ?? new PlimsollError("unavailable", `plimsoll: ${e.message}`, {
291
- cause: e, notDispatched: fetchDidNotSend(e) ? "environment" : undefined,
295
+ cause: e, notDispatched: this.ownFetch && fetchDidNotSend(e) ? "environment" : undefined,
292
296
  });
293
297
  }
294
298
  if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
@@ -433,7 +437,7 @@ export class PlimsollClient {
433
437
  return decoded(() => this.checked(env, payload, resp));
434
438
  }
435
439
  checked(env, payload, resp) {
436
- const checked = checkRecord(requestDigest({ protocol: env.protocol, minimumIsolation: env.minimumIsolation ?? "", timeoutMs: env.timeoutMs ?? 0, softwareRule: env.softwareRule, payload: digestPayload(payload) }), env.protocol, env.softwareRule, 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);
437
441
  if ("problem" in checked)
438
442
  throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { result: resp });
439
443
  const r = checked.record;
@@ -630,7 +634,7 @@ export class Session {
630
634
  const end = sessionEndFromWire(m.ended);
631
635
  if (end !== "open")
632
636
  this.#end = { reason: end, detail: m.endDetail ?? "" };
633
- const checked = checkRecord(digest, env.protocol, rule, run);
637
+ const checked = checkRecord(digest, rule, run);
634
638
  if ("problem" in checked)
635
639
  throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { result: run });
636
640
  const r = checked.record;
package/dist/errors.d.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  import type { RunRecord } from "./record.ts";
2
+ import { REFUSAL_NAMES, SESSION_END_NAMES } from "./tables.gen.ts";
2
3
  import type { WireError, WireRecord } from "./wire.ts";
3
4
  /** Why a request was refused before any code ran (plimsoll.v1.NotDispatchedReason). */
4
- export type Refusal = "request" | "permission" | "protocol" | "unsupported" | "isolation" | "capacity" | "environment" | "unknown";
5
+ export type Refusal = (typeof REFUSAL_NAMES)[number];
5
6
  /**
6
7
  * Why a session ended (plimsoll.v1.SessionEnd), "open" while it has not. "unknown" is
7
8
  * an end this client has no name for (a daemon newer than the client): the session
8
9
  * ended, for a reason it cannot name.
9
10
  */
10
- export type SessionEnd = "open" | "closed" | "expired" | "disk_exceeded" | "main_process_ended" | "boundary_failed" | "sandbox_changed" | "shutdown" | "replaced" | "not_found" | "unclaimed" | "unknown";
11
+ export type SessionEnd = (typeof SESSION_END_NAMES)[number] | "unknown";
11
12
  /**
12
13
  * Connect's status codes, plus the two this client raises itself:
13
14
  * "data_loss" for an answer that does not check (the run may have executed),
@@ -35,7 +36,7 @@ export declare class PlimsollError extends Error {
35
36
  readonly result: unknown;
36
37
  /**
37
38
  * The record the daemon sends with a session call that may have run but ended in
38
- * an error (a version 3 record, as it came off the wire). The Session checks it
39
+ * an error (an unanswered record, as it came off the wire). The Session checks it
39
40
  * and keeps it in its chain, so the session goes on; the call's outcome is unknown.
40
41
  */
41
42
  readonly unanswered: WireRecord | undefined;
package/dist/errors.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // anything ran. A refusal raised before dispatch carries the NotDispatched detail
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
+ import { REFUSAL_NAMES, SESSION_END_NAMES } from "./tables.gen.js";
5
6
  export class PlimsollError extends Error {
6
7
  code;
7
8
  /**
@@ -20,7 +21,7 @@ export class PlimsollError extends Error {
20
21
  result;
21
22
  /**
22
23
  * The record the daemon sends with a session call that may have run but ended in
23
- * an error (a version 3 record, as it came off the wire). The Session checks it
24
+ * an error (an unanswered record, as it came off the wire). The Session checks it
24
25
  * and keeps it in its chain, so the session goes on; the call's outcome is unknown.
25
26
  */
26
27
  unanswered;
@@ -57,20 +58,6 @@ const NOT_BOUND = "the answer does not carry this request's Plimsoll-Request-Id
57
58
  export function unboundSuccess(method) {
58
59
  return new PlimsollError("data_loss", `plimsoll: ${method}: ${NOT_BOUND}; the call may have run`, { answerNotBound: true });
59
60
  }
60
- const REFUSALS = ["unknown", "request", "permission", "protocol", "unsupported", "isolation", "capacity", "environment"];
61
- const SESSION_ENDS = [
62
- "open",
63
- "closed",
64
- "expired",
65
- "disk_exceeded",
66
- "main_process_ended",
67
- "boundary_failed",
68
- "sandbox_changed",
69
- "shutdown",
70
- "replaced",
71
- "not_found",
72
- "unclaimed",
73
- ];
74
61
  // Only an absent or unspecified end means open. Any other value says the session
75
62
  // ended, so one this client has no name for is "unknown", never "open": read as open,
76
63
  // an ended session would be reported as still holding its state and files. The
@@ -79,11 +66,11 @@ export function sessionEndFromWire(v) {
79
66
  if (v === undefined || v === 0)
80
67
  return "open";
81
68
  if (typeof v === "number")
82
- return SESSION_ENDS[v] ?? "unknown";
69
+ return SESSION_END_NAMES[v] ?? "unknown";
83
70
  const name = v.replace(/^SESSION_END_/, "").toLowerCase();
84
71
  if (name === "unspecified")
85
72
  return "open";
86
- return name !== "open" && name !== "unknown" && SESSION_ENDS.includes(name) ? name : "unknown";
73
+ return name !== "open" && name !== "unknown" && SESSION_END_NAMES.includes(name) ? name : "unknown";
87
74
  }
88
75
  // Reads one varint at b[i]; returns [value, next index].
89
76
  function varint(b, i) {
@@ -122,6 +109,14 @@ function decodeDetail(b) {
122
109
  detail = Buffer.from(b.subarray(k, k + n)).toString("utf8");
123
110
  i = k + n;
124
111
  }
112
+ else if (wire === 1 || wire === 5) {
113
+ // A fixed-width field this client does not know is skipped, as Go and Python skip
114
+ // it, so a newer daemon's extra field does not cost a refusal its mark (review B8,
115
+ // 2026-10-23).
116
+ i += wire === 1 ? 8 : 4;
117
+ if (i > b.length)
118
+ throw new Error("bad length");
119
+ }
125
120
  else {
126
121
  throw new Error("unexpected wire type");
127
122
  }
@@ -142,7 +137,7 @@ function bigVarint(b, i) {
142
137
  }
143
138
  const RECORD_STRINGS = {
144
139
  2: "requestSha256", 3: "resultSha256", 4: "provider", 5: "isolation", 6: "environment", 7: "policy",
145
- 10: "session", 12: "previousSha256", 13: "recordSha256", 14: "softwareIdentity", 15: "softwareRuleId", 16: "unanswered",
140
+ 10: "session", 12: "previousSha256", 13: "recordSha256", 14: "softwareIdentity", 15: "softwareRuleId", 16: "unanswered", 17: "instance",
146
141
  };
147
142
  // Decodes an UnansweredCall detail (field 1, a RunRecord) by hand, into the record's
148
143
  // proto3 JSON form, so the record checks exactly as one read off a JSON answer.
@@ -221,7 +216,7 @@ export function errorFromWire(httpStatus, body, answer) {
221
216
  try {
222
217
  const bytes = Buffer.from(d.value ?? "", "base64");
223
218
  if (d.type === "plimsoll.v1.NotDispatched") {
224
- notDispatched = REFUSALS[decodeDetail(bytes).reason] ?? "unknown";
219
+ notDispatched = REFUSAL_NAMES[decodeDetail(bytes).reason] ?? "unknown";
225
220
  }
226
221
  else if (d.type === "plimsoll.v1.SessionEnded") {
227
222
  // The detail itself says the session ended, so an unspecified reason is not "open".
@@ -238,7 +233,7 @@ export function errorFromWire(httpStatus, body, answer) {
238
233
  }
239
234
  }
240
235
  if (notDispatched === undefined && answer.mark) {
241
- const named = REFUSALS.find((r) => r !== "unknown" && r === answer.mark);
236
+ const named = REFUSAL_NAMES.find((r) => r !== "unknown" && r === answer.mark);
242
237
  if (named)
243
238
  notDispatched = named;
244
239
  }
package/dist/record.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import type { WireRecord, WireRunResponse, WireSoftwareRule } from "./wire.ts";
2
- /** The record encoding version of an answered call, which this client computes and checks. */
3
- export declare const RECORD_VERSION = 2;
4
- /** The record encoding version of a session call that may have run but ended in an error. */
5
- export declare const UNANSWERED_RECORD_VERSION = 3;
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
+ export declare const RECORD_VERSION = 4;
4
+ /** A record's instance: "" (the provider names none) or a typed reference such as `k8s-pod-uid:` and a pod's UID. */
5
+ export declare function validInstance(s: string): boolean;
6
6
  /** The payload of a request as the digest sees it. */
7
7
  export type DigestPayload = {
8
8
  kind: "javascript";
@@ -55,12 +55,14 @@ export type RunRecord = {
55
55
  session: string;
56
56
  sequence: bigint;
57
57
  previousSha256: string;
58
- /** On a version 3 record, the Connect code a session call that may have run ended with. */
58
+ /** On an unanswered call's record, the Connect code a session call that may have run ended with. */
59
59
  unanswered: string;
60
+ /** The sandbox instance that ran the call, as the response states it, or "". */
61
+ instance: string;
60
62
  sha256: string;
61
63
  };
62
64
  export declare function recordFromWire(m: WireRecord): RunRecord;
63
- /** A record's own digest, over every field but its digest. */
65
+ /** A record's own digest, over the fields its version covers (every field but its digest for an unknown version). */
64
66
  export declare function recordDigest(r: RunRecord): string;
65
67
  /** The SHA-256 of a session ID: what a session call's record carries instead of the ID. */
66
68
  export declare function sessionFingerprint(sessionId: string): string;
@@ -72,7 +74,7 @@ export declare function softwareRuleId(rule: WireSoftwareRule | undefined): stri
72
74
  export declare function softwareRuleAllows(rule: WireSoftwareRule | undefined, identity: string): boolean;
73
75
  /**
74
76
  * Checks the record the daemon sends with an unanswered session call's error
75
- * (record.CheckUnanswered): version 3, no result digest, a Connect code, the digest of
77
+ * (record.CheckUnanswered): the version, no result digest, a Connect code, the digest of
76
78
  * the request sent, its software rule and that its software is in it, its own digest,
77
79
  * its tier against the call's floor, and its place in the chain.
78
80
  * Returns the reason it does not check, or the record.
@@ -87,7 +89,7 @@ export declare function checkUnanswered(reqDigest: string, floor: string, rule:
87
89
  * both digests, the evidence the response repeats, the software rule and the
88
90
  * record's own digest. Returns the reason it does not check, or undefined.
89
91
  */
90
- export declare function checkRecord(reqDigest: string, protocol: number, rule: WireSoftwareRule | undefined, resp: WireRunResponse): {
92
+ export declare function checkRecord(reqDigest: string, rule: WireSoftwareRule | undefined, resp: WireRunResponse): {
91
93
  record: RunRecord;
92
94
  } | {
93
95
  problem: string;
package/dist/record.js CHANGED
@@ -3,10 +3,14 @@
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
5
  import { PlimsollError } from "./errors.js";
6
- /** The record encoding version of an answered call, which this client computes and checks. */
7
- export const RECORD_VERSION = 2;
8
- /** The record encoding version of a session call that may have run but ended in an error. */
9
- export const UNANSWERED_RECORD_VERSION = 3;
6
+ import { OUTCOMES, TIERS } from "./tables.gen.js";
7
+ /** The record encoding version this client computes and checks: every field, every time, for an answered call and an unanswered session call alike. */
8
+ export const RECORD_VERSION = 4;
9
+ const INSTANCE_FORM = /^[a-z][a-z0-9-]{0,31}:[A-Za-z0-9._:-]{1,127}$/;
10
+ /** A record's instance: "" (the provider names none) or a typed reference such as `k8s-pod-uid:` and a pod's UID. */
11
+ export function validInstance(s) {
12
+ return s === "" || INSTANCE_FORM.test(s);
13
+ }
10
14
  const UNANSWERED_CODES = new Set([
11
15
  "canceled", "unknown", "invalid_argument", "deadline_exceeded", "not_found", "already_exists", "permission_denied",
12
16
  "resource_exhausted", "failed_precondition", "aborted", "out_of_range", "unimplemented", "internal", "unavailable",
@@ -53,11 +57,13 @@ class Encoder {
53
57
  }
54
58
  /** The request digest of a Run request or a session call (the same fields). */
55
59
  export function requestDigest(r) {
56
- const e = new Encoder(r.protocol >= 2 ? "plimsoll.run-request.v2" : "plimsoll.run-request.v1");
60
+ // A protocol 1 request (the records of version 1) has the first encoding: no software rule.
61
+ const first = r.protocol < 2;
62
+ const e = new Encoder(first ? "plimsoll.run-request.v1" : "plimsoll.run-request.v2");
57
63
  e.int("protocol", r.protocol);
58
64
  e.str("minimum_isolation", r.minimumIsolation);
59
65
  e.int("timeout_ms", r.timeoutMs);
60
- if (r.protocol >= 2) {
66
+ if (!first) {
61
67
  const ids = r.softwareRule?.identities ?? [];
62
68
  e.str("software_mode", r.softwareRule?.mode ?? "");
63
69
  e.int("software_identities", ids.length);
@@ -95,20 +101,22 @@ export function requestDigest(r) {
95
101
  }
96
102
  return e.sum();
97
103
  }
98
- const OUTCOME_NUMBERS = {
99
- PROJECT_OUTCOME_UNSPECIFIED: 0,
100
- PROJECT_OUTCOME_COMPLETED: 1,
101
- PROJECT_OUTCOME_SETUP_FAILED: 2,
102
- PROJECT_OUTCOME_TIMED_OUT: 3,
103
- PROJECT_OUTCOME_PROTOCOL_ERROR: 4,
104
- };
104
+ /**
105
+ * Why a live answer's record version is refused: a newer daemon (upgrade the client) or an
106
+ * older one. A live answer must carry the current version; it is never called forged.
107
+ */
108
+ function versionProblem(version) {
109
+ return version > RECORD_VERSION
110
+ ? `a newer daemon answered with run record version ${version}; this client reads version ${RECORD_VERSION}: upgrade the client`
111
+ : `the daemon answered with run record version ${version}; this client requires version ${RECORD_VERSION} of a live answer`;
112
+ }
105
113
  /** The wire enum's number; an unknown name is undefined, which fails the check. */
106
114
  export function outcomeNumber(name) {
107
115
  if (name === undefined)
108
116
  return 0;
109
117
  if (typeof name === "number")
110
118
  return name;
111
- return OUTCOME_NUMBERS[name];
119
+ return OUTCOMES[name];
112
120
  }
113
121
  const b64 = (s) => Buffer.from(s ?? "", "base64");
114
122
  /** The result digest of a Run response as it arrived on the wire. */
@@ -194,31 +202,59 @@ export function recordFromWire(m) {
194
202
  sequence: big(m.sequence, "sequence"),
195
203
  previousSha256: m.previousSha256 ?? "",
196
204
  unanswered: m.unanswered ?? "",
205
+ instance: m.instance ?? "",
197
206
  sha256: m.recordSha256 ?? "",
198
207
  };
199
208
  }
200
- /** A record's own digest, over every field but its digest. */
209
+ /** A record's own digest, over the fields its version covers (every field but its digest for an unknown version). */
201
210
  export function recordDigest(r) {
202
211
  const e = new Encoder(`plimsoll.run-record.v${r.version}`);
203
- e.str("request_sha256", r.requestSha256);
204
- e.str("result_sha256", r.resultSha256);
205
- if (r.version >= 3)
206
- e.str("unanswered", r.unanswered);
207
- e.str("provider", r.provider);
208
- e.str("isolation", r.isolation);
209
- e.str("environment", r.environment);
210
- e.str("policy", r.policy);
211
- if (r.version >= 2) {
212
- e.str("software_identity", r.softwareIdentity);
213
- e.str("software_rule_id", r.softwareRuleId);
212
+ for (const name of RECORD_FIELDS[r.version] ?? RECORD_FIELDS[RECORD_VERSION]) {
213
+ const v = recordField(r, name);
214
+ if (typeof v === "string")
215
+ e.str(name, v);
216
+ else
217
+ e.int(name, v);
214
218
  }
215
- e.int("started_unix_ms", r.startedUnixMs);
216
- e.int("ended_unix_ms", r.endedUnixMs);
217
- e.str("session", r.session);
218
- e.int("sequence", r.sequence);
219
- e.str("previous_sha256", r.previousSha256);
220
219
  return e.sum();
221
220
  }
221
+ /**
222
+ * The fields of each published record version's digest, in order (record.published): a
223
+ * version leaves this table only by a dated, announced decision.
224
+ */
225
+ const RECORD_FIELDS = {
226
+ 1: ["request_sha256", "result_sha256", "provider", "isolation", "environment", "policy",
227
+ "started_unix_ms", "ended_unix_ms", "session", "sequence", "previous_sha256"],
228
+ 2: ["request_sha256", "result_sha256", "provider", "isolation", "environment", "policy",
229
+ "software_identity", "software_rule_id", "started_unix_ms", "ended_unix_ms", "session", "sequence",
230
+ "previous_sha256"],
231
+ 3: ["request_sha256", "result_sha256", "unanswered", "provider", "isolation", "environment", "policy",
232
+ "software_identity", "software_rule_id", "started_unix_ms", "ended_unix_ms", "session", "sequence",
233
+ "previous_sha256"],
234
+ 4: ["request_sha256", "result_sha256", "unanswered", "provider", "isolation", "environment", "policy",
235
+ "software_identity", "software_rule_id", "instance", "started_unix_ms", "ended_unix_ms", "session",
236
+ "sequence", "previous_sha256"],
237
+ };
238
+ function recordField(r, name) {
239
+ switch (name) {
240
+ case "request_sha256": return r.requestSha256;
241
+ case "result_sha256": return r.resultSha256;
242
+ case "unanswered": return r.unanswered;
243
+ case "provider": return r.provider;
244
+ case "isolation": return r.isolation;
245
+ case "environment": return r.environment;
246
+ case "policy": return r.policy;
247
+ case "software_identity": return r.softwareIdentity;
248
+ case "software_rule_id": return r.softwareRuleId;
249
+ case "instance": return r.instance;
250
+ case "started_unix_ms": return r.startedUnixMs;
251
+ case "ended_unix_ms": return r.endedUnixMs;
252
+ case "session": return r.session;
253
+ case "sequence": return r.sequence;
254
+ case "previous_sha256": return r.previousSha256;
255
+ }
256
+ throw new Error(`no record field ${name}`);
257
+ }
222
258
  /** The SHA-256 of a session ID: what a session call's record carries instead of the ID. */
223
259
  export function sessionFingerprint(sessionId) {
224
260
  return createHash("sha256").update(sessionId, "utf8").digest("hex");
@@ -241,19 +277,21 @@ export function softwareRuleAllows(rule, identity) {
241
277
  return true;
242
278
  return identity !== "" && rule.identities.includes(identity);
243
279
  }
244
- // The tiers, weakest first, as client.ts's TIERS (which imports this module).
245
- const TIER_ORDER = ["none", "process", "container", "kernel", "vm"];
280
+ // The tiers, weakest first (generated, internal/wiretables).
281
+ const TIER_ORDER = TIERS;
246
282
  /**
247
283
  * Checks the record the daemon sends with an unanswered session call's error
248
- * (record.CheckUnanswered): version 3, no result digest, a Connect code, the digest of
284
+ * (record.CheckUnanswered): the version, no result digest, a Connect code, the digest of
249
285
  * the request sent, its software rule and that its software is in it, its own digest,
250
286
  * its tier against the call's floor, and its place in the chain.
251
287
  * Returns the reason it does not check, or the record.
252
288
  */
253
289
  export function checkUnanswered(reqDigest, floor, rule, m, fingerprint, prevSeq, prev) {
254
290
  const r = recordFromWire(m);
255
- if (r.version !== UNANSWERED_RECORD_VERSION)
256
- return { problem: `an unanswered call's record is version ${r.version}` };
291
+ if (r.version !== RECORD_VERSION)
292
+ return { problem: versionProblem(r.version) };
293
+ if (!validInstance(r.instance))
294
+ return { problem: "the record's instance is not a typed reference" };
257
295
  if (r.resultSha256 !== "" || !UNANSWERED_CODES.has(r.unanswered))
258
296
  return { problem: "an unanswered call's record states a result or no error code" };
259
297
  if (r.requestSha256 !== reqDigest)
@@ -276,29 +314,27 @@ export function checkUnanswered(reqDigest, floor, rule, m, fingerprint, prevSeq,
276
314
  * both digests, the evidence the response repeats, the software rule and the
277
315
  * record's own digest. Returns the reason it does not check, or undefined.
278
316
  */
279
- export function checkRecord(reqDigest, protocol, rule, resp) {
317
+ export function checkRecord(reqDigest, rule, resp) {
280
318
  if (!resp.record)
281
319
  return { problem: "the response carries no run record" };
282
320
  const r = recordFromWire(resp.record);
283
321
  const result = resultDigest(resp);
284
- if (r.version !== 1 && r.version !== RECORD_VERSION)
285
- return { problem: `unknown run record version ${r.version}` };
286
- if (protocol >= 2 && r.version !== RECORD_VERSION)
287
- return { problem: `protocol ${protocol} requires record version ${RECORD_VERSION}` };
288
- if (r.version === 1 && (r.softwareIdentity !== "" || r.softwareRuleId !== ""))
289
- return { problem: "a version 1 record cannot carry software fields" };
322
+ if (r.version !== RECORD_VERSION)
323
+ return { problem: versionProblem(r.version) };
290
324
  if (r.unanswered !== "")
291
- return { problem: `an answered call's record states an unanswered code, which version ${r.version} does not cover` };
325
+ return { problem: "an answered call's record states an unanswered code" };
292
326
  if (r.requestSha256 !== reqDigest)
293
327
  return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
294
328
  if (r.resultSha256 !== result)
295
329
  return { problem: `result digest ${r.resultSha256}, the result received digests to ${result}` };
296
330
  if (r.provider !== (resp.sandbox ?? "") || r.isolation !== (resp.isolation ?? ""))
297
331
  return { problem: "the record's provider or tier differs from the response's" };
298
- if (r.version >= 2 && r.environment !== (resp.environment ?? ""))
332
+ if (r.environment !== (resp.environment ?? ""))
299
333
  return { problem: "the record's environment differs from the response's" };
300
- if (r.version >= 2 &&
301
- (r.softwareIdentity !== (resp.softwareIdentity ?? "") || r.softwareRuleId !== softwareRuleId(rule) || !softwareRuleAllows(rule, r.softwareIdentity))) {
334
+ if (r.instance !== (resp.instance ?? "") || !validInstance(r.instance)) {
335
+ return { problem: "the record's instance is not the response's, or not a typed reference" };
336
+ }
337
+ if ((r.softwareIdentity !== (resp.softwareIdentity ?? "") || r.softwareRuleId !== softwareRuleId(rule) || !softwareRuleAllows(rule, r.softwareIdentity))) {
302
338
  return { problem: "the selected software or admission rule differs from the request and response" };
303
339
  }
304
340
  if (r.sha256 !== recordDigest(r))
@@ -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
@@ -291,21 +291,24 @@ export class CodeSandboxes {
291
291
  // The Describe is shared with other calls, so an abort stops this call's wait for
292
292
  // it, not the Describe.
293
293
  const info = await untilAborted(this.#describe(), signal);
294
- const proved = info.environments.project.languages;
295
- // A daemon that states no languages predates the statement: let it try.
296
- if (proved.length > 0 && !proved.includes(language)) {
297
- throw new PlimsollError("unimplemented", `plimsoll: the sandbox image has no ${language} interpreter (it runs ${proved.join(", ")})`, {
298
- notDispatched: "unsupported",
299
- });
300
- }
301
294
  // Without a key there is no conversation to scope a sandbox to, and sharing
302
295
  // one across conversations would hand one user's files to another.
303
296
  const persistent = key !== undefined && (await untilAborted(this.persistent(), signal));
297
+ // The languages proved where this call will run: the session's image for a kept
298
+ // sandbox, the project image otherwise (a daemon with neither runs JavaScript
299
+ // snippets, which #fresh checks). Every daemon states them (protocol 4), so one that
300
+ // states none proved none and is refused, never let try (review B9, 2026-10-23).
301
+ const env = persistent ? info.sessionEnvironment : info.supportsProject ? info.environments.project : undefined;
302
+ if (env && !env.languages.includes(language)) {
303
+ throw new PlimsollError("unimplemented", `plimsoll: the sandbox image has no ${language} interpreter (it runs ${env.languages.join(", ") || "none"})`, {
304
+ notDispatched: "unsupported",
305
+ });
306
+ }
304
307
  return { key, id, info, language, files, persistent };
305
308
  });
306
309
  const opts = { timeoutMs: this.#opts.timeoutMs, minimumIsolation: this.#floor, signal };
307
310
  if (key === undefined || !persistent) {
308
- return this.#fresh(info, language, input.code, files, opts);
311
+ return this.#fresh(key, info, language, input.code, files, opts);
309
312
  }
310
313
  let retried = false;
311
314
  for (;;) {
@@ -324,6 +327,7 @@ export class CodeSandboxes {
324
327
  session = await beforeDispatch(() => untilAborted(entry.session, signal));
325
328
  // From here the cell may have been sent: an unmarked error stays unmarked.
326
329
  const r = await session.runCell({ language, code: input.code, files }, opts);
330
+ this.#record(r.record, key);
327
331
  // Read once the call has answered: the session runs its calls in order, so of
328
332
  // calls made at once only the first to answer finds the sandbox new.
329
333
  const first = !entry.answered;
@@ -345,6 +349,8 @@ export class CodeSandboxes {
345
349
  };
346
350
  }
347
351
  catch (e) {
352
+ if (e instanceof PlimsollError && e.record)
353
+ this.#record(e.record, key);
348
354
  // Aborted while its sandbox opened: nothing was sent, and a sandbox no call has
349
355
  // used is not kept for a call that has gone (the open finishes, then closes).
350
356
  if (!session && signal?.aborted) {
@@ -400,7 +406,7 @@ export class CodeSandboxes {
400
406
  }
401
407
  // A fresh sandbox for one call: the files, the code and a runner that prints the
402
408
  // last expression, as one project.
403
- async #fresh(info, language, code, files, opts) {
409
+ async #fresh(key, info, language, code, files, opts) {
404
410
  if (!info.supportsProject) {
405
411
  // A snippet is all this daemon runs (wasm): JavaScript, without files.
406
412
  if (language !== "javascript") {
@@ -414,6 +420,7 @@ export class CodeSandboxes {
414
420
  });
415
421
  }
416
422
  const r = await this.client.runJavaScript(snippetRunner(code), opts);
423
+ this.#record(r.record, key);
417
424
  return {
418
425
  ...this.#cut(language, r.exitCode, r.timedOut, r.stdout, r.stderr, r.stdoutTruncated || r.stderrTruncated),
419
426
  stateKept: false,
@@ -427,6 +434,7 @@ export class CodeSandboxes {
427
434
  files: [...files, { path: runner.file, content: code }, { path: runner.path, content: runner.source }],
428
435
  steps: [runner.step],
429
436
  }, opts);
437
+ this.#record(r.record, key);
430
438
  const step = r.steps[0];
431
439
  if (!step) {
432
440
  // No step report: the outcome says what ended the run (a timeout, a lost report),
@@ -555,6 +563,20 @@ export class CodeSandboxes {
555
563
  callbackFailed(e);
556
564
  }
557
565
  }
566
+ // Never throws, for the same reason: a receipt store's failure must not turn a
567
+ // result the model should see into an error.
568
+ #record(record, key) {
569
+ const callback = this.#opts.onRecord;
570
+ if (!callback)
571
+ return;
572
+ const failed = (e) => console.warn(`plimsoll: onRecord failed for record ${record.sha256}:`, errorText(e));
573
+ try {
574
+ void Promise.resolve(callback(record, key)).catch(failed);
575
+ }
576
+ catch (e) {
577
+ failed(e);
578
+ }
579
+ }
558
580
  #touch(id) {
559
581
  const entry = this.#entries.get(id);
560
582
  const ms = this.#opts.idleCloseMs ?? 10 * 60_000;
@@ -0,0 +1,13 @@
1
+ /** plimsoll.v1.ProjectOutcome, by number. */
2
+ export declare const OUTCOMES: Readonly<Record<string, number>>;
3
+ export declare const OUTCOME_NAMES: readonly ["unspecified", "completed", "setup_failed", "timed_out", "protocol_error", "runner_failed"];
4
+ /** plimsoll.v1.SessionEnd, by number. */
5
+ export declare const SESSION_ENDS: Readonly<Record<string, number>>;
6
+ export declare const SESSION_END_NAMES: readonly ["open", "closed", "expired", "disk_exceeded", "main_process_ended", "boundary_failed", "sandbox_changed", "shutdown", "replaced", "not_found", "unclaimed"];
7
+ /** plimsoll.v1.NotDispatchedReason, by number. */
8
+ export declare const REFUSALS: Readonly<Record<string, number>>;
9
+ export declare const REFUSAL_NAMES: readonly ["unknown", "request", "permission", "protocol", "unsupported", "isolation", "capacity", "environment"];
10
+ /** Isolation tiers, weakest first (sandbox.IsolationClass). */
11
+ export declare const TIERS: readonly ["none", "process", "container", "kernel", "vm"];
12
+ /** The languages plimsoll keeps an interpreter for (sandbox.Languages). */
13
+ export declare const LANGUAGES: readonly ["javascript", "python"];
@@ -0,0 +1,44 @@
1
+ // Code generated by internal/wiretables (make generate). DO NOT EDIT.
2
+ // The protocol's enums and plimsoll's named values, from proto/plimsoll/v1/sandbox.proto
3
+ // and package sandbox, so this client and the Go and Python ones cannot drift apart.
4
+ /** plimsoll.v1.ProjectOutcome, by number. */
5
+ export const OUTCOMES = {
6
+ PROJECT_OUTCOME_UNSPECIFIED: 0,
7
+ PROJECT_OUTCOME_COMPLETED: 1,
8
+ PROJECT_OUTCOME_SETUP_FAILED: 2,
9
+ PROJECT_OUTCOME_TIMED_OUT: 3,
10
+ PROJECT_OUTCOME_PROTOCOL_ERROR: 4,
11
+ PROJECT_OUTCOME_RUNNER_FAILED: 5,
12
+ };
13
+ export const OUTCOME_NAMES = ["unspecified", "completed", "setup_failed", "timed_out", "protocol_error", "runner_failed"];
14
+ /** plimsoll.v1.SessionEnd, by number. */
15
+ export const SESSION_ENDS = {
16
+ SESSION_END_UNSPECIFIED: 0,
17
+ SESSION_END_CLOSED: 1,
18
+ SESSION_END_EXPIRED: 2,
19
+ SESSION_END_DISK_EXCEEDED: 3,
20
+ SESSION_END_MAIN_PROCESS_ENDED: 4,
21
+ SESSION_END_BOUNDARY_FAILED: 5,
22
+ SESSION_END_SANDBOX_CHANGED: 6,
23
+ SESSION_END_SHUTDOWN: 7,
24
+ SESSION_END_REPLACED: 8,
25
+ SESSION_END_NOT_FOUND: 9,
26
+ SESSION_END_UNCLAIMED: 10,
27
+ };
28
+ export const SESSION_END_NAMES = ["open", "closed", "expired", "disk_exceeded", "main_process_ended", "boundary_failed", "sandbox_changed", "shutdown", "replaced", "not_found", "unclaimed"];
29
+ /** plimsoll.v1.NotDispatchedReason, by number. */
30
+ export const REFUSALS = {
31
+ NOT_DISPATCHED_REASON_UNSPECIFIED: 0,
32
+ NOT_DISPATCHED_REASON_REQUEST: 1,
33
+ NOT_DISPATCHED_REASON_PERMISSION: 2,
34
+ NOT_DISPATCHED_REASON_PROTOCOL: 3,
35
+ NOT_DISPATCHED_REASON_UNSUPPORTED: 4,
36
+ NOT_DISPATCHED_REASON_ISOLATION: 5,
37
+ NOT_DISPATCHED_REASON_CAPACITY: 6,
38
+ NOT_DISPATCHED_REASON_ENVIRONMENT: 7,
39
+ };
40
+ export const REFUSAL_NAMES = ["unknown", "request", "permission", "protocol", "unsupported", "isolation", "capacity", "environment"];
41
+ /** Isolation tiers, weakest first (sandbox.IsolationClass). */
42
+ export const TIERS = ["none", "process", "container", "kernel", "vm"];
43
+ /** The languages plimsoll keeps an interpreter for (sandbox.Languages). */
44
+ export const LANGUAGES = ["javascript", "python"];
package/dist/wire.d.ts CHANGED
@@ -54,6 +54,7 @@ export type WireRecord = {
54
54
  unanswered?: string;
55
55
  softwareIdentity?: string;
56
56
  softwareRuleId?: string;
57
+ instance?: string;
57
58
  recordSha256?: string;
58
59
  };
59
60
  export type WireAdvice = {
@@ -116,6 +117,7 @@ export type WireRunResponse = {
116
117
  record?: WireRecord;
117
118
  softwareIdentity?: string;
118
119
  environment?: string;
120
+ instance?: string;
119
121
  javascript?: WireJavaScriptResult;
120
122
  project?: WireProjectResult;
121
123
  module?: unknown;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plimsollmark/client",
3
- "version": "0.21.0",
3
+ "version": "0.23.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",