@plimsollmark/client 0.27.2 → 0.28.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/dist/record.js CHANGED
@@ -3,20 +3,52 @@
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
- import { OUTCOMES, TIERS } from "./tables.gen.js";
6
+ // The record's version (the one this client computes and checks: every field, every time,
7
+ // for an answered call and an unanswered session call alike), its layouts and bounds,
8
+ // generated from the Go record and sandbox packages.
9
+ import { DAEMON_VERSION_PATTERN, INSTANCE_PATTERN, LAST_WALL_CLOCK_END_VERSION, MAX_DAEMON_VERSION_BYTES, MAX_QUALIFICATION_BYTES, OUTCOMES, QUALIFICATION_FORBIDDEN, RECORD_FIELDS, RECORD_VERSION, RETIRED_END_BEFORE_START_TEXT, TIERS, UNANSWERED_CODES as UNANSWERED_CODE_LIST, } from "./tables.gen.js";
7
10
  import { wireBytes, WireShapeError } from "./wire.js";
8
- /** The record encoding version this client computes and checks: every field, every time, for an answered call and an unanswered session call alike. */
9
- export const RECORD_VERSION = 4;
10
- const INSTANCE_FORM = /^[a-z][a-z0-9-]{0,31}:[A-Za-z0-9._:-]{1,127}$/;
11
+ const INSTANCE_FORM = new RegExp(INSTANCE_PATTERN);
11
12
  /** A record's instance: "" (the provider names none) or a typed reference such as `k8s-pod-uid:` and a pod's UID. */
12
13
  export function validInstance(s) {
13
14
  return s === "" || INSTANCE_FORM.test(s);
14
15
  }
15
- const UNANSWERED_CODES = new Set([
16
- "canceled", "unknown", "invalid_argument", "deadline_exceeded", "not_found", "already_exists", "permission_denied",
17
- "resource_exhausted", "failed_precondition", "aborted", "out_of_range", "unimplemented", "internal", "unavailable",
18
- "data_loss", "unauthenticated",
19
- ]);
16
+ // A control character, or a format character that breaks a line or shows text in another
17
+ // order than it is stored (record.ValidText), from the generated ranges: the one set every
18
+ // field a reader is shown is held to (the table's name is the qualification's, the first
19
+ // field it was written for).
20
+ const hex = (c) => `\\u{${c.toString(16)}}`;
21
+ const FORBIDDEN_IN_TEXT = new RegExp(`[${QUALIFICATION_FORBIDDEN.map(([lo, hi]) => `${hex(lo)}-${hex(hi)}`).join("")}]`, "u");
22
+ /**
23
+ * Text a record may state where a reader is shown it as it is: UTF-8 with no control
24
+ * character and none of the format characters that break a line or reorder displayed text,
25
+ * as record.ValidText. A lone surrogate is not UTF-8. The provider's name, the tier and the
26
+ * isolation qualification are held to it (shownFields).
27
+ */
28
+ export function validText(s) {
29
+ return !/\p{Cs}/u.test(s) && !FORBIDDEN_IN_TEXT.test(s);
30
+ }
31
+ /** A record's fields a reader is shown as the run's evidence, each with the name a refusal gives it, as record.ShownFields. */
32
+ export function shownFields(r) {
33
+ return [["provider", r.provider], ["isolation", r.isolation], ["isolation qualification", r.isolationQualification]];
34
+ }
35
+ /**
36
+ * A record's isolation qualification: "" (the provider states none), or at most
37
+ * MAX_QUALIFICATION_BYTES of UTF-8 that validText accepts, as record.ValidQualification.
38
+ */
39
+ export function validQualification(s) {
40
+ return validText(s) && Buffer.byteLength(s, "utf8") <= MAX_QUALIFICATION_BYTES;
41
+ }
42
+ const DAEMON_VERSION_FORM = new RegExp(DAEMON_VERSION_PATTERN);
43
+ /**
44
+ * A record's daemon version: "", "(devel)", or a module version such as "v0.28.0" or a
45
+ * pseudo-version, at most MAX_DAEMON_VERSION_BYTES (the grammar is ASCII, so characters are
46
+ * bytes), as record.ValidDaemonVersion.
47
+ */
48
+ export function validDaemonVersion(s) {
49
+ return s === "" || (s.length <= MAX_DAEMON_VERSION_BYTES && DAEMON_VERSION_FORM.test(s));
50
+ }
51
+ const UNANSWERED_CODES = new Set(UNANSWERED_CODE_LIST);
20
52
  class Encoder {
21
53
  h = createHash("sha256");
22
54
  constructor(domain) {
@@ -187,25 +219,45 @@ function big(v, name) {
187
219
  return BigInt(v);
188
220
  throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not an integer`);
189
221
  }
222
+ // text and flag read a record field the JSON codec sends as a string or a boolean: absent is "" or false, and any
223
+ // other JSON type is an answer this client cannot read, a PlimsollError (Go's protojson and Python's typed reads
224
+ // refuse the same), never a TypeError later or a value coerced to the right type.
225
+ function text(v, name) {
226
+ if (v === undefined || v === null)
227
+ return "";
228
+ if (typeof v !== "string")
229
+ throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not text`);
230
+ return v;
231
+ }
232
+ function flag(v, name) {
233
+ if (v === undefined || v === null)
234
+ return false;
235
+ if (typeof v !== "boolean")
236
+ throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not a boolean`);
237
+ return v;
238
+ }
190
239
  export function recordFromWire(m) {
191
240
  return {
192
241
  version: m.version ?? 0,
193
- requestSha256: m.requestSha256 ?? "",
194
- resultSha256: m.resultSha256 ?? "",
195
- provider: m.provider ?? "",
196
- isolation: m.isolation ?? "",
197
- environment: m.environment ?? "",
198
- policy: m.policy ?? "",
199
- softwareIdentity: m.softwareIdentity ?? "",
200
- softwareRuleId: m.softwareRuleId ?? "",
242
+ requestSha256: text(m.requestSha256, "requestSha256"),
243
+ resultSha256: text(m.resultSha256, "resultSha256"),
244
+ provider: text(m.provider, "provider"),
245
+ isolation: text(m.isolation, "isolation"),
246
+ environment: text(m.environment, "environment"),
247
+ policy: text(m.policy, "policy"),
248
+ softwareIdentity: text(m.softwareIdentity, "softwareIdentity"),
249
+ softwareRuleId: text(m.softwareRuleId, "softwareRuleId"),
201
250
  startedUnixMs: big(m.startedUnixMs, "startedUnixMs"),
202
251
  endedUnixMs: big(m.endedUnixMs, "endedUnixMs"),
203
- session: m.session ?? "",
252
+ session: text(m.session, "session"),
204
253
  sequence: big(m.sequence, "sequence"),
205
- previousSha256: m.previousSha256 ?? "",
206
- unanswered: m.unanswered ?? "",
207
- instance: m.instance ?? "",
208
- sha256: m.recordSha256 ?? "",
254
+ previousSha256: text(m.previousSha256, "previousSha256"),
255
+ unanswered: text(m.unanswered, "unanswered"),
256
+ instance: text(m.instance, "instance"),
257
+ isolationQualification: text(m.isolationQualification, "isolationQualification"),
258
+ warm: flag(m.warm, "warm"),
259
+ daemonVersion: text(m.daemonVersion, "daemonVersion"),
260
+ sha256: text(m.recordSha256, "recordSha256"),
209
261
  };
210
262
  }
211
263
  /** A record's own digest, over the fields its version covers (every field but its digest for an unknown version). */
@@ -215,28 +267,54 @@ export function recordDigest(r) {
215
267
  const v = recordField(r, name);
216
268
  if (typeof v === "string")
217
269
  e.str(name, v);
270
+ else if (typeof v === "boolean")
271
+ e.bool(name, v);
218
272
  else
219
273
  e.int(name, v);
220
274
  }
221
275
  return e.sum();
222
276
  }
223
277
  /**
224
- * The fields of each published record version's digest, in order (record.published): a
225
- * version leaves this table only by a dated, announced decision.
278
+ * The fields a record's version does not cover are unset, it states a result digest or,
279
+ * for an unanswered call, an error code, exactly one, and the code is one of the closed
280
+ * set, its tier is one of TIERS (never "unknown" or empty, whatever floor the request
281
+ * named), it does not end before it starts, answered or not, its qualification and daemon
282
+ * version are in their bounds, and its instance is a typed reference (record.statesOnly).
283
+ * The record of a call lost across a takeover is checked by this alone.
284
+ * Returns the reason it fails, or undefined.
226
285
  */
227
- const RECORD_FIELDS = {
228
- 1: ["request_sha256", "result_sha256", "provider", "isolation", "environment", "policy",
229
- "started_unix_ms", "ended_unix_ms", "session", "sequence", "previous_sha256"],
230
- 2: ["request_sha256", "result_sha256", "provider", "isolation", "environment", "policy",
231
- "software_identity", "software_rule_id", "started_unix_ms", "ended_unix_ms", "session", "sequence",
232
- "previous_sha256"],
233
- 3: ["request_sha256", "result_sha256", "unanswered", "provider", "isolation", "environment", "policy",
234
- "software_identity", "software_rule_id", "started_unix_ms", "ended_unix_ms", "session", "sequence",
235
- "previous_sha256"],
236
- 4: ["request_sha256", "result_sha256", "unanswered", "provider", "isolation", "environment", "policy",
237
- "software_identity", "software_rule_id", "instance", "started_unix_ms", "ended_unix_ms", "session",
238
- "sequence", "previous_sha256"],
239
- };
286
+ export function statesOnlyProblem(r) {
287
+ for (const [name, text] of shownFields(r)) {
288
+ if (typeof text !== "string" || !validText(text))
289
+ return `the record's ${name} is not UTF-8 or holds a control or bidirectional format character`;
290
+ }
291
+ const covered = RECORD_FIELDS[r.version] ?? [];
292
+ for (const name of RECORD_FIELDS[RECORD_VERSION]) {
293
+ const v = recordField(r, name);
294
+ if (!covered.includes(name) && v !== "" && v !== false && v !== 0n)
295
+ return `a version ${r.version} record does not cover ${name}, so it cannot state one`;
296
+ }
297
+ const unanswered = r.unanswered !== "";
298
+ if (unanswered === (r.resultSha256 !== ""))
299
+ return "a record states a result or, for an unanswered call, an error code, exactly one";
300
+ if (unanswered && !UNANSWERED_CODES.has(r.unanswered))
301
+ return `an unanswered call's record names ${JSON.stringify(r.unanswered)}, not a Connect code`;
302
+ if (!TIERS.includes(r.isolation))
303
+ return `the record's isolation ${JSON.stringify(r.isolation)} is not a tier (${TIERS.join(", ")})`;
304
+ // A version 1 or 2 record that ends before it starts is refused as a retired reading, not
305
+ // as a forgery (record.LastWallClockEndVersion, retired 2026-11-21).
306
+ if (r.endedUnixMs < r.startedUnixMs && r.version <= LAST_WALL_CLOCK_END_VERSION)
307
+ return RETIRED_END_BEFORE_START_TEXT;
308
+ if (r.endedUnixMs < r.startedUnixMs)
309
+ return "the record ends before it starts";
310
+ if (!validInstance(r.instance))
311
+ return "the record's instance is not a typed reference";
312
+ if (!validQualification(r.isolationQualification))
313
+ return `the record's isolation qualification is over ${MAX_QUALIFICATION_BYTES} bytes`;
314
+ if (!validDaemonVersion(r.daemonVersion))
315
+ return `the record's daemon version ${JSON.stringify(r.daemonVersion)} is not a module version or (devel)`;
316
+ return undefined;
317
+ }
240
318
  function recordField(r, name) {
241
319
  switch (name) {
242
320
  case "request_sha256": return r.requestSha256;
@@ -249,6 +327,9 @@ function recordField(r, name) {
249
327
  case "software_identity": return r.softwareIdentity;
250
328
  case "software_rule_id": return r.softwareRuleId;
251
329
  case "instance": return r.instance;
330
+ case "isolation_qualification": return r.isolationQualification;
331
+ case "warm": return r.warm;
332
+ case "daemon_version": return r.daemonVersion;
252
333
  case "started_unix_ms": return r.startedUnixMs;
253
334
  case "ended_unix_ms": return r.endedUnixMs;
254
335
  case "session": return r.session;
@@ -292,8 +373,9 @@ export function checkUnanswered(reqDigest, floor, rule, m, fingerprint, prevSeq,
292
373
  const r = recordFromWire(m);
293
374
  if (r.version !== RECORD_VERSION)
294
375
  return { problem: versionProblem(r.version) };
295
- if (!validInstance(r.instance))
296
- return { problem: "the record's instance is not a typed reference" };
376
+ const bounds = statesOnlyProblem(r);
377
+ if (bounds !== undefined)
378
+ return { problem: bounds };
297
379
  if (r.resultSha256 !== "" || !UNANSWERED_CODES.has(r.unanswered))
298
380
  return { problem: "an unanswered call's record states a result or no error code" };
299
381
  if (r.requestSha256 !== reqDigest)
@@ -341,8 +423,6 @@ export function checkRecord(reqDigest, kind, rule, resp) {
341
423
  return { problem: `the answer holds ${kinds.length} results; a run has one` };
342
424
  if (kinds.length !== 1 || kinds[0] !== kind)
343
425
  return { problem: `the daemon answered a ${kind} request with ${kinds.length === 1 ? kinds[0] : "no"} result` };
344
- if (r.endedUnixMs < r.startedUnixMs)
345
- return { problem: "the record ends before it starts" };
346
426
  if (r.requestSha256 !== reqDigest)
347
427
  return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
348
428
  if (r.resultSha256 !== result)
@@ -354,6 +434,15 @@ export function checkRecord(reqDigest, kind, rule, resp) {
354
434
  if (r.instance !== (resp.instance ?? "") || !validInstance(r.instance)) {
355
435
  return { problem: "the record's instance is not the response's, or not a typed reference" };
356
436
  }
437
+ if (r.isolationQualification !== (resp.isolationQualification ?? ""))
438
+ return { problem: "the record's isolation qualification is not the response's" };
439
+ if (r.warm !== (resp.warm ?? false))
440
+ return { problem: `the record states warm ${r.warm}, the response ${resp.warm ?? false}` };
441
+ if (r.daemonVersion !== (resp.daemonVersion ?? ""))
442
+ return { problem: "the record's daemon version is not the response's" };
443
+ const bounds = statesOnlyProblem(r);
444
+ if (bounds !== undefined)
445
+ return { problem: bounds };
357
446
  if ((r.softwareIdentity !== (resp.softwareIdentity ?? "") || r.softwareRuleId !== softwareRuleId(rule) || !softwareRuleAllows(rule, r.softwareIdentity))) {
358
447
  return { problem: "the selected software or admission rule differs from the request and response" };
359
448
  }
@@ -86,6 +86,43 @@ export type CodeSandboxesOptions = {
86
86
  */
87
87
  onRecord?: (record: RunRecord, key: SandboxKey | undefined) => void | Promise<void>;
88
88
  };
89
+ /**
90
+ * The grant a tool's every call carries, chosen by the application, never by a model's
91
+ * tool call: the name of a grant profile the operator configured on the daemon
92
+ * (PLIMSOLL_GRANTS_FILE), and the description of its API that plimsoll-specgen wrote for
93
+ * that profile (-emit description), which the tool shows its model.
94
+ */
95
+ export type ToolGrant = {
96
+ profile: string;
97
+ apiDescription: string;
98
+ };
99
+ /** The most characters of an API description a tool takes: it travels in every model request (about 8,000 tokens). */
100
+ export declare const MAX_API_DESCRIPTION_CHARS = 32000;
101
+ /**
102
+ * What the daemon's Describe said a granted tool can do, read once when the tool is
103
+ * built: the languages whose code can call the API there (JavaScript wherever a granted
104
+ * project or snippet runs; Python too where every project step gets the broker's socket,
105
+ * PYTHON_GRANT_PROVIDERS), and whether calls run as snippets (a daemon without projects).
106
+ */
107
+ export type GrantPlan = ToolGrant & {
108
+ provider: string;
109
+ languages: Language[];
110
+ snippets: boolean;
111
+ };
112
+ /** Said after a granted call that may have run. */
113
+ export declare const GRANTED_MAY_HAVE_RUN = "It may have called the API too, as many times as the run's call budget allows; it was not retried.";
114
+ /** Said after a granted call's permission refusal: the daemon's words name the profile; these say whose it is to fix. */
115
+ export declare const GRANT_PERMISSION_NOTE: string;
116
+ /** Why code in language cannot call the API on the daemon plan describes, and what to write instead. */
117
+ export declare function grantRefusal(plan: GrantPlan, language: Language): string;
118
+ /**
119
+ * The languages a granted tool offers: the application's, less those whose code cannot
120
+ * call the API on the daemon plan describes, so the model is never offered a language
121
+ * that would be refused. None of them left is the application's mistake, said at once.
122
+ */
123
+ export declare function offeredForGrant(languages: ToolLanguages, plan: GrantPlan): ToolLanguages;
124
+ /** Refuses a grant given to a tool factory that keeps state; the granted one is named. */
125
+ export declare function refuseGrant(opts: object, granted: string): void;
89
126
  /** What the executeCode tool takes. */
90
127
  export type ExecuteCodeInput = {
91
128
  code: string;
@@ -130,12 +167,33 @@ export type ExecuteCodeOutput = {
130
167
  freshSandbox?: true;
131
168
  /** The tier the code ran behind: configuration and provider evidence, not attestation. */
132
169
  isolation: string;
170
+ /**
171
+ * The sentence the provider states beside that tier, present only when it states one (only
172
+ * WSL runs so far: Microsoft's statement that WSL is not a security sandbox for running
173
+ * untrusted code). The record the client checked states it too.
174
+ */
175
+ isolationQualification?: string;
133
176
  /** SHA-256 of the run record checked by the client before this result was returned. */
134
177
  recordSha256: string;
135
178
  };
136
179
  export declare class CodeSandboxes {
137
180
  #private;
138
- constructor(opts: CodeSandboxesOptions);
181
+ /**
182
+ * With grant, every call carries it, and so runs in a sandbox of its own, never in a
183
+ * kept one (a session's interpreter outlives the call, and its code with it): the
184
+ * sandboxes are never opened, and sessions "always" is refused here.
185
+ */
186
+ constructor(opts: CodeSandboxesOptions & {
187
+ grant?: ToolGrant;
188
+ });
189
+ /** The grant every call carries, or undefined. */
190
+ get grant(): ToolGrant | undefined;
191
+ /**
192
+ * What the daemon's Describe says this instance's grant can do: which languages' code
193
+ * can call the API, and whether calls run as snippets. Throws, marked not dispatched,
194
+ * reason unsupported, when the daemon cannot carry the grant at all.
195
+ */
196
+ grantPlan(signal?: AbortSignal): Promise<GrantPlan>;
139
197
  get client(): PlimsollClient;
140
198
  /** The languages the tool offers, the first being the default. */
141
199
  get languages(): ToolLanguages;
package/dist/sandboxes.js CHANGED
@@ -38,6 +38,7 @@
38
38
  import { createHash } from "node:crypto";
39
39
  import { PlimsollClient } from "./client.js";
40
40
  import { PlimsollError } from "./errors.js";
41
+ import { GRANTED_CELL, PYTHON_GRANT_PROVIDERS, SNIPPET_CELL } from "./granted.gen.js";
41
42
  export const DEFAULT_LANGUAGES = ["python", "javascript"];
42
43
  // One string per key: JSON keeps a pair from aliasing another pair, or a string key,
43
44
  // as a separator could.
@@ -102,15 +103,111 @@ function untilAborted(p, signal) {
102
103
  export function keyDigest(key) {
103
104
  return createHash("sha256").update(keyId(key), "utf8").digest("hex").slice(0, 12);
104
105
  }
106
+ /** The most characters of an API description a tool takes: it travels in every model request (about 8,000 tokens). */
107
+ export const MAX_API_DESCRIPTION_CHARS = 32_000;
108
+ const LANGUAGE_NAMES = { python: "Python", javascript: "JavaScript" };
109
+ /** Said after a granted call that may have run. */
110
+ export const GRANTED_MAY_HAVE_RUN = "It may have called the API too, as many times as the run's call budget allows; it was not retried.";
111
+ /** Said after a granted call's permission refusal: the daemon's words name the profile; these say whose it is to fix. */
112
+ export const GRANT_PERMISSION_NOTE = "The API this tool is set up to call is not available to it, so nothing ran: the grant profile is unknown to the daemon, or this caller is not on it. " +
113
+ "That is the operator's to fix; do not retry, and tell the user the API could not be reached.";
114
+ /** Why code in language cannot call the API on the daemon plan describes, and what to write instead. */
115
+ export function grantRefusal(plan, language) {
116
+ const others = plan.languages.map((l) => LANGUAGE_NAMES[l]);
117
+ const instead = others.length ? ` Write the program in ${others.join(" or ")}.` : "";
118
+ const why = language === "python"
119
+ ? plan.snippets
120
+ ? `the daemon (provider ${plan.provider}) runs JavaScript snippets only`
121
+ : `its provider (${plan.provider}) gives a Python step no way to reach plimsoll's broker`
122
+ : `the daemon's project image (provider ${plan.provider}) states no ${LANGUAGE_NAMES[language]} interpreter`;
123
+ return `plimsoll: ${LANGUAGE_NAMES[language]} code cannot call the API on this sandbox: ${why}; nothing ran.${instead}`;
124
+ }
125
+ /**
126
+ * The languages a granted tool offers: the application's, less those whose code cannot
127
+ * call the API on the daemon plan describes, so the model is never offered a language
128
+ * that would be refused. None of them left is the application's mistake, said at once.
129
+ */
130
+ export function offeredForGrant(languages, plan) {
131
+ const kept = languages.filter((l) => plan.languages.includes(l));
132
+ if (kept.length === 0) {
133
+ throw new PlimsollError("invalid_argument", `plimsoll: this tool's code is to call the API of grant profile ${JSON.stringify(plan.profile)}, and on this daemon none of ${languages.join(", ")} can: ${grantRefusal(plan, languages[0])}`, { notDispatched: "request" });
134
+ }
135
+ return kept;
136
+ }
137
+ /** Refuses a grant given to a tool factory that keeps state; the granted one is named. */
138
+ export function refuseGrant(opts, granted) {
139
+ if (opts.grant !== undefined) {
140
+ throw new PlimsollError("invalid_argument", `plimsoll: this tool keeps state between calls, which a granted call cannot have; build a granted tool with ${granted}`, {
141
+ notDispatched: "request",
142
+ });
143
+ }
144
+ }
145
+ function grantPlanOf(grant, info) {
146
+ const noRun = (why) => new PlimsollError("unimplemented", `plimsoll: ${why}, so no call of this tool can carry grant profile ${JSON.stringify(grant.profile)}; nothing ran`, {
147
+ notDispatched: "unsupported",
148
+ });
149
+ if (!info.supportsProject) {
150
+ if (!info.supportsJavaScriptGrants)
151
+ throw noRun(`the daemon's provider (${info.sandbox}) runs no projects and grants no snippet`);
152
+ return { ...grant, provider: info.sandbox, languages: ["javascript"], snippets: true };
153
+ }
154
+ if (!info.supportsProjectGrants)
155
+ throw noRun(`the daemon's provider (${info.sandbox}) cannot give a project run a grant`);
156
+ const langs = info.environments.project.languages;
157
+ const languages = ["javascript", "python"].filter((l) => langs.includes(l) && (l !== "python" || PYTHON_GRANT_PROVIDERS.includes(info.sandbox)));
158
+ if (languages.length === 0)
159
+ throw noRun(`no language of the daemon's project image (provider ${info.sandbox}) can call the API from a granted run`);
160
+ return { ...grant, provider: info.sandbox, languages: [...languages], snippets: false };
161
+ }
162
+ /** The qualification beside a result's tier, as a field only when the provider states one. */
163
+ function qualification(q) {
164
+ return q === "" ? {} : { isolationQualification: q };
165
+ }
105
166
  export class CodeSandboxes {
106
167
  #opts;
107
168
  #entries = new Map();
108
169
  #clock = 0;
109
170
  #info;
110
171
  #client;
172
+ /**
173
+ * With grant, every call carries it, and so runs in a sandbox of its own, never in a
174
+ * kept one (a session's interpreter outlives the call, and its code with it): the
175
+ * sandboxes are never opened, and sessions "always" is refused here.
176
+ */
111
177
  constructor(opts) {
178
+ if (opts.grant !== undefined) {
179
+ const g = opts.grant;
180
+ if (!g || typeof g.profile !== "string" || g.profile === "" || typeof g.apiDescription !== "string" || g.apiDescription.trim() === "") {
181
+ throw new PlimsollError("invalid_argument", "plimsoll: a tool's grant is a profile name and its API's description (plimsoll-specgen -emit description), both nonempty", {
182
+ notDispatched: "request",
183
+ });
184
+ }
185
+ if (g.apiDescription.length > MAX_API_DESCRIPTION_CHARS) {
186
+ throw new PlimsollError("invalid_argument", `plimsoll: the API's description holds ${g.apiDescription.length} characters, more than ${MAX_API_DESCRIPTION_CHARS}`, {
187
+ notDispatched: "request",
188
+ });
189
+ }
190
+ if (opts.sessions === "always") {
191
+ throw new PlimsollError("invalid_argument", "plimsoll: sessions \"always\" asks for kept state, which a granted call cannot have: every call of a tool with a grant runs in a sandbox of its own. Keep a second tool without the grant for kept state", { notDispatched: "request" });
192
+ }
193
+ }
112
194
  this.#opts = opts;
113
195
  }
196
+ /** The grant every call carries, or undefined. */
197
+ get grant() {
198
+ return this.#opts.grant;
199
+ }
200
+ /**
201
+ * What the daemon's Describe says this instance's grant can do: which languages' code
202
+ * can call the API, and whether calls run as snippets. Throws, marked not dispatched,
203
+ * reason unsupported, when the daemon cannot carry the grant at all.
204
+ */
205
+ async grantPlan(signal) {
206
+ const grant = this.#opts.grant;
207
+ if (!grant)
208
+ throw new PlimsollError("invalid_argument", "plimsoll: this tool carries no grant", { notDispatched: "request" });
209
+ return grantPlanOf(grant, await untilAborted(this.#describe(), signal));
210
+ }
114
211
  get client() {
115
212
  const c = this.#opts.client;
116
213
  return (this.#client ??= typeof c === "function" ? c() : c);
@@ -176,6 +273,12 @@ export class CodeSandboxes {
176
273
  }
177
274
  catch (e) {
178
275
  const err = saysWhetherItRan(e);
276
+ // A granted call that may have run may have called the API too, as often as the
277
+ // run's call budget allows; a permission refusal of one is the operator's to fix.
278
+ if (this.#opts.grant && !err.notDispatched && !err.message.includes(GRANTED_MAY_HAVE_RUN))
279
+ err.message += " " + GRANTED_MAY_HAVE_RUN;
280
+ if (this.#opts.grant && err.notDispatched === "permission" && !err.message.includes(GRANT_PERMISSION_NOTE))
281
+ err.message += " " + GRANT_PERMISSION_NOTE;
179
282
  // The Describe decides the mode and the languages for every call, and a daemon
180
283
  // can change under a long-lived process (restarted with sessions on or off, or
181
284
  // another image, tier or protocol). A refusal that says so drops it, and the next
@@ -186,6 +289,8 @@ export class CodeSandboxes {
186
289
  }
187
290
  }
188
291
  async #run(keyOrResolver, input, signal) {
292
+ if (this.#opts.grant)
293
+ return this.#granted(keyOrResolver, input, signal);
189
294
  const { key, id, info, language, files, persistent } = await beforeDispatch(async () => {
190
295
  const key = typeof keyOrResolver === "function" ? keyOrResolver() : keyOrResolver;
191
296
  const id = key === undefined ? undefined : keyId(key);
@@ -259,6 +364,7 @@ export class CodeSandboxes {
259
364
  filesPersist: !ended,
260
365
  ...(first ? { freshSandbox: true } : {}),
261
366
  isolation: r.isolation,
367
+ ...qualification(r.isolationQualification),
262
368
  recordSha256: r.record.sha256,
263
369
  };
264
370
  }
@@ -294,6 +400,78 @@ export class CodeSandboxes {
294
400
  }
295
401
  }
296
402
  }
403
+ // A granted call: in a sandbox of its own, never a kept one, as the fresh cell's form
404
+ // (GRANTED_CELL: the cell runner prints the final expression's value) in a granted
405
+ // project, or on a daemon that runs snippets only as a granted snippet. The key only
406
+ // names the conversation for onRecord; no sandbox is kept for it.
407
+ async #granted(keyOrResolver, input, signal) {
408
+ const { key, plan, language, files } = await beforeDispatch(async () => {
409
+ const key = typeof keyOrResolver === "function" ? keyOrResolver() : keyOrResolver;
410
+ if (key !== undefined)
411
+ keyId(key);
412
+ const files = input.files ?? [];
413
+ const reserved = files.find((f) => f.path === ".plimsoll" || f.path.startsWith(".plimsoll/"));
414
+ if (reserved) {
415
+ throw new PlimsollError("invalid_argument", `plimsoll: ${JSON.stringify(reserved.path)} is under .plimsoll/, which the sandbox's runner reserves`, {
416
+ notDispatched: "request",
417
+ });
418
+ }
419
+ const language = input.language ?? this.languages[0];
420
+ const plan = await this.grantPlan(signal);
421
+ if (!plan.languages.includes(language)) {
422
+ throw new PlimsollError("unimplemented", grantRefusal(plan, language), { notDispatched: "unsupported" });
423
+ }
424
+ if (!this.languages.includes(language)) {
425
+ throw new PlimsollError("invalid_argument", `plimsoll: this tool runs ${this.languages.join(" or ")}, not ${language}`, { notDispatched: "request" });
426
+ }
427
+ if (plan.snippets && files.length > 0) {
428
+ throw new PlimsollError("unimplemented", `plimsoll: the daemon (${plan.provider}) runs JavaScript snippets only, which take no files`, {
429
+ notDispatched: "unsupported",
430
+ });
431
+ }
432
+ return { key, plan, language, files };
433
+ });
434
+ const opts = { timeoutMs: this.#opts.timeoutMs, minimumIsolation: this.#floor, signal, grantProfile: plan.profile };
435
+ if (plan.snippets) {
436
+ const r = await this.client.runJavaScript(SNIPPET_CELL[0] + JSON.stringify(input.code) + SNIPPET_CELL[1], opts);
437
+ this.#record(r.record, key);
438
+ return this.#freshOutput(language, r.timedOut ? 124 : r.exitCode, r.timedOut, r.stdout, r.stderr, r.stdoutTruncated || r.stderrTruncated, r.isolation, r.isolationQualification, r.record);
439
+ }
440
+ const cell = GRANTED_CELL[language];
441
+ const project = { files: [...files, ...cell.files, { path: cell.codePath, content: input.code }], steps: [cell.step] };
442
+ let r;
443
+ try {
444
+ r = await this.client.runProject(project, opts);
445
+ }
446
+ catch (e) {
447
+ if (e instanceof PlimsollError && e.record)
448
+ this.#record(e.record, key);
449
+ throw e;
450
+ }
451
+ this.#record(r.record, key);
452
+ const step = r.steps[0];
453
+ if (!step) {
454
+ // As a cell run by itself reads the same ends (sandbox.RunCellFresh).
455
+ if (r.outcome === "timed_out")
456
+ return this.#freshOutput(language, 124, true, "", "", false, r.isolation, r.isolationQualification, r.record);
457
+ if (r.outcome === "setup_failed") {
458
+ throw new PlimsollError("invalid_argument", `plimsoll: the call's files could not be set up, so none of its code ran: ${r.detail}`, { notDispatched: "request", result: r });
459
+ }
460
+ throw new PlimsollError("unknown", `plimsoll: the run ended ${r.outcome} without a step's report (${r.detail}); the code may have run`, { result: r });
461
+ }
462
+ const timedOut = step.timedOut || r.outcome === "timed_out";
463
+ return this.#freshOutput(language, timedOut ? 124 : step.exitCode, timedOut, step.stdout, step.stderr, step.stdoutTruncated || step.stderrTruncated, r.isolation, r.isolationQualification, r.record);
464
+ }
465
+ #freshOutput(language, exitCode, timedOut, stdout, stderr, truncated, isolation, isolationQualification, record) {
466
+ return {
467
+ ...this.#cut(language, exitCode, timedOut, stdout, stderr, truncated),
468
+ stateKept: false,
469
+ filesPersist: false,
470
+ isolation,
471
+ ...qualification(isolationQualification),
472
+ recordSha256: record.sha256,
473
+ };
474
+ }
297
475
  /** Closes the key's sandbox, if it has one. Safe to call more than once. */
298
476
  dispose(key) {
299
477
  return this.#dispose(keyId(key));
@@ -342,6 +520,7 @@ export class CodeSandboxes {
342
520
  stateKept: false,
343
521
  filesPersist: false,
344
522
  isolation: r.isolation,
523
+ ...qualification(r.isolationQualification),
345
524
  recordSha256: r.record.sha256,
346
525
  };
347
526
  }
@@ -11,3 +11,79 @@ export declare const REFUSAL_NAMES: readonly ["unknown", "request", "permission"
11
11
  export declare const TIERS: readonly ["none", "process", "container", "kernel", "vm"];
12
12
  /** The languages plimsoll keeps an interpreter for (sandbox.Languages). */
13
13
  export declare const LANGUAGES: readonly ["javascript", "python"];
14
+ /** The wire protocol number a client states on every request (protocol.Number). */
15
+ export declare const PROTOCOL = 7;
16
+ /** The header carrying a client's ID for one request, which the daemon echoes (protocol.RequestIDHeader). */
17
+ export declare const REQUEST_ID_HEADER = "Plimsoll-Request-Id";
18
+ /** The daemon's mark on an answer written before any handler ran (protocol.NotDispatchedHeader). */
19
+ export declare const NOT_DISPATCHED_HEADER = "Plimsoll-Not-Dispatched";
20
+ /** A correlation id's grammar; the daemon drops one outside it (protocol.TraceIDPattern). */
21
+ export declare const TRACE_ID_PATTERN = "^[A-Za-z0-9._:-]{1,64}$";
22
+ /** The text of a session call, close or attach refused because another worker attached (protocol.StaleOwnerText). */
23
+ export declare const STALE_OWNER_TEXT = "session ownership generation is stale";
24
+ /** The text of an attach refused because its checkpoint is not the session's head (protocol.CheckpointMismatchText). */
25
+ export declare const CHECKPOINT_MISMATCH_TEXT = "session checkpoint does not match";
26
+ /** The tiers a request may state as its floor, weakest first: every tier but none. */
27
+ export declare const FLOORS: readonly ["process", "container", "kernel", "vm"];
28
+ /** The record version a live answer carries (record.Version). */
29
+ export declare const RECORD_VERSION = 5;
30
+ /** Each published record version's digest fields, in order (record.PublishedLayouts). */
31
+ export declare const RECORD_FIELDS: Readonly<Record<number, readonly string[]>>;
32
+ /** The last record version whose daemons stamped both times from the wall clock; reading such a record that ends before it starts is retired (record.LastWallClockEndVersion). */
33
+ export declare const LAST_WALL_CLOCK_END_VERSION = 2;
34
+ /** The refusal of a version 1 or 2 record that ends before it starts: a retired reading, not a forgery (record.RetiredEndBeforeStartText). */
35
+ export declare const RETIRED_END_BEFORE_START_TEXT = "the record ends before it starts, and that reading is retired by the decision of 2026-11-21: records of versions 1 and 2 that end before they start are no longer read; daemons v0.10.0 to v0.12.0 could write one during a clock step";
36
+ /** The codes an unanswered call's record may name (record.UnansweredCodes). */
37
+ export declare const UNANSWERED_CODES: readonly ["aborted", "already_exists", "canceled", "data_loss", "deadline_exceeded", "failed_precondition", "internal", "invalid_argument", "not_found", "out_of_range", "permission_denied", "resource_exhausted", "unauthenticated", "unavailable", "unimplemented", "unknown"];
38
+ /** The most bytes an isolation qualification may take (record.MaxQualificationBytes). */
39
+ export declare const MAX_QUALIFICATION_BYTES = 1024;
40
+ /** The code points a qualification may not hold, as inclusive ranges (record.QualificationForbidden). */
41
+ export declare const QUALIFICATION_FORBIDDEN: readonly (readonly [number, number])[];
42
+ /** The most bytes a record's daemon version may take (record.MaxDaemonVersionBytes). */
43
+ export declare const MAX_DAEMON_VERSION_BYTES = 128;
44
+ /** A daemon version's grammar, when it is not empty (record.DaemonVersionPattern). */
45
+ export declare const DAEMON_VERSION_PATTERN = "^(?:\\(devel\\)|v[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?)$";
46
+ /** A typed instance reference's grammar, when it is not empty (sandbox.InstancePattern). */
47
+ export declare const INSTANCE_PATTERN = "^[a-z][a-z0-9-]{0,31}:[A-Za-z0-9._:-]{1,127}$";
48
+ /** The most bytes of code a snippet or a cell may carry (sandbox.MaxCodeBytes). */
49
+ export declare const MAX_CODE_BYTES = 262144;
50
+ /** The most bytes a request's files may hold together (sandbox.MaxProjectBytes). */
51
+ export declare const MAX_PROJECT_BYTES = 4194304;
52
+ /** The most files a request may write (sandbox.MaxProjectFiles). */
53
+ export declare const MAX_PROJECT_FILES = 200;
54
+ /** The most steps a project may run (sandbox.MaxProjectSteps). */
55
+ export declare const MAX_PROJECT_STEPS = 20;
56
+ /** The most artifacts a project may ask for (sandbox.MaxProjectArtifacts). */
57
+ export declare const MAX_PROJECT_ARTIFACTS = 100;
58
+ /** The most bytes a file or artifact path may take (sandbox.MaxProjectPathBytes). */
59
+ export declare const MAX_PROJECT_PATH_BYTES = 1024;
60
+ /** The most bytes one step's command may take (sandbox.MaxProjectStepBytes). */
61
+ export declare const MAX_PROJECT_STEP_BYTES = 16384;
62
+ /** The most parameter rows a module run may carry (sandbox.MaxModuleRows). */
63
+ export declare const MAX_MODULE_ROWS = 100000;
64
+ /** The most values one module row may carry (sandbox.MaxModuleRowWidth). */
65
+ export declare const MAX_MODULE_ROW_WIDTH = 64;
66
+ /** The most steps one module instance may take (sandbox.MaxModuleSteps). */
67
+ export declare const MAX_MODULE_STEPS = 1000000;
68
+ /** The most bytes a module run's results may take (sandbox.MaxModuleResultBytes). */
69
+ export declare const MAX_MODULE_RESULT_BYTES = 8388608;
70
+ /** The bytes a module run's results start with before the rows (sandbox.ModuleResultHeaderBytes). */
71
+ export declare const MODULE_RESULT_HEADER_BYTES = 20;
72
+ /** A model id's grammar (sandbox.ModuleIDPattern). */
73
+ export declare const MODULE_ID_PATTERN = "^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$";
74
+ /** The most identities an approved software rule may name (sandbox.MaxSoftwareIdentities). */
75
+ export declare const MAX_SOFTWARE_IDENTITIES = 32;
76
+ /** The most bytes one software identity may take (sandbox.MaxSoftwareIdentityBytes). */
77
+ export declare const MAX_SOFTWARE_IDENTITY_BYTES = 256;
78
+ /** The characters a software identity may hold (sandbox.SoftwareIdentityPattern). */
79
+ export declare const SOFTWARE_IDENTITY_PATTERN = "^[A-Za-z0-9._:/@+-]+$";
80
+ /** The largest answer a client reads (client.MaxResponseBytes). */
81
+ export declare const MAX_RESPONSE_BYTES = 33554432;
82
+ /** The one version of a session checkpoint the clients write and read (client.CheckpointVersion). */
83
+ export declare const CHECKPOINT_VERSION = 1;
84
+ /** A daemon name's grammar: the application's own name for a daemon, never a URL (client.DaemonNamePattern). */
85
+ export declare const DAEMON_NAME_PATTERN = "^[A-Za-z0-9._-]{1,64}$";
86
+ /** A software rule's ID as a checkpoint states it (client.SoftwareRuleIDPattern). */
87
+ export declare const SOFTWARE_RULE_ID_PATTERN = "^(?:exact:[A-Za-z0-9._:/@+-]{1,256}|approved:sha256:[0-9a-f]{64})$";
88
+ /** What a client says when it refuses a repeat of a call lost across a takeover (client.CallAlreadySentText). */
89
+ export declare const CALL_ALREADY_SENT_TEXT = "this call was already sent once in the session, and its answer was lost";