@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/README.md +104 -3
- package/dist/ai-sdk.d.ts +20 -1
- package/dist/ai-sdk.js +28 -1
- package/dist/checkpoint.d.ts +41 -0
- package/dist/checkpoint.js +131 -0
- package/dist/client.d.ts +114 -15
- package/dist/client.js +335 -40
- package/dist/errors.d.ts +27 -4
- package/dist/errors.js +60 -10
- package/dist/granted.gen.d.ts +32 -0
- package/dist/granted.gen.js +33 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/mastra.d.ts +38 -1
- package/dist/mastra.js +23 -1
- package/dist/record.d.ts +36 -2
- package/dist/record.js +130 -41
- package/dist/sandboxes.d.ts +59 -1
- package/dist/sandboxes.js +179 -0
- package/dist/tables.gen.d.ts +76 -0
- package/dist/tables.gen.js +85 -2
- package/dist/tool.d.ts +13 -4
- package/dist/tool.js +57 -9
- package/dist/trigger.js +4 -1
- package/dist/wire.d.ts +48 -0
- package/dist/wire.js +25 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -82,6 +82,52 @@ 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
|
+
- **A call whose answer was lost.** After a call ends with no answer this client could
|
|
111
|
+
check, `session.lostRequestSha256` names it. `attachSession(checkpoint, {
|
|
112
|
+
lostRequestSha256 })` from the checkpoint saved before that call then takes the session
|
|
113
|
+
over across that one call (the *explained gap*), when the daemon's last record is that
|
|
114
|
+
call, and `session.lostCall` holds its record; its output is lost. The record says whether
|
|
115
|
+
the daemon answered it: a result digest when the daemon answered, which does not show that
|
|
116
|
+
the call ran to its end (a step stopped at its time limit and a setup that failed are
|
|
117
|
+
answers too), an `unanswered` code when it ended without an answer, so that it may have
|
|
118
|
+
done none, part or all of its work. The new session's first call is refused, with nothing sent, if it repeats that
|
|
119
|
+
call, which was already sent once (`CallAlreadySentError`). Only the first call is checked,
|
|
120
|
+
so a different first call spends the check and the lost call can then run again; the rule
|
|
121
|
+
is this client's, not the daemon's.
|
|
122
|
+
- **The limit:** with no store, this client can name a lost call only when the answer was
|
|
123
|
+
lost in the same process. A process that died mid-call leaves a gap the next one cannot
|
|
124
|
+
explain unless your application recorded the call's request digest before sending.
|
|
125
|
+
- Anyone who holds the token and a session's run records can take the session over. Open
|
|
126
|
+
development mode refuses every takeover.
|
|
127
|
+
|
|
128
|
+
The rules in full:
|
|
129
|
+
[carrying a session on from another worker](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#carrying-a-session-on-from-another-worker).
|
|
130
|
+
|
|
85
131
|
Cleartext HTTP is accepted only to a loopback address unless you pass `insecureHttp: true`.
|
|
86
132
|
|
|
87
133
|
## `executeCode` for an agent: `CodeSandboxes`
|
|
@@ -97,7 +143,8 @@ Every call of a conversation runs in the same sandbox, so code one call ran can
|
|
|
97
143
|
later calls see: a call's output is only as trustworthy as the calls before it in that
|
|
98
144
|
conversation
|
|
99
145
|
([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
|
|
146
|
+
The tool's calls are cells, which carry no grant, so no API access is shared between them;
|
|
147
|
+
a tool whose code calls an API is the granted one below, whose calls keep nothing.
|
|
101
148
|
|
|
102
149
|
**The key decides who shares a sandbox, so derive it from identities you verified.** A
|
|
103
150
|
sandbox holds one trust domain: everything one call leaves there, later calls with the same
|
|
@@ -284,9 +331,56 @@ The session ID is a capability. It lives in the client's memory and nowhere else
|
|
|
284
331
|
a log line, not in a record, not in Trigger.dev's `chat.local` (which is serialized into
|
|
285
332
|
subtask metadata). Records carry its SHA-256.
|
|
286
333
|
|
|
334
|
+
### A grant: `executeCode` whose code calls one web API
|
|
335
|
+
|
|
336
|
+
`plimsollGrantedCodeTool` (AI SDK) and `plimsollGrantedExecuteCode` (Mastra) build the tool
|
|
337
|
+
with a grant your application chose, never the model: the name of a grant profile the
|
|
338
|
+
operator configured on the daemon, and the description `plimsoll-specgen -only allow.json
|
|
339
|
+
-emit description api.json` wrote for it
|
|
340
|
+
([capability-grants.md](https://github.com/plimsollmark/plimsoll/blob/main/docs/capability-grants.md#from-an-agent-kits-code-tool)).
|
|
341
|
+
|
|
342
|
+
```ts
|
|
343
|
+
import { plimsollGrantedCodeTool } from "@plimsollmark/client/ai-sdk";
|
|
344
|
+
|
|
345
|
+
const apiDescription = readFileSync("description.txt", "utf8");
|
|
346
|
+
const { executeCode } = await plimsollGrantedCodeTool({ client, grant: { profile: "lights", apiDescription } });
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
- **Built after the daemon's Describe**, which decides what it offers: JavaScript wherever
|
|
350
|
+
a granted project runs (docker, openshell, e2b with a guard URL, dockercloud) or, on a
|
|
351
|
+
daemon that runs snippets only, a granted snippet without files; Python too on docker and
|
|
352
|
+
openshell, through `import plimsoll_host` (`plimsoll_host.get(path)`, `post(path, body)`,
|
|
353
|
+
`put`, `patch`, `delete`, `call`). The description tells the model the routes and how to
|
|
354
|
+
call them; a tool left with no language, or a daemon that cannot carry the grant, rejects
|
|
355
|
+
the factory, marked not dispatched. On a daemon that runs snippets only (wasm), top-level
|
|
356
|
+
`await` does not work, and the description says to end the code with an async function's
|
|
357
|
+
call instead.
|
|
358
|
+
- **Describe is read once, when the tool is built.** The tool's languages and description
|
|
359
|
+
stay as that answer made them, and its calls reuse it, as `CodeSandboxes` reuses its one
|
|
360
|
+
Describe; the Python executor, by contrast, reads Describe again on every call. A refusal
|
|
361
|
+
that says the daemon changed (`unsupported`, `environment`, `protocol`, `isolation`) makes
|
|
362
|
+
the next call read it again, but the tool's description does not change: after the daemon
|
|
363
|
+
moves to another provider or image, build the tool again.
|
|
364
|
+
- **Every call runs in a sandbox of its own** (the cell's form in a granted project, so the
|
|
365
|
+
last expression's value still prints), never a conversation's kept sandbox: a cell
|
|
366
|
+
carries no grant, so kept state is not available to the granted tool, and it says so.
|
|
367
|
+
`sessions: "always"` with a grant is refused; keep `plimsollCodeTools`' tool beside it
|
|
368
|
+
for kept state. `plimsollCodeTools`, `plimsollExecuteCode` and `plimsollCodeSandbox`
|
|
369
|
+
refuse a grant.
|
|
370
|
+
- **Refusals say what to do.** A Python call where steps cannot reach the broker is refused
|
|
371
|
+
`unsupported` with what to write instead; an unknown profile is `permission`, the
|
|
372
|
+
operator's to fix; a call that may have run says the API may have been called too.
|
|
373
|
+
- The broker, outside the sandbox, holds the key and adds it; the code can still do
|
|
374
|
+
whatever an allowed route permits and read whatever it returns. The run record does not
|
|
375
|
+
list the calls.
|
|
376
|
+
|
|
377
|
+
A runnable example against a stand-in API: `examples/granted.ts`. The client's
|
|
378
|
+
`runProject` and `runJavaScript` take a per-call `grantProfile` (`GrantRunOptions`).
|
|
379
|
+
|
|
287
380
|
## Vercel AI SDK
|
|
288
381
|
|
|
289
|
-
`@plimsollmark/client/ai-sdk` exports `plimsollCodeTools
|
|
382
|
+
`@plimsollmark/client/ai-sdk` exports `plimsollCodeTools`, and `plimsollGrantedCodeTool`
|
|
383
|
+
for a tool whose code calls a granted API (above). Its `executeCode` tool
|
|
290
384
|
runs fresh; `forConversation({userId, conversationId})` binds a tool to
|
|
291
385
|
application-owned identity and the shared sandbox manager, with the user as the key's
|
|
292
386
|
owner. It accepts Python or JavaScript plus text files and returns checked results. The
|
|
@@ -294,7 +388,7 @@ default minimum isolation is kernel, as for every add-on on `CodeSandboxes`; use
|
|
|
294
388
|
verified gVisor or VM daemon for hostile code.
|
|
295
389
|
|
|
296
390
|
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.
|
|
391
|
+
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
392
|
|
|
299
393
|
## Trigger.dev
|
|
300
394
|
|
|
@@ -303,6 +397,10 @@ The add-on follows Trigger.dev's own
|
|
|
303
397
|
`onTurnStart`, reuse in `executeCode`, dispose in `onChatSuspend` (right before the run
|
|
304
398
|
sleeps) and in `onComplete`.
|
|
305
399
|
|
|
400
|
+
This add-on needs the optional `@trigger.dev/sdk` (>=4.7.0 <5, tested at exactly 4.7.0),
|
|
401
|
+
`ai` (>=7.0.126 <8, tested at exactly 7.0.126) and `zod` (>=4.6.7 <5, tested at exactly
|
|
402
|
+
4.6.7) peer packages.
|
|
403
|
+
|
|
306
404
|
```ts
|
|
307
405
|
import { chat } from "@trigger.dev/sdk/ai";
|
|
308
406
|
import { PlimsollClient } from "@plimsollmark/client";
|
|
@@ -366,6 +464,9 @@ export const analyst = new Agent({ id: "analyst", name: "analyst", instructions:
|
|
|
366
464
|
No floor is set here, so the tool requires `kernel`; for local development against an
|
|
367
465
|
ordinary docker daemon, pass `minimumIsolation: "container"`.
|
|
368
466
|
|
|
467
|
+
This add-on needs the optional `@mastra/core` (>=1.73.0 <2, tested at exactly 1.73.0)
|
|
468
|
+
and `zod` (>=4.6.7 <5, tested at exactly 4.6.7) peer packages.
|
|
469
|
+
|
|
369
470
|
Recorded calls through this tool, two users and a disposed thread included, replay on its
|
|
370
471
|
integration page: [see a run, INTERNAL · plimsoll site →](https://plimsollmark.github.io/plimsoll/integrations/mastra/index.html).
|
|
371
472
|
|
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,41 @@
|
|
|
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 a call that was sent once with no answer reaching any worker (an
|
|
22
|
+
* attach explained the gap it left), which the session's next call is refused for
|
|
23
|
+
* repeating (CallAlreadySentError); "" for none. A checkpoint carries it until that next
|
|
24
|
+
* call, unless the daemon refused that call with the not-dispatched mark: nothing ran, so
|
|
25
|
+
* the call after it is still the next.
|
|
26
|
+
*/
|
|
27
|
+
lostCallSha256: string;
|
|
28
|
+
};
|
|
29
|
+
/** @internal Whether name is a daemon name: 1 to 64 of [A-Za-z0-9._-], never a URL. */
|
|
30
|
+
export declare function validDaemonName(name: unknown): name is string;
|
|
31
|
+
/** What is wrong with cp, or undefined when it is a checkpoint this client can attach with. */
|
|
32
|
+
export declare function checkpointProblem(cp: SessionCheckpoint): string | undefined;
|
|
33
|
+
/** Throws (invalid_argument, not dispatched) unless cp validates. */
|
|
34
|
+
export declare function validateCheckpoint(cp: SessionCheckpoint): void;
|
|
35
|
+
/**
|
|
36
|
+
* The JSON form every official client reads: these snake_case keys, every one present,
|
|
37
|
+
* the generation and the count as decimal strings (a number cannot hold every uint64).
|
|
38
|
+
*/
|
|
39
|
+
export declare function checkpointToJSON(cp: SessionCheckpoint): string;
|
|
40
|
+
/** Reads the JSON form: one object holding every key and no other. Throws invalid_argument. */
|
|
41
|
+
export declare function parseCheckpoint(text: string): SessionCheckpoint;
|
|
@@ -0,0 +1,131 @@
|
|
|
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
|
+
if (typeof cp.lostCallSha256 !== "string" || (cp.lostCallSha256 !== "" && (!HEX64.test(cp.lostCallSha256) || cp.calls === 0n))) {
|
|
62
|
+
return "the lost call is not a request digest of a call the session ran";
|
|
63
|
+
}
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
function invalid(problem) {
|
|
67
|
+
return new PlimsollError("invalid_argument", `plimsoll: invalid session checkpoint: ${problem}`, { notDispatched: "request" });
|
|
68
|
+
}
|
|
69
|
+
/** Throws (invalid_argument, not dispatched) unless cp validates. */
|
|
70
|
+
export function validateCheckpoint(cp) {
|
|
71
|
+
const problem = checkpointProblem(cp);
|
|
72
|
+
if (problem)
|
|
73
|
+
throw invalid(problem);
|
|
74
|
+
}
|
|
75
|
+
// The JSON form's keys, in the order every official client writes them.
|
|
76
|
+
const KEYS = [
|
|
77
|
+
["version", "version"],
|
|
78
|
+
["daemon", "daemon"],
|
|
79
|
+
["session", "session"],
|
|
80
|
+
["generation", "generation"],
|
|
81
|
+
["calls", "calls"],
|
|
82
|
+
["last_record_sha256", "lastRecordSha256"],
|
|
83
|
+
["provider", "provider"],
|
|
84
|
+
["isolation", "isolation"],
|
|
85
|
+
["isolation_qualification", "isolationQualification"],
|
|
86
|
+
["software_identity", "softwareIdentity"],
|
|
87
|
+
["open_floor", "openFloor"],
|
|
88
|
+
["open_rule", "openRule"],
|
|
89
|
+
["expires_unix_ms", "expiresUnixMs"],
|
|
90
|
+
["idle_timeout_ms", "idleTimeoutMs"],
|
|
91
|
+
["lost_call_sha256", "lostCallSha256"],
|
|
92
|
+
];
|
|
93
|
+
/**
|
|
94
|
+
* The JSON form every official client reads: these snake_case keys, every one present,
|
|
95
|
+
* the generation and the count as decimal strings (a number cannot hold every uint64).
|
|
96
|
+
*/
|
|
97
|
+
export function checkpointToJSON(cp) {
|
|
98
|
+
validateCheckpoint(cp);
|
|
99
|
+
const out = {};
|
|
100
|
+
for (const [wire, key] of KEYS) {
|
|
101
|
+
const v = cp[key];
|
|
102
|
+
out[wire] = typeof v === "bigint" ? v.toString() : v;
|
|
103
|
+
}
|
|
104
|
+
return JSON.stringify(out);
|
|
105
|
+
}
|
|
106
|
+
/** Reads the JSON form: one object holding every key and no other. Throws invalid_argument. */
|
|
107
|
+
export function parseCheckpoint(text) {
|
|
108
|
+
let d;
|
|
109
|
+
try {
|
|
110
|
+
d = JSON.parse(text);
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
throw invalid(e.message);
|
|
114
|
+
}
|
|
115
|
+
if (d === null || typeof d !== "object" || Array.isArray(d))
|
|
116
|
+
throw invalid("not an object");
|
|
117
|
+
const o = d;
|
|
118
|
+
const names = Object.keys(o).sort();
|
|
119
|
+
const want = KEYS.map(([w]) => w).sort();
|
|
120
|
+
if (names.length !== want.length || names.some((n, i) => n !== want[i]))
|
|
121
|
+
throw invalid("the object does not hold exactly the checkpoint's keys");
|
|
122
|
+
for (const k of ["generation", "calls"]) {
|
|
123
|
+
if (typeof o[k] !== "string" || !DECIMAL.test(o[k]))
|
|
124
|
+
throw invalid(`${k} is not a decimal string with no leading zero`);
|
|
125
|
+
}
|
|
126
|
+
const cp = {};
|
|
127
|
+
for (const [wire, key] of KEYS)
|
|
128
|
+
cp[key] = wire === "generation" || wire === "calls" ? BigInt(o[wire]) : o[wire];
|
|
129
|
+
validateCheckpoint(cp);
|
|
130
|
+
return cp;
|
|
131
|
+
}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import { type RunRecord } from "./record.ts";
|
|
2
|
-
import { LANGUAGES, OUTCOME_NAMES, TIERS } from "./tables.gen.ts";
|
|
2
|
+
import { LANGUAGES, OUTCOME_NAMES, PROTOCOL, TIERS } from "./tables.gen.ts";
|
|
3
|
+
import { type SessionCheckpoint } from "./checkpoint.ts";
|
|
3
4
|
import { type SessionEnd } from "./errors.ts";
|
|
4
|
-
import type { WireCellRun, WireEnvelope, WireOpenSessionResponse, WireSoftwareRule } from "./wire.ts";
|
|
5
|
-
|
|
6
|
-
export declare const PROTOCOL = 5;
|
|
5
|
+
import type { WireAttachSessionResponse, WireCellRun, WireEnvelope, WireOpenSessionResponse, WireSoftwareRule } from "./wire.ts";
|
|
6
|
+
export { PROTOCOL };
|
|
7
7
|
/** How strong the boundary is, weakest first. */
|
|
8
8
|
export type Isolation = (typeof TIERS)[number];
|
|
9
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* Whether a tier the daemon reported is at least `floor`, as the Go client's
|
|
11
|
+
* IsolationClass.Meets and the Python client's meets. A tier or floor this client does
|
|
12
|
+
* not know (including an empty one) meets nothing; every known tier meets "none". A
|
|
13
|
+
* request cannot state "none" as its floor (minimumIsolation), which is a separate rule.
|
|
14
|
+
*/
|
|
10
15
|
export declare function meets(actual: string, floor: Isolation): boolean;
|
|
11
16
|
/** A caller's rule for the selected software: one exact identity, or 1 to 32 approved ones. */
|
|
12
17
|
export type SoftwareRule = {
|
|
@@ -31,6 +36,13 @@ export type ClientOptions = {
|
|
|
31
36
|
* earlier one may have delivered the code.
|
|
32
37
|
*/
|
|
33
38
|
fetch?: typeof fetch;
|
|
39
|
+
/**
|
|
40
|
+
* The application's own name for this daemon, never a URL: 1 to 64 of [A-Za-z0-9._-]. A
|
|
41
|
+
* session's checkpoint states it, and attachSession takes only a checkpoint that names
|
|
42
|
+
* it, so a checkpoint read from the application's store can only reach a daemon the
|
|
43
|
+
* application configured. Without it, sessions cannot be checkpointed or attached.
|
|
44
|
+
*/
|
|
45
|
+
daemonName?: string;
|
|
34
46
|
/**
|
|
35
47
|
* Bounds each HTTP exchange, sending and reading the answer, in milliseconds.
|
|
36
48
|
* Default 6 minutes, as the Go and Python clients. A run's timeoutMs bounds what
|
|
@@ -48,10 +60,25 @@ export type RunOptions = {
|
|
|
48
60
|
traceId?: string;
|
|
49
61
|
signal?: AbortSignal;
|
|
50
62
|
};
|
|
63
|
+
/**
|
|
64
|
+
* A run of a snippet or a project, with the grant profile it selects for this call alone:
|
|
65
|
+
* it replaces the client's javascriptGrantProfile or projectGrantProfile, and "" selects
|
|
66
|
+
* none. A cell carries no grant, so runCell takes RunOptions.
|
|
67
|
+
*/
|
|
68
|
+
export type GrantRunOptions = RunOptions & {
|
|
69
|
+
grantProfile?: string;
|
|
70
|
+
};
|
|
51
71
|
/** Evidence every answered run carries: configuration and provider evidence, never attestation. */
|
|
52
72
|
export type Evidence = {
|
|
53
73
|
sandbox: string;
|
|
54
74
|
isolation: string;
|
|
75
|
+
/**
|
|
76
|
+
* The sentence the provider's vendor or design requires beside `isolation`, as the daemon
|
|
77
|
+
* states it (only the WSL containers provider states one so far: Microsoft's statement that
|
|
78
|
+
* WSL is not a security sandbox for running untrusted code), or "" when it states none. Show
|
|
79
|
+
* it wherever you show the tier. The record repeats it, signed.
|
|
80
|
+
*/
|
|
81
|
+
isolationQualification: string;
|
|
55
82
|
softwareIdentity: string;
|
|
56
83
|
environment: string;
|
|
57
84
|
/** The sandbox instance that ran it, as a typed reference (`k8s-pod-uid:` and a pod's UID), or "" when the provider names none. */
|
|
@@ -284,6 +311,7 @@ export declare class PlimsollClient {
|
|
|
284
311
|
private readonly requestTimeoutMs;
|
|
285
312
|
/** @internal */ readonly jsGrant: string;
|
|
286
313
|
/** @internal */ readonly projectGrant: string;
|
|
314
|
+
/** @internal */ readonly daemonName: string | undefined;
|
|
287
315
|
constructor(opts: ClientOptions);
|
|
288
316
|
/** @internal One unary Connect call with the JSON codec. */
|
|
289
317
|
call<T>(method: string, body: unknown, signal?: AbortSignal): Promise<T>;
|
|
@@ -291,9 +319,9 @@ export declare class PlimsollClient {
|
|
|
291
319
|
describe(signal?: AbortSignal): Promise<Info>;
|
|
292
320
|
private info;
|
|
293
321
|
/** Runs a JavaScript snippet in a fresh sandbox. */
|
|
294
|
-
runJavaScript(code: string, opts?:
|
|
322
|
+
runJavaScript(code: string, opts?: GrantRunOptions): Promise<JavaScriptResult>;
|
|
295
323
|
/** Writes a multi-file project into a fresh sandbox and runs its steps in order. */
|
|
296
|
-
runProject(req: ProjectRequest, opts?:
|
|
324
|
+
runProject(req: ProjectRequest, opts?: GrantRunOptions): Promise<ProjectResult>;
|
|
297
325
|
/**
|
|
298
326
|
* Runs a cell by itself: code for an interpreter of its language, its files written
|
|
299
327
|
* into the work directory first, its final expression's value printed, in a sandbox
|
|
@@ -320,12 +348,51 @@ export declare class PlimsollClient {
|
|
|
320
348
|
* states supportsSessions.
|
|
321
349
|
*/
|
|
322
350
|
openSession(opts?: SessionOptions): Promise<Session>;
|
|
351
|
+
/**
|
|
352
|
+
* Takes over the session `cp` names and carries its chain on from cp's head (Go:
|
|
353
|
+
* Remote.AttachSession): the daemon raises the session's ownership generation by one, and
|
|
354
|
+
* every call or close a worker holding an older one sends is refused before it runs
|
|
355
|
+
* (StaleOwnerError).
|
|
356
|
+
*
|
|
357
|
+
* Refused here, with nothing sent, when cp does not validate, when it names another daemon
|
|
358
|
+
* than this client's daemonName, or when the client has none. The daemon refuses an
|
|
359
|
+
* unknown, ended or another caller's session as not found, a stale generation as
|
|
360
|
+
* StaleOwnerError and a checkpoint that is not its head (a call ran after cp was saved)
|
|
361
|
+
* as CheckpointMismatchError; open development mode refuses every attach.
|
|
362
|
+
*
|
|
363
|
+
* The answer must repeat cp exactly, else data_loss, and the session is not closed: a bad
|
|
364
|
+
* answer gives this client no right to destroy a session another worker may be using. A
|
|
365
|
+
* transport failure or an abort after sending is thrown as it is and never retried: the
|
|
366
|
+
* daemon may have raised the generation, so cp may already be stale.
|
|
367
|
+
*
|
|
368
|
+
* opts.lostRequestSha256 names the call this application believes ran after cp with no
|
|
369
|
+
* answer reaching it (session.lostRequestSha256 gives it for a call of this process).
|
|
370
|
+
* With it, the daemon takes the session over from a checkpoint exactly one call behind
|
|
371
|
+
* its head when its last record is that call, following cp (the explained gap), and
|
|
372
|
+
* returns the record; it must check on its own, be the call named, at cp's next place,
|
|
373
|
+
* stating the evidence the session stated at open, and be the new head
|
|
374
|
+
* (session.lostCall). The attached session then refuses its first call if it repeats
|
|
375
|
+
* that call (CallAlreadySentError). A lost call's record the attach did not name is refused
|
|
376
|
+
* as data_loss.
|
|
377
|
+
*/
|
|
378
|
+
attachSession(cp: SessionCheckpoint, opts?: {
|
|
379
|
+
traceId?: string;
|
|
380
|
+
signal?: AbortSignal;
|
|
381
|
+
lostRequestSha256?: string;
|
|
382
|
+
}): Promise<Session>;
|
|
383
|
+
private attached;
|
|
323
384
|
/** @internal */
|
|
324
385
|
envelope(opts: RunOptions, rule: WireSoftwareRule | undefined): WireEnvelope;
|
|
325
386
|
private exchange;
|
|
326
387
|
private checked;
|
|
327
388
|
}
|
|
328
389
|
/** @internal */
|
|
390
|
+
export declare function lostRecord(cp: SessionCheckpoint, lost: string, m: NonNullable<WireAttachSessionResponse["lostRecord"]>): {
|
|
391
|
+
record: RunRecord;
|
|
392
|
+
} | {
|
|
393
|
+
problem: string;
|
|
394
|
+
};
|
|
395
|
+
/** @internal */
|
|
329
396
|
export declare function projectPayload(req: ProjectRequest, grantProfile: string): Payload;
|
|
330
397
|
/**
|
|
331
398
|
* An open session. Calls are serialized here as they are on the daemon, so the
|
|
@@ -340,18 +407,48 @@ export declare class Session {
|
|
|
340
407
|
readonly fingerprint: string;
|
|
341
408
|
/** The tier the daemon measured when the session opened. */
|
|
342
409
|
readonly isolation: string;
|
|
410
|
+
/** The sentence the provider states beside that tier, "" when it states none. Every call's record states it too. */
|
|
411
|
+
readonly isolationQualification: string;
|
|
343
412
|
readonly sandbox: string;
|
|
344
413
|
/** The selected software the daemon stated at open. */
|
|
345
414
|
readonly softwareIdentity: string;
|
|
346
415
|
readonly expiresAtMs: number;
|
|
347
416
|
readonly idleTimeoutMs: number;
|
|
348
417
|
/** @internal */
|
|
349
|
-
constructor(client: PlimsollClient, m: WireOpenSessionResponse, rule: WireSoftwareRule | undefined, floor?: Exclude<Isolation, "none"
|
|
418
|
+
constructor(client: PlimsollClient, m: WireOpenSessionResponse, rule: WireSoftwareRule | undefined, floor?: Exclude<Isolation, "none">, attached?: {
|
|
419
|
+
generation: bigint;
|
|
420
|
+
calls: bigint;
|
|
421
|
+
last: string;
|
|
422
|
+
lostCall: string;
|
|
423
|
+
lostRecord: RunRecord | undefined;
|
|
424
|
+
});
|
|
350
425
|
/**
|
|
351
426
|
* Why this client sends nothing more on the session, once a call ended without an
|
|
352
427
|
* answer it could check (the call may have run); undefined while it is usable.
|
|
353
428
|
*/
|
|
354
429
|
get stopped(): string | undefined;
|
|
430
|
+
/**
|
|
431
|
+
* The request digest of the call after which this session stopped with no answer it could
|
|
432
|
+
* check, or "": the call that may have run, for another worker's attachSession to name
|
|
433
|
+
* (lostRequestSha256) together with a checkpoint saved before it.
|
|
434
|
+
*/
|
|
435
|
+
get lostRequestSha256(): string;
|
|
436
|
+
/**
|
|
437
|
+
* The record of the call that was sent once and whose answer was lost, on a session attached
|
|
438
|
+
* across an explained gap; its output is lost. The record says whether the daemon answered
|
|
439
|
+
* it: a result digest when the daemon answered, which does not show that the call ran to its
|
|
440
|
+
* end (a step stopped at its time limit and a setup that failed are answers too), an
|
|
441
|
+
* unanswered code when it ended without an answer, so that it may have done none, part or all
|
|
442
|
+
* of its work.
|
|
443
|
+
*/
|
|
444
|
+
get lostCall(): RunRecord | undefined;
|
|
445
|
+
/**
|
|
446
|
+
* The session's checkpoint (Go: Session.Checkpoint), for the application to save where
|
|
447
|
+
* only it can write, so another process can attachSession. It waits for a call in
|
|
448
|
+
* flight, so the head it states follows that call. Refused when the client has no
|
|
449
|
+
* daemonName and when the session is stopped, closed or ended.
|
|
450
|
+
*/
|
|
451
|
+
checkpoint(): Promise<SessionCheckpoint>;
|
|
355
452
|
/** The session's end once a response reported it, else undefined. */
|
|
356
453
|
get ended(): {
|
|
357
454
|
reason: SessionEnd;
|
|
@@ -374,13 +471,15 @@ export declare class Session {
|
|
|
374
471
|
runCell(req: CellRequest, opts?: RunOptions): Promise<CellResult>;
|
|
375
472
|
/**
|
|
376
473
|
* Ends the session (or collects one that ended by itself) and checks the
|
|
377
|
-
* daemon's count of executed calls against the chain this client saw.
|
|
378
|
-
*
|
|
379
|
-
*
|
|
380
|
-
*
|
|
381
|
-
*
|
|
382
|
-
*
|
|
474
|
+
* daemon's count of executed calls against the chain this client saw. Once the
|
|
475
|
+
* daemon has answered a close with its count, every later call returns that
|
|
476
|
+
* close's promise, so its summary or its error (a count that differs from this
|
|
477
|
+
* client's chain included), without another request: the daemon forgets a session
|
|
478
|
+
* at its first close, and a second CloseSession would be answered NotFound. A close
|
|
479
|
+
* that ended any other way (lost in transit, timed out, its signal aborted, refused
|
|
480
|
+
* by the daemon, as with "the session is still ending; close it again") is sent
|
|
481
|
+
* again by the next call (finding hunt-quality-90). A call made while a close is in
|
|
482
|
+
* flight shares it, and that close's signal is the one that applies.
|
|
383
483
|
*/
|
|
384
484
|
close(signal?: AbortSignal): Promise<SessionSummary>;
|
|
385
485
|
}
|
|
386
|
-
export {};
|