@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/README.md CHANGED
@@ -57,7 +57,7 @@ import { PlimsollClient } from "@plimsollmark/client";
57
57
 
58
58
  const plimsoll = new PlimsollClient({ baseUrl: "https://plimsoll.internal:8443", token: process.env.PLIMSOLL_TOKEN });
59
59
 
60
- const info = await plimsoll.describe(); // provider, tier, supportsSessions, ...
60
+ const info = await plimsoll.describe(); // sandbox, isolation, supportsSessions, ...
61
61
  const r = await plimsoll.runJavaScript("console.log(6 * 7)", { minimumIsolation: "container", timeoutMs: 10_000 });
62
62
  r.stdout; // "42\n"; a non-zero r.exitCode is a normal result, not an error
63
63
 
@@ -82,6 +82,60 @@ gets the first one's summary or error: the daemon forgets a session at its first
82
82
  would answer a second with NotFound. A close refused not dispatched (aborted before it was
83
83
  sent, say) closed nothing, so a later `close()` tries again.
84
84
 
85
+ ### Carrying a session on from another process
86
+
87
+ Another process of your application, with the same token, can take a session over from a
88
+ *checkpoint*: the session's public chain head and the policy it stated at open, which holds
89
+ no secret. This client keeps no store; save the checkpoint where only your application can
90
+ write, keyed by identities it verified.
91
+
92
+ ```ts
93
+ import { checkpointToJSON, parseCheckpoint, PlimsollClient } from "@plimsollmark/client";
94
+
95
+ const a = new PlimsollClient({ baseUrl, token, daemonName: "prod" }); // a short name, never a URL
96
+ const s = await a.openSession();
97
+ await s.runCell({ language: "python", code: "x = 1" });
98
+ const saved = checkpointToJSON(await s.checkpoint()); // after each call
99
+ // In another process:
100
+ const b = new PlimsollClient({ baseUrl, token, daemonName: "prod" });
101
+ const t = await b.attachSession(parseCheckpoint(saved));
102
+ await t.runCell({ language: "python", code: "x" }); // the same interpreter
103
+ ```
104
+
105
+ - The first process's later calls and close are refused before they run
106
+ (`StaleOwnerError`, marked not dispatched). A checkpoint that is not the session's head
107
+ is `CheckpointMismatchError`, and nothing moves. An answer that does not repeat the
108
+ checkpoint is `data_loss`, and the session is not closed. A failed or aborted attach is
109
+ never retried.
110
+ - Every call states the head it expects to run on (the generation, the count of calls and
111
+ the last record), and the daemon runs it only on that head. A call refused because the
112
+ daemon's head is another (`HeadMismatchError`, marked not dispatched, with the daemon's
113
+ head) means another holder of the session ran a call between this client's: the session
114
+ stops and sends nothing more.
115
+ - **A call whose answer was lost.** After a call ends with no answer this client could
116
+ check, `session.lostRequestSha256` names it. `attachSession(checkpoint, {
117
+ lostRequestSha256 })` from the checkpoint saved before that call then takes the session
118
+ over across that one call (the *explained gap*), when the daemon's last record is that
119
+ call. The new session is *recovering*: every call is refused before it is sent
120
+ (`RecoveringError`) until you have read `session.lostCall` and called
121
+ `session.resolveLostCall()`. `lostCall.record` says whether the daemon answered the call:
122
+ a result digest when it answered, which does not show that the call ran to its end (a
123
+ step stopped at its time limit and a setup that failed are answers too), an `unanswered`
124
+ code when it ended without an answer, so that it may have done none, part or all of its
125
+ work. `lostCall.answer` is the call's result when the daemon kept it (it keeps the last
126
+ answer in memory until the next call starts or the session suspends or ends, unless the
127
+ session was opened with `keepNoAnswer: true`), checked against the record. A checkpoint
128
+ saved while recovering carries the state (`recoveringRequestSha256`), so the worker that
129
+ attaches from it is recovering too, knowing the lost call by its request digest alone.
130
+ - **The limit:** with no store, this client can name a lost call only when the answer was
131
+ lost in the same process. A process that died mid-call leaves a gap the next one cannot
132
+ explain unless your application recorded the call's request digest before sending.
133
+ - Anyone who holds the token and a session's run records can take the session over. Open
134
+ development mode refuses every takeover.
135
+
136
+ The rules in full:
137
+ [carrying a session on from another worker](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#carrying-a-session-on-from-another-worker).
138
+
85
139
  Cleartext HTTP is accepted only to a loopback address unless you pass `insecureHttp: true`.
86
140
 
87
141
  ## `executeCode` for an agent: `CodeSandboxes`
@@ -97,7 +151,8 @@ Every call of a conversation runs in the same sandbox, so code one call ran can
97
151
  later calls see: a call's output is only as trustworthy as the calls before it in that
98
152
  conversation
99
153
  ([what a session gives up](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#what-a-session-gives-up)).
100
- The tool's calls are cells, which carry no grant, so no API access is shared between them.
154
+ The tool's calls are cells, which carry no grant, so no API access is shared between them;
155
+ a tool whose code calls an API is the granted one below, whose calls keep nothing.
101
156
 
102
157
  **The key decides who shares a sandbox, so derive it from identities you verified.** A
103
158
  sandbox holds one trust domain: everything one call leaves there, later calls with the same
@@ -284,9 +339,56 @@ The session ID is a capability. It lives in the client's memory and nowhere else
284
339
  a log line, not in a record, not in Trigger.dev's `chat.local` (which is serialized into
285
340
  subtask metadata). Records carry its SHA-256.
286
341
 
342
+ ### A grant: `executeCode` whose code calls one web API
343
+
344
+ `plimsollGrantedCodeTool` (AI SDK) and `plimsollGrantedExecuteCode` (Mastra) build the tool
345
+ with a grant your application chose, never the model: the name of a grant profile the
346
+ operator configured on the daemon, and the description `plimsoll-specgen -only allow.json
347
+ -emit description api.json` wrote for it
348
+ ([capability-grants.md](https://github.com/plimsollmark/plimsoll/blob/main/docs/capability-grants.md#from-an-agent-kits-code-tool)).
349
+
350
+ ```ts
351
+ import { plimsollGrantedCodeTool } from "@plimsollmark/client/ai-sdk";
352
+
353
+ const apiDescription = readFileSync("description.txt", "utf8");
354
+ const { executeCode } = await plimsollGrantedCodeTool({ client, grant: { profile: "lights", apiDescription } });
355
+ ```
356
+
357
+ - **Built after the daemon's Describe**, which decides what it offers: JavaScript wherever
358
+ a granted project runs (docker, openshell, e2b with a guard URL, dockercloud) or, on a
359
+ daemon that runs snippets only, a granted snippet without files; Python too on docker and
360
+ openshell, through `import plimsoll_host` (`plimsoll_host.get(path)`, `post(path, body)`,
361
+ `put`, `patch`, `delete`, `call`). The description tells the model the routes and how to
362
+ call them; a tool left with no language, or a daemon that cannot carry the grant, rejects
363
+ the factory, marked not dispatched. On a daemon that runs snippets only (wasm), top-level
364
+ `await` does not work, and the description says to end the code with an async function's
365
+ call instead.
366
+ - **Describe is read once, when the tool is built.** The tool's languages and description
367
+ stay as that answer made them, and its calls reuse it, as `CodeSandboxes` reuses its one
368
+ Describe; the Python executor, by contrast, reads Describe again on every call. A refusal
369
+ that says the daemon changed (`unsupported`, `environment`, `protocol`, `isolation`) makes
370
+ the next call read it again, but the tool's description does not change: after the daemon
371
+ moves to another provider or image, build the tool again.
372
+ - **Every call runs in a sandbox of its own** (the cell's form in a granted project, so the
373
+ last expression's value still prints), never a conversation's kept sandbox: a cell
374
+ carries no grant, so kept state is not available to the granted tool, and it says so.
375
+ `sessions: "always"` with a grant is refused; keep `plimsollCodeTools`' tool beside it
376
+ for kept state. `plimsollCodeTools`, `plimsollExecuteCode` and `plimsollCodeSandbox`
377
+ refuse a grant.
378
+ - **Refusals say what to do.** A Python call where steps cannot reach the broker is refused
379
+ `unsupported` with what to write instead; an unknown profile is `permission`, the
380
+ operator's to fix; a call that may have run says the API may have been called too.
381
+ - The broker, outside the sandbox, holds the key and adds it; the code can still do
382
+ whatever an allowed route permits and read whatever it returns. The run record does not
383
+ list the calls.
384
+
385
+ A runnable example against a stand-in API: `examples/granted.ts`. The client's
386
+ `runProject` and `runJavaScript` take a per-call `grantProfile` (`GrantRunOptions`).
387
+
287
388
  ## Vercel AI SDK
288
389
 
289
- `@plimsollmark/client/ai-sdk` exports `plimsollCodeTools`. Its `executeCode` tool
390
+ `@plimsollmark/client/ai-sdk` exports `plimsollCodeTools`, and `plimsollGrantedCodeTool`
391
+ for a tool whose code calls a granted API (above). Its `executeCode` tool
290
392
  runs fresh; `forConversation({userId, conversationId})` binds a tool to
291
393
  application-owned identity and the shared sandbox manager, with the user as the key's
292
394
  owner. It accepts Python or JavaScript plus text files and returns checked results. The
@@ -294,7 +396,7 @@ default minimum isolation is kernel, as for every add-on on `CodeSandboxes`; use
294
396
  verified gVisor or VM daemon for hostile code.
295
397
 
296
398
  See [usage, lifecycle and the no-spend local smoke check, EXTERNAL · official docs ↗](https://github.com/plimsollmark/plimsoll/blob/main/docs/ai-sdk.md).
297
- This source add-on needs the optional `ai` and `zod` peer packages.
399
+ This source add-on needs the optional `ai` (>=7.0.126 <8, tested at exactly 7.0.126) and `zod` (>=4.6.7 <5, tested at exactly 4.6.7) peer packages.
298
400
 
299
401
  ## Trigger.dev
300
402
 
@@ -303,6 +405,10 @@ The add-on follows Trigger.dev's own
303
405
  `onTurnStart`, reuse in `executeCode`, dispose in `onChatSuspend` (right before the run
304
406
  sleeps) and in `onComplete`.
305
407
 
408
+ This add-on needs the optional `@trigger.dev/sdk` (>=4.7.0 <5, tested at exactly 4.7.0),
409
+ `ai` (>=7.0.126 <8, tested at exactly 7.0.126) and `zod` (>=4.6.7 <5, tested at exactly
410
+ 4.6.7) peer packages.
411
+
306
412
  ```ts
307
413
  import { chat } from "@trigger.dev/sdk/ai";
308
414
  import { PlimsollClient } from "@plimsollmark/client";
@@ -366,6 +472,9 @@ export const analyst = new Agent({ id: "analyst", name: "analyst", instructions:
366
472
  No floor is set here, so the tool requires `kernel`; for local development against an
367
473
  ordinary docker daemon, pass `minimumIsolation: "container"`.
368
474
 
475
+ This add-on needs the optional `@mastra/core` (>=1.73.0 <2, tested at exactly 1.73.0)
476
+ and `zod` (>=4.6.7 <5, tested at exactly 4.6.7) peer packages.
477
+
369
478
  Recorded calls through this tool, two users and a disposed thread included, replay on its
370
479
  integration page: [see a run, INTERNAL · plimsoll site →](https://plimsollmark.github.io/plimsoll/integrations/mastra/index.html).
371
480
 
package/dist/ai-sdk.d.ts CHANGED
@@ -1,6 +1,25 @@
1
1
  import { type Tool } from "ai";
2
- import { CodeSandboxes, type CodeSandboxesOptions, type ExecuteCodeOutput } from "./sandboxes.ts";
2
+ import { CodeSandboxes, type CodeSandboxesOptions, type ExecuteCodeOutput, type ToolGrant } from "./sandboxes.ts";
3
3
  import { type ExecuteCodeToolInput } from "./tool.ts";
4
+ /**
5
+ * The executeCode tool with a grant: every call can reach the one web API the operator's
6
+ * profile allows, through plimsoll's broker outside the sandbox, which holds and adds
7
+ * the API's credential. The profile and the API's description are the application's
8
+ * (grant), never a model's. Built after the daemon's Describe, which decides what the
9
+ * tool offers: JavaScript wherever a granted project or snippet runs, Python too where
10
+ * every project step reaches the broker (docker, openshell), and the tool's description
11
+ * says which. Every call runs in a sandbox of its own, so kept state between calls is
12
+ * not available to it; keep plimsollCodeTools' tool beside it for that. Rejects, marked
13
+ * not dispatched, when the daemon cannot carry the grant. Describe is read once, here: the
14
+ * tool's languages and description stay as that answer made them, and its calls reuse it,
15
+ * so after the daemon moves to another provider or image, build the tool again.
16
+ */
17
+ export declare function plimsollGrantedCodeTool(opts: CodeSandboxesOptions & {
18
+ grant: ToolGrant;
19
+ }): Promise<{
20
+ executeCode: PlimsollCodeTool;
21
+ sandboxes: CodeSandboxes;
22
+ }>;
4
23
  /** Application-owned identity, never fields of a model-generated tool call. */
5
24
  export type ConversationScope = {
6
25
  userId: string;
package/dist/ai-sdk.js CHANGED
@@ -2,8 +2,34 @@
2
2
  // Only this optional entry point imports AI SDK and its schema dependency.
3
3
  import { tool } from "ai";
4
4
  import { PlimsollError } from "./errors.js";
5
- import { CodeSandboxes } from "./sandboxes.js";
5
+ import { CodeSandboxes, offeredForGrant, refuseGrant } from "./sandboxes.js";
6
6
  import { executeCodeDescription, executeCodeInput } from "./tool.js";
7
+ /**
8
+ * The executeCode tool with a grant: every call can reach the one web API the operator's
9
+ * profile allows, through plimsoll's broker outside the sandbox, which holds and adds
10
+ * the API's credential. The profile and the API's description are the application's
11
+ * (grant), never a model's. Built after the daemon's Describe, which decides what the
12
+ * tool offers: JavaScript wherever a granted project or snippet runs, Python too where
13
+ * every project step reaches the broker (docker, openshell), and the tool's description
14
+ * says which. Every call runs in a sandbox of its own, so kept state between calls is
15
+ * not available to it; keep plimsollCodeTools' tool beside it for that. Rejects, marked
16
+ * not dispatched, when the daemon cannot carry the grant. Describe is read once, here: the
17
+ * tool's languages and description stay as that answer made them, and its calls reuse it,
18
+ * so after the daemon moves to another provider or image, build the tool again.
19
+ */
20
+ export async function plimsollGrantedCodeTool(opts) {
21
+ const sandboxes = new CodeSandboxes(opts);
22
+ const plan = await sandboxes.grantPlan();
23
+ const languages = offeredForGrant(sandboxes.languages, plan);
24
+ return {
25
+ executeCode: tool({
26
+ description: executeCodeDescription(languages, "fresh", plan),
27
+ inputSchema: executeCodeInput(languages, true),
28
+ execute: async (input, { abortSignal }) => sandboxes.run(undefined, input, abortSignal),
29
+ }),
30
+ sandboxes,
31
+ };
32
+ }
7
33
  function scopeKey(scope) {
8
34
  if (!scope || typeof scope.userId !== "string" || !scope.userId || typeof scope.conversationId !== "string" || !scope.conversationId) {
9
35
  throw new PlimsollError("invalid_argument", "plimsoll: a conversation requires nonempty userId and conversationId from the application", {
@@ -20,6 +46,7 @@ function scopeKey(scope) {
20
46
  * Default floor: verified kernel isolation, or a stronger VM boundary.
21
47
  */
22
48
  export function plimsollCodeTools(opts) {
49
+ refuseGrant(opts, "plimsollGrantedCodeTool");
23
50
  const sandboxes = new CodeSandboxes(opts);
24
51
  const makeTool = (key) => {
25
52
  const scope = key === undefined || opts.sessions === "never" ? "fresh" : "conversation";
@@ -0,0 +1,42 @@
1
+ export type SessionCheckpoint = {
2
+ version: number;
3
+ /** The application's own name for the daemon (ClientOptions.daemonName), never a URL. */
4
+ daemon: string;
5
+ /** The fingerprint: the SHA-256 of the session ID, 64 lowercase hex digits. */
6
+ session: string;
7
+ generation: bigint;
8
+ calls: bigint;
9
+ lastRecordSha256: string;
10
+ provider: string;
11
+ isolation: string;
12
+ isolationQualification: string;
13
+ softwareIdentity: string;
14
+ /** The floor sent at open, as the daemon echoed it; "" for none. */
15
+ openFloor: string;
16
+ /** The ID of the software rule sent at open, "" for none. */
17
+ openRule: string;
18
+ expiresUnixMs: number;
19
+ idleTimeoutMs: number;
20
+ /**
21
+ * The request digest of the lost call the session was recovering from when the
22
+ * checkpoint was saved (session.lostCall), "" when it was not recovering. A session
23
+ * attached from such a checkpoint is recovering too: every call is refused before it is
24
+ * sent (RecoveringError) until session.resolveLostCall(). It knows the lost call by this
25
+ * digest alone; the record and the answer stayed with the worker that attached across
26
+ * the gap. The head (calls, lastRecordSha256) already counts the lost call.
27
+ */
28
+ recoveringRequestSha256: string;
29
+ };
30
+ /** @internal Whether name is a daemon name: 1 to 64 of [A-Za-z0-9._-], never a URL. */
31
+ export declare function validDaemonName(name: unknown): name is string;
32
+ /** What is wrong with cp, or undefined when it is a checkpoint this client can attach with. */
33
+ export declare function checkpointProblem(cp: SessionCheckpoint): string | undefined;
34
+ /** Throws (invalid_argument, not dispatched) unless cp validates. */
35
+ export declare function validateCheckpoint(cp: SessionCheckpoint): void;
36
+ /**
37
+ * The JSON form every official client reads: these snake_case keys, every one present,
38
+ * the generation and the count as decimal strings (a number cannot hold every uint64).
39
+ */
40
+ export declare function checkpointToJSON(cp: SessionCheckpoint): string;
41
+ /** Reads the JSON form: one object holding every key and no other. Throws invalid_argument. */
42
+ export declare function parseCheckpoint(text: string): SessionCheckpoint;
@@ -0,0 +1,132 @@
1
+ // Session checkpoints (Go: client.Checkpoint, Python: SessionCheckpoint), so another
2
+ // process can carry on with a session: PlimsollClient.attachSession. A checkpoint is a
3
+ // session's public chain head (the ownership generation, the count of calls and the last
4
+ // record's digest) and the policy the session stated at open. It holds no secret: not the
5
+ // session ID, not a credential. The application keeps it where only it can write: anyone
6
+ // holding the caller's credential and a session's checkpoint (or its run records, which
7
+ // carry the fingerprint and the head) can take the session over. This client has no store:
8
+ // the application owns it, as in Go.
9
+ import { PlimsollError } from "./errors.js";
10
+ import { validQualification } from "./record.js";
11
+ import { CHECKPOINT_VERSION, DAEMON_NAME_PATTERN, FLOORS, MAX_SOFTWARE_IDENTITY_BYTES, SOFTWARE_IDENTITY_PATTERN, SOFTWARE_RULE_ID_PATTERN, } from "./tables.gen.js";
12
+ const DAEMON_NAME = new RegExp(DAEMON_NAME_PATTERN);
13
+ const RULE_ID = new RegExp(SOFTWARE_RULE_ID_PATTERN);
14
+ const IDENTITY = new RegExp(SOFTWARE_IDENTITY_PATTERN);
15
+ const HEX64 = /^[0-9a-f]{64}$/;
16
+ const DECIMAL = /^(?:0|[1-9][0-9]*)$/;
17
+ const UINT64_MAX = (1n << 64n) - 1n;
18
+ /** @internal Whether name is a daemon name: 1 to 64 of [A-Za-z0-9._-], never a URL. */
19
+ export function validDaemonName(name) {
20
+ return typeof name === "string" && DAEMON_NAME.test(name);
21
+ }
22
+ const isFloor = (s) => typeof s === "string" && FLOORS.includes(s);
23
+ const whole = (v, lo, hi) => typeof v === "number" && Number.isInteger(v) && v >= lo && v <= hi;
24
+ const utf8Bytes = (s) => Buffer.byteLength(s, "utf8");
25
+ /** What is wrong with cp, or undefined when it is a checkpoint this client can attach with. */
26
+ export function checkpointProblem(cp) {
27
+ if (cp === null || typeof cp !== "object")
28
+ return "not an object";
29
+ if (cp.version !== CHECKPOINT_VERSION)
30
+ return "unknown version";
31
+ if (!validDaemonName(cp.daemon))
32
+ return "the daemon name is not 1 to 64 of [A-Za-z0-9._-]";
33
+ if (typeof cp.session !== "string" || !HEX64.test(cp.session))
34
+ return "the fingerprint is not 64 lowercase hex digits";
35
+ if (typeof cp.generation !== "bigint" || cp.generation < 1n || cp.generation > UINT64_MAX)
36
+ return "the generation is not a positive 64-bit number";
37
+ if (typeof cp.calls !== "bigint" || cp.calls < 0n || cp.calls > UINT64_MAX || typeof cp.lastRecordSha256 !== "string")
38
+ return "the count of calls is not a 64-bit number";
39
+ if ((cp.calls === 0n) !== (cp.lastRecordSha256 === "") || (cp.calls > 0n && !HEX64.test(cp.lastRecordSha256)))
40
+ return "the last record does not match the count of calls";
41
+ if (typeof cp.provider !== "string" || cp.provider === "" || utf8Bytes(cp.provider) > 256 || !cp.provider.isWellFormed())
42
+ return "the provider is empty or malformed";
43
+ if (!isFloor(cp.isolation))
44
+ return "the tier is not one a session runs at";
45
+ if (typeof cp.isolationQualification !== "string" || !validQualification(cp.isolationQualification))
46
+ return "the isolation qualification is malformed";
47
+ const id = cp.softwareIdentity;
48
+ if (typeof id !== "string" || (id !== "" && (utf8Bytes(id) > MAX_SOFTWARE_IDENTITY_BYTES || !IDENTITY.test(id))))
49
+ return "the software identity is malformed";
50
+ if (cp.openFloor !== "" && !isFloor(cp.openFloor))
51
+ return "the open floor is not a tier";
52
+ if (cp.openFloor !== "" && FLOORS.indexOf(cp.isolation) < FLOORS.indexOf(cp.openFloor)) {
53
+ return "the tier is below the open floor";
54
+ }
55
+ if (typeof cp.openRule !== "string" || (cp.openRule !== "" && !RULE_ID.test(cp.openRule)))
56
+ return "the open rule is not a software rule's ID";
57
+ if (!whole(cp.expiresUnixMs, 1, Number.MAX_SAFE_INTEGER))
58
+ return "the expiry is not a positive time";
59
+ if (!whole(cp.idleTimeoutMs, 0, 2 ** 32 - 1))
60
+ return "the idle timeout is not a 32-bit number";
61
+ const rec = cp.recoveringRequestSha256;
62
+ if (typeof rec !== "string" || (rec !== "" && (!HEX64.test(rec) || cp.calls === 0n))) {
63
+ return "the lost call it recovers from is not a request digest of a call the session ran";
64
+ }
65
+ return undefined;
66
+ }
67
+ function invalid(problem) {
68
+ return new PlimsollError("invalid_argument", `plimsoll: invalid session checkpoint: ${problem}`, { notDispatched: "request" });
69
+ }
70
+ /** Throws (invalid_argument, not dispatched) unless cp validates. */
71
+ export function validateCheckpoint(cp) {
72
+ const problem = checkpointProblem(cp);
73
+ if (problem)
74
+ throw invalid(problem);
75
+ }
76
+ // The JSON form's keys, in the order every official client writes them.
77
+ const KEYS = [
78
+ ["version", "version"],
79
+ ["daemon", "daemon"],
80
+ ["session", "session"],
81
+ ["generation", "generation"],
82
+ ["calls", "calls"],
83
+ ["last_record_sha256", "lastRecordSha256"],
84
+ ["provider", "provider"],
85
+ ["isolation", "isolation"],
86
+ ["isolation_qualification", "isolationQualification"],
87
+ ["software_identity", "softwareIdentity"],
88
+ ["open_floor", "openFloor"],
89
+ ["open_rule", "openRule"],
90
+ ["expires_unix_ms", "expiresUnixMs"],
91
+ ["idle_timeout_ms", "idleTimeoutMs"],
92
+ ["recovering_request_sha256", "recoveringRequestSha256"],
93
+ ];
94
+ /**
95
+ * The JSON form every official client reads: these snake_case keys, every one present,
96
+ * the generation and the count as decimal strings (a number cannot hold every uint64).
97
+ */
98
+ export function checkpointToJSON(cp) {
99
+ validateCheckpoint(cp);
100
+ const out = {};
101
+ for (const [wire, key] of KEYS) {
102
+ const v = cp[key];
103
+ out[wire] = typeof v === "bigint" ? v.toString() : v;
104
+ }
105
+ return JSON.stringify(out);
106
+ }
107
+ /** Reads the JSON form: one object holding every key and no other. Throws invalid_argument. */
108
+ export function parseCheckpoint(text) {
109
+ let d;
110
+ try {
111
+ d = JSON.parse(text);
112
+ }
113
+ catch (e) {
114
+ throw invalid(e.message);
115
+ }
116
+ if (d === null || typeof d !== "object" || Array.isArray(d))
117
+ throw invalid("not an object");
118
+ const o = d;
119
+ const names = Object.keys(o).sort();
120
+ const want = KEYS.map(([w]) => w).sort();
121
+ if (names.length !== want.length || names.some((n, i) => n !== want[i]))
122
+ throw invalid("the object does not hold exactly the checkpoint's keys");
123
+ for (const k of ["generation", "calls"]) {
124
+ if (typeof o[k] !== "string" || !DECIMAL.test(o[k]))
125
+ throw invalid(`${k} is not a decimal string with no leading zero`);
126
+ }
127
+ const cp = {};
128
+ for (const [wire, key] of KEYS)
129
+ cp[key] = wire === "generation" || wire === "calls" ? BigInt(o[wire]) : o[wire];
130
+ validateCheckpoint(cp);
131
+ return cp;
132
+ }