@plimsollmark/client 0.27.2 → 0.29.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";
7
- 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}$/;
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";
10
+ import { INT64, UINT32, UINT64, wholeInt, wireBytes, WireShapeError } from "./wire.js";
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) {
@@ -180,32 +212,51 @@ export function resultDigest(resp) {
180
212
  // big reads a 64-bit integer field the JSON codec sends as a decimal string (or a
181
213
  // number). Anything else is an answer this client cannot read, a PlimsollError,
182
214
  // never BigInt's own SyntaxError or RangeError.
183
- function big(v, name) {
184
- if (v === undefined)
185
- return 0n;
186
- if ((typeof v === "string" && /^-?[0-9]{1,20}$/.test(v)) || (typeof v === "number" && Number.isSafeInteger(v)))
187
- return BigInt(v);
188
- throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not an integer`);
215
+ function big(v, name, range = INT64) {
216
+ const n = wholeInt(v, range);
217
+ if (n === undefined)
218
+ throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not an integer in one whole decimal`);
219
+ return n;
220
+ }
221
+ // text and flag read a record field the JSON codec sends as a string or a boolean: absent is "" or false, and any
222
+ // other JSON type is an answer this client cannot read, a PlimsollError (Go's protojson and Python's typed reads
223
+ // refuse the same), never a TypeError later or a value coerced to the right type.
224
+ function text(v, name) {
225
+ if (v === undefined || v === null)
226
+ return "";
227
+ if (typeof v !== "string")
228
+ throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not text`);
229
+ return v;
230
+ }
231
+ function flag(v, name) {
232
+ if (v === undefined || v === null)
233
+ return false;
234
+ if (typeof v !== "boolean")
235
+ throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not a boolean`);
236
+ return v;
189
237
  }
190
238
  export function recordFromWire(m) {
191
239
  return {
192
- 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 ?? "",
240
+ version: Number(big(m.version, "version", UINT32)),
241
+ requestSha256: text(m.requestSha256, "requestSha256"),
242
+ resultSha256: text(m.resultSha256, "resultSha256"),
243
+ provider: text(m.provider, "provider"),
244
+ isolation: text(m.isolation, "isolation"),
245
+ environment: text(m.environment, "environment"),
246
+ policy: text(m.policy, "policy"),
247
+ softwareIdentity: text(m.softwareIdentity, "softwareIdentity"),
248
+ softwareRuleId: text(m.softwareRuleId, "softwareRuleId"),
201
249
  startedUnixMs: big(m.startedUnixMs, "startedUnixMs"),
202
250
  endedUnixMs: big(m.endedUnixMs, "endedUnixMs"),
203
- session: m.session ?? "",
204
- sequence: big(m.sequence, "sequence"),
205
- previousSha256: m.previousSha256 ?? "",
206
- unanswered: m.unanswered ?? "",
207
- instance: m.instance ?? "",
208
- sha256: m.recordSha256 ?? "",
251
+ session: text(m.session, "session"),
252
+ sequence: big(m.sequence, "sequence", UINT64),
253
+ previousSha256: text(m.previousSha256, "previousSha256"),
254
+ unanswered: text(m.unanswered, "unanswered"),
255
+ instance: text(m.instance, "instance"),
256
+ isolationQualification: text(m.isolationQualification, "isolationQualification"),
257
+ warm: flag(m.warm, "warm"),
258
+ daemonVersion: text(m.daemonVersion, "daemonVersion"),
259
+ sha256: text(m.recordSha256, "recordSha256"),
209
260
  };
210
261
  }
211
262
  /** A record's own digest, over the fields its version covers (every field but its digest for an unknown version). */
@@ -215,28 +266,76 @@ export function recordDigest(r) {
215
266
  const v = recordField(r, name);
216
267
  if (typeof v === "string")
217
268
  e.str(name, v);
269
+ else if (typeof v === "boolean")
270
+ e.bool(name, v);
218
271
  else
219
272
  e.int(name, v);
220
273
  }
221
274
  return e.sum();
222
275
  }
223
276
  /**
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.
277
+ * Which calls each published record version records (record.published's answered and
278
+ * unanswered flags): versions 1 and 2 answered calls only, version 3 unanswered session
279
+ * calls only, versions 4 and 5 both. Published versions are frozen, so this is too; a
280
+ * version missing here records nothing, so a new one is refused until it is added, and a
281
+ * test holds the keys to RECORD_FIELDS' (finding release-85).
226
282
  */
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"],
283
+ export const RECORD_KINDS = {
284
+ 1: { answered: true, unanswered: false },
285
+ 2: { answered: true, unanswered: false },
286
+ 3: { answered: false, unanswered: true },
287
+ 4: { answered: true, unanswered: true },
288
+ 5: { answered: true, unanswered: true },
239
289
  };
290
+ /**
291
+ * The record records a kind of call its version records, the fields its version does not
292
+ * cover are unset, it states a result digest or,
293
+ * for an unanswered call, an error code, exactly one, and the code is one of the closed
294
+ * set, its tier is one of TIERS (never "unknown" or empty, whatever floor the request
295
+ * named), it does not end before it starts, answered or not, its qualification and daemon
296
+ * version are in their bounds, and its instance is a typed reference (record.statesOnly).
297
+ * The record of a call lost across a takeover is checked by this alone.
298
+ * Returns the reason it fails, or undefined.
299
+ */
300
+ export function statesOnlyProblem(r) {
301
+ for (const [name, text] of shownFields(r)) {
302
+ if (typeof text !== "string" || !validText(text))
303
+ return `the record's ${name} is not UTF-8 or holds a control or bidirectional format character`;
304
+ }
305
+ const unanswered = r.unanswered !== "";
306
+ const kinds = RECORD_KINDS[r.version];
307
+ if (!kinds)
308
+ return `a version ${r.version} record is not of a published version`;
309
+ if (unanswered && !kinds.unanswered)
310
+ return `a version ${r.version} record cannot record an unanswered call`;
311
+ if (!unanswered && !kinds.answered)
312
+ return `a version ${r.version} record records only an unanswered call`;
313
+ const covered = RECORD_FIELDS[r.version] ?? [];
314
+ for (const name of RECORD_FIELDS[RECORD_VERSION]) {
315
+ const v = recordField(r, name);
316
+ if (!covered.includes(name) && v !== "" && v !== false && v !== 0n)
317
+ return `a version ${r.version} record does not cover ${name}, so it cannot state one`;
318
+ }
319
+ if (unanswered === (r.resultSha256 !== ""))
320
+ return "a record states a result or, for an unanswered call, an error code, exactly one";
321
+ if (unanswered && !UNANSWERED_CODES.has(r.unanswered))
322
+ return `an unanswered call's record names ${JSON.stringify(r.unanswered)}, not a Connect code`;
323
+ if (!TIERS.includes(r.isolation))
324
+ return `the record's isolation ${JSON.stringify(r.isolation)} is not a tier (${TIERS.join(", ")})`;
325
+ // A version 1 or 2 record that ends before it starts is refused as a retired reading, not
326
+ // as a forgery (record.LastWallClockEndVersion, retired 2026-11-21).
327
+ if (r.endedUnixMs < r.startedUnixMs && r.version <= LAST_WALL_CLOCK_END_VERSION)
328
+ return RETIRED_END_BEFORE_START_TEXT;
329
+ if (r.endedUnixMs < r.startedUnixMs)
330
+ return "the record ends before it starts";
331
+ if (!validInstance(r.instance))
332
+ return "the record's instance is not a typed reference";
333
+ if (!validQualification(r.isolationQualification))
334
+ return `the record's isolation qualification is over ${MAX_QUALIFICATION_BYTES} bytes`;
335
+ if (!validDaemonVersion(r.daemonVersion))
336
+ return `the record's daemon version ${JSON.stringify(r.daemonVersion)} is not a module version or (devel)`;
337
+ return undefined;
338
+ }
240
339
  function recordField(r, name) {
241
340
  switch (name) {
242
341
  case "request_sha256": return r.requestSha256;
@@ -249,6 +348,9 @@ function recordField(r, name) {
249
348
  case "software_identity": return r.softwareIdentity;
250
349
  case "software_rule_id": return r.softwareRuleId;
251
350
  case "instance": return r.instance;
351
+ case "isolation_qualification": return r.isolationQualification;
352
+ case "warm": return r.warm;
353
+ case "daemon_version": return r.daemonVersion;
252
354
  case "started_unix_ms": return r.startedUnixMs;
253
355
  case "ended_unix_ms": return r.endedUnixMs;
254
356
  case "session": return r.session;
@@ -292,8 +394,9 @@ export function checkUnanswered(reqDigest, floor, rule, m, fingerprint, prevSeq,
292
394
  const r = recordFromWire(m);
293
395
  if (r.version !== RECORD_VERSION)
294
396
  return { problem: versionProblem(r.version) };
295
- if (!validInstance(r.instance))
296
- return { problem: "the record's instance is not a typed reference" };
397
+ const bounds = statesOnlyProblem(r);
398
+ if (bounds !== undefined)
399
+ return { problem: bounds };
297
400
  if (r.resultSha256 !== "" || !UNANSWERED_CODES.has(r.unanswered))
298
401
  return { problem: "an unanswered call's record states a result or no error code" };
299
402
  if (r.requestSha256 !== reqDigest)
@@ -341,8 +444,6 @@ export function checkRecord(reqDigest, kind, rule, resp) {
341
444
  return { problem: `the answer holds ${kinds.length} results; a run has one` };
342
445
  if (kinds.length !== 1 || kinds[0] !== kind)
343
446
  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
447
  if (r.requestSha256 !== reqDigest)
347
448
  return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
348
449
  if (r.resultSha256 !== result)
@@ -354,6 +455,15 @@ export function checkRecord(reqDigest, kind, rule, resp) {
354
455
  if (r.instance !== (resp.instance ?? "") || !validInstance(r.instance)) {
355
456
  return { problem: "the record's instance is not the response's, or not a typed reference" };
356
457
  }
458
+ if (r.isolationQualification !== (resp.isolationQualification ?? ""))
459
+ return { problem: "the record's isolation qualification is not the response's" };
460
+ if (r.warm !== (resp.warm ?? false))
461
+ return { problem: `the record states warm ${r.warm}, the response ${resp.warm ?? false}` };
462
+ if (r.daemonVersion !== (resp.daemonVersion ?? ""))
463
+ return { problem: "the record's daemon version is not the response's" };
464
+ const bounds = statesOnlyProblem(r);
465
+ if (bounds !== undefined)
466
+ return { problem: bounds };
357
467
  if ((r.softwareIdentity !== (resp.softwareIdentity ?? "") || r.softwareRuleId !== softwareRuleId(rule) || !softwareRuleAllows(rule, r.softwareIdentity))) {
358
468
  return { problem: "the selected software or admission rule differs from the request and response" };
359
469
  }
@@ -361,3 +471,56 @@ export function checkRecord(reqDigest, kind, rule, resp) {
361
471
  return { problem: `record digest ${r.sha256}, its fields digest to ${recordDigest(r)}` };
362
472
  return { record: r };
363
473
  }
474
+ /**
475
+ * Checks the answer an attach returned for a lost call (AttachSessionResponse.lostAnswer)
476
+ * against that call's record, which the caller has already checked against its
477
+ * checkpoint and the request digest it named (record.CheckLostAnswer): the answer carries
478
+ * exactly that record, which is a live answered call's, and one result of a session call's
479
+ * kind whose result digest is the record's, stating the evidence the record states. The
480
+ * request itself is not at hand, only its digest, so the record's request digest and
481
+ * software rule stand for it. Returns the result's kind, or the reason it does not check.
482
+ */
483
+ export function checkLostAnswer(resp, lost) {
484
+ if (resp === null || typeof resp !== "object" || Array.isArray(resp))
485
+ return { problem: "the lost call's answer is not an object" };
486
+ if (!resp.record)
487
+ return { problem: "the lost call's answer carries no run record" };
488
+ const r = recordFromWire(resp.record);
489
+ if (!sameRecord(r, lost))
490
+ return { problem: "the lost call's answer carries another record than the lost call's" };
491
+ if (r.version !== RECORD_VERSION)
492
+ return { problem: versionProblem(r.version) };
493
+ if (r.unanswered !== "")
494
+ return { problem: `an answer came for a call whose record states it ended unanswered (${r.unanswered})` };
495
+ const bounds = statesOnlyProblem(r);
496
+ if (bounds !== undefined)
497
+ return { problem: bounds };
498
+ if (r.sha256 !== recordDigest(r))
499
+ return { problem: `record digest ${r.sha256}, its fields digest to ${recordDigest(r)}` };
500
+ const kinds = ["javascript", "project", "module", "cell"].filter((k) => resp[k] !== undefined && resp[k] !== null);
501
+ const kind = kinds[0];
502
+ if (kinds.length !== 1 || kind === "module" || kind === undefined)
503
+ return { problem: "the lost call's answer holds no one result of a session call's kind" };
504
+ let result;
505
+ try {
506
+ result = resultDigest(resp);
507
+ }
508
+ catch (e) {
509
+ if (e instanceof WireShapeError)
510
+ return { problem: `the lost call's answer is malformed: ${e.message}` };
511
+ throw e;
512
+ }
513
+ if (r.resultSha256 !== result)
514
+ return { problem: `result digest ${r.resultSha256}, the lost call's answer digests to ${result}` };
515
+ if (r.provider !== (resp.sandbox ?? "") || r.isolation !== (resp.isolation ?? "") || r.environment !== (resp.environment ?? "") ||
516
+ r.instance !== (resp.instance ?? "") || r.isolationQualification !== (resp.isolationQualification ?? "") || r.warm !== (resp.warm ?? false) ||
517
+ r.daemonVersion !== (resp.daemonVersion ?? "") || r.softwareIdentity !== (resp.softwareIdentity ?? "")) {
518
+ return { problem: "the lost call's answer states other evidence than its record" };
519
+ }
520
+ return { kind };
521
+ }
522
+ // Whether two records read off the wire are the same record, field by field (Go: proto.Equal
523
+ // on the wire messages).
524
+ function sameRecord(a, b) {
525
+ return Object.keys(a).every((k) => a[k] === b[k]);
526
+ }
@@ -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
  }