@plimsollmark/client 0.14.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/errors.js ADDED
@@ -0,0 +1,132 @@
1
+ // Errors keep the daemon's one distinction that matters for a retry: whether
2
+ // anything ran. A refusal raised before dispatch carries the NotDispatched detail
3
+ // and comes back with notDispatched set; anything else may have followed
4
+ // execution and is never a safe automatic retry (docs/run-results.md).
5
+ export class PlimsollError extends Error {
6
+ code;
7
+ /**
8
+ * Set when the daemon stated that nothing ran. Undefined means execution may
9
+ * have occurred, whatever the code.
10
+ */
11
+ notDispatched;
12
+ /** Set when a session call was refused because its session had ended. */
13
+ sessionEnded;
14
+ /**
15
+ * The result the daemon returned, on a "data_loss" error raised after it
16
+ * answered: the record or the isolation evidence did not check, the run may
17
+ * have executed, and this is what came back.
18
+ */
19
+ result;
20
+ constructor(code, message, opts = {}) {
21
+ super(message, opts.cause === undefined ? undefined : { cause: opts.cause });
22
+ this.name = "PlimsollError";
23
+ this.code = code;
24
+ this.notDispatched = opts.notDispatched;
25
+ this.sessionEnded = opts.sessionEnded;
26
+ this.result = opts.result;
27
+ }
28
+ }
29
+ const REFUSALS = ["unknown", "request", "permission", "protocol", "unsupported", "isolation", "capacity", "environment"];
30
+ const SESSION_ENDS = [
31
+ "open",
32
+ "closed",
33
+ "expired",
34
+ "disk_exceeded",
35
+ "main_process_ended",
36
+ "boundary_failed",
37
+ "sandbox_changed",
38
+ "shutdown",
39
+ ];
40
+ export function sessionEndFromWire(v) {
41
+ if (v === undefined)
42
+ return "open";
43
+ if (typeof v === "number")
44
+ return SESSION_ENDS[v] ?? "open";
45
+ const name = v.replace(/^SESSION_END_/, "").toLowerCase();
46
+ return name === "unspecified" ? "open" : (SESSION_ENDS.includes(name) ? name : "open");
47
+ }
48
+ // Reads one varint at b[i]; returns [value, next index].
49
+ function varint(b, i) {
50
+ let v = 0;
51
+ let shift = 0;
52
+ for (; i < b.length && shift < 35; shift += 7) {
53
+ const c = b[i++];
54
+ v += (c & 0x7f) * 2 ** shift;
55
+ if ((c & 0x80) === 0)
56
+ return [v, i];
57
+ }
58
+ throw new Error("bad varint");
59
+ }
60
+ // Decodes the two tiny detail messages by hand (field 1 an enum, field 2 a
61
+ // string), so the client needs no protobuf runtime.
62
+ function decodeDetail(b) {
63
+ let reason = 0;
64
+ let detail = "";
65
+ let i = 0;
66
+ while (i < b.length) {
67
+ const [tag, j] = varint(b, i);
68
+ i = j;
69
+ const field = Math.floor(tag / 8);
70
+ const wire = tag & 7;
71
+ if (wire === 0) {
72
+ const [v, k] = varint(b, i);
73
+ i = k;
74
+ if (field === 1)
75
+ reason = v;
76
+ }
77
+ else if (wire === 2) {
78
+ const [n, k] = varint(b, i);
79
+ if (k + n > b.length)
80
+ throw new Error("bad length");
81
+ if (field === 2)
82
+ detail = Buffer.from(b.subarray(k, k + n)).toString("utf8");
83
+ i = k + n;
84
+ }
85
+ else {
86
+ throw new Error("unexpected wire type");
87
+ }
88
+ }
89
+ return { reason, detail };
90
+ }
91
+ /** The error a Connect error body describes, with its plimsoll details restored. */
92
+ export function errorFromWire(httpStatus, body) {
93
+ const code = body?.code ?? httpStatusCode(httpStatus);
94
+ let notDispatched;
95
+ let sessionEnded;
96
+ for (const d of body?.details ?? []) {
97
+ try {
98
+ const bytes = Buffer.from(d.value ?? "", "base64");
99
+ if (d.type === "plimsoll.v1.NotDispatched") {
100
+ notDispatched = REFUSALS[decodeDetail(bytes).reason] ?? "unknown";
101
+ }
102
+ else if (d.type === "plimsoll.v1.SessionEnded") {
103
+ const m = decodeDetail(bytes);
104
+ sessionEnded = { reason: sessionEndFromWire(m.reason), detail: m.detail };
105
+ }
106
+ }
107
+ catch {
108
+ // An undecodable detail states nothing; in particular not that nothing ran.
109
+ }
110
+ }
111
+ return new PlimsollError(code, body?.message ?? `HTTP ${httpStatus}`, { notDispatched, sessionEnded });
112
+ }
113
+ // Connect's mapping for a response without a Connect error body.
114
+ function httpStatusCode(status) {
115
+ switch (status) {
116
+ case 400:
117
+ return "internal";
118
+ case 401:
119
+ return "unauthenticated";
120
+ case 403:
121
+ return "permission_denied";
122
+ case 404:
123
+ return "unimplemented";
124
+ case 429:
125
+ case 502:
126
+ case 503:
127
+ case 504:
128
+ return "unavailable";
129
+ default:
130
+ return "unknown";
131
+ }
132
+ }
@@ -0,0 +1,4 @@
1
+ export { PlimsollClient, Session, PROTOCOL, meets, type AdviceFinding, type CellRequest, type CellResult, type ClientOptions, type Evidence, type Info, type Isolation, type JavaScriptResult, type Language, type PayloadEnvironment, type ProjectOutcome, type ProjectRequest, type ProjectResult, type RunOptions, type SessionOptions, type SessionSummary, type SoftwareRule, type StepResult, } from "./client.ts";
2
+ export { PlimsollError, type Code, type Refusal, type SessionEnd } from "./errors.ts";
3
+ export type { RunRecord } from "./record.ts";
4
+ export { CodeSandboxes, DEFAULT_LANGUAGES, type CodeSandboxesOptions, type ExecuteCodeInput, type ExecuteCodeOutput, type SessionMode, type ToolLanguages, } from "./sandboxes.ts";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { PlimsollClient, Session, PROTOCOL, meets, } from "./client.js";
2
+ export { PlimsollError } from "./errors.js";
3
+ export { CodeSandboxes, DEFAULT_LANGUAGES, } from "./sandboxes.js";
@@ -0,0 +1,27 @@
1
+ import { CodeSandboxes, type CodeSandboxesOptions } from "./sandboxes.ts";
2
+ export type PlimsollExecuteCodeOptions = CodeSandboxesOptions;
3
+ export declare function plimsollExecuteCode(opts: PlimsollExecuteCodeOptions): {
4
+ executeCode: import("@mastra/core/tools").Tool<{
5
+ code: string;
6
+ language: "javascript" | "python";
7
+ files?: {
8
+ path: string;
9
+ content: string;
10
+ }[] | undefined;
11
+ }, {
12
+ language: string;
13
+ exitCode: number;
14
+ timedOut: boolean;
15
+ stdout: string;
16
+ stderr: string;
17
+ truncated: boolean;
18
+ stateKept: boolean;
19
+ freshInterpreter?: true | undefined;
20
+ filesPersist: boolean;
21
+ freshSandbox?: true | undefined;
22
+ isolation: string;
23
+ }, unknown, unknown, import("@mastra/core/tools").ToolExecutionContext<unknown, unknown, unknown>, "executeCode", unknown>;
24
+ /** Closes a thread's sandbox, e.g. when the conversation ends. */
25
+ dispose: (threadId: string, resourceId?: string) => Promise<void>;
26
+ sandboxes: CodeSandboxes;
27
+ };
package/dist/mastra.js ADDED
@@ -0,0 +1,30 @@
1
+ // Mastra add-on: the same executeCode tool on the same client, for a Mastra agent.
2
+ // Mastra has no hook for "the conversation is going to sleep", so a thread's
3
+ // sandbox closes when you call dispose(threadId), or after idleCloseMs without a
4
+ // call, whichever comes first.
5
+ import { createTool } from "@mastra/core/tools";
6
+ import { CodeSandboxes } from "./sandboxes.js";
7
+ import { executeCodeDescription, executeCodeInput, executeCodeOutput } from "./tool.js";
8
+ // A thread id is unique only within its resource (the user), so the key is both.
9
+ const threadKey = (threadId, resourceId = "") => `${resourceId}\u0000${threadId}`;
10
+ export function plimsollExecuteCode(opts) {
11
+ const sandboxes = new CodeSandboxes(opts);
12
+ const executeCode = createTool({
13
+ id: "executeCode",
14
+ description: executeCodeDescription(sandboxes.languages),
15
+ inputSchema: executeCodeInput(sandboxes.languages),
16
+ outputSchema: executeCodeOutput,
17
+ // The thread scopes the sandbox. A call outside a thread runs fresh: one
18
+ // sandbox shared across conversations would show one user another's files.
19
+ execute: async (input, ctx) => {
20
+ const thread = ctx?.agent?.threadId;
21
+ return sandboxes.run(thread ? threadKey(thread, ctx?.agent?.resourceId) : undefined, input, ctx?.abortSignal);
22
+ },
23
+ });
24
+ return {
25
+ executeCode,
26
+ /** Closes a thread's sandbox, e.g. when the conversation ends. */
27
+ dispose: (threadId, resourceId) => sandboxes.dispose(threadKey(threadId, resourceId)),
28
+ sandboxes,
29
+ };
30
+ }
@@ -0,0 +1,78 @@
1
+ import type { WireRecord, WireRunResponse, WireSoftwareRule } from "./wire.ts";
2
+ /** The record encoding version this client computes and checks. */
3
+ export declare const RECORD_VERSION = 2;
4
+ /** The payload of a request as the digest sees it. */
5
+ export type DigestPayload = {
6
+ kind: "javascript";
7
+ code: string;
8
+ grantProfile: string;
9
+ } | {
10
+ kind: "cell";
11
+ language: string;
12
+ code: string;
13
+ files: readonly {
14
+ path: string;
15
+ content: string;
16
+ }[];
17
+ } | {
18
+ kind: "project";
19
+ grantProfile: string;
20
+ files: readonly {
21
+ path: string;
22
+ content: string;
23
+ }[];
24
+ steps: readonly string[];
25
+ artifacts: readonly string[];
26
+ };
27
+ export type DigestRequest = {
28
+ protocol: number;
29
+ minimumIsolation: string;
30
+ timeoutMs: number;
31
+ softwareRule: WireSoftwareRule | undefined;
32
+ payload: DigestPayload;
33
+ };
34
+ /** The request digest of a Run request or a session call (the same fields). */
35
+ export declare function requestDigest(r: DigestRequest): string;
36
+ /** The wire enum's number; an unknown name is undefined, which fails the check. */
37
+ export declare function outcomeNumber(name: string | number | undefined): number | undefined;
38
+ /** The result digest of a Run response as it arrived on the wire. */
39
+ export declare function resultDigest(resp: WireRunResponse): string;
40
+ /** A record as this client reads it off the wire, every field present. */
41
+ export type RunRecord = {
42
+ version: number;
43
+ requestSha256: string;
44
+ resultSha256: string;
45
+ provider: string;
46
+ isolation: string;
47
+ environment: string;
48
+ policy: string;
49
+ softwareIdentity: string;
50
+ softwareRuleId: string;
51
+ startedUnixMs: bigint;
52
+ endedUnixMs: bigint;
53
+ session: string;
54
+ sequence: bigint;
55
+ previousSha256: string;
56
+ sha256: string;
57
+ };
58
+ export declare function recordFromWire(m: WireRecord): RunRecord;
59
+ /** A record's own digest, over every field but its digest. */
60
+ export declare function recordDigest(r: RunRecord): string;
61
+ /** The SHA-256 of a session ID: what a session call's record carries instead of the ID. */
62
+ export declare function sessionFingerprint(sessionId: string): string;
63
+ /**
64
+ * The record ID of a software rule: "exact:<identity>" for one identity, else
65
+ * "approved:sha256:" over the identities sorted in byte order, joined by a zero byte.
66
+ */
67
+ export declare function softwareRuleId(rule: WireSoftwareRule | undefined): string;
68
+ export declare function softwareRuleAllows(rule: WireSoftwareRule | undefined, identity: string): boolean;
69
+ /**
70
+ * Checks everything a record states that the caller can recompute: the version,
71
+ * both digests, the evidence the response repeats, the software rule and the
72
+ * record's own digest. Returns the reason it does not check, or undefined.
73
+ */
74
+ export declare function checkRecord(reqDigest: string, protocol: number, rule: WireSoftwareRule | undefined, resp: WireRunResponse): {
75
+ record: RunRecord;
76
+ } | {
77
+ problem: string;
78
+ };
package/dist/record.js ADDED
@@ -0,0 +1,250 @@
1
+ // Run-record digests, computed from docs/run-records.md alone: lowercase hex
2
+ // SHA-256 over a length-prefixed encoding, never over protobuf or JSON bytes.
3
+ // The golden vectors in record/record_test.go are checked in test/record.test.ts.
4
+ import { createHash } from "node:crypto";
5
+ /** The record encoding version this client computes and checks. */
6
+ export const RECORD_VERSION = 2;
7
+ class Encoder {
8
+ h = createHash("sha256");
9
+ constructor(domain) {
10
+ this.value(Buffer.from(domain, "utf8"));
11
+ }
12
+ value(b) {
13
+ const n = Buffer.alloc(8);
14
+ n.writeBigUInt64BE(BigInt(b.length));
15
+ this.h.update(n);
16
+ this.h.update(b);
17
+ }
18
+ bytes(name, v) {
19
+ this.value(Buffer.from(name, "utf8"));
20
+ this.value(v);
21
+ }
22
+ str(name, v) {
23
+ this.bytes(name, Buffer.from(v, "utf8"));
24
+ }
25
+ // Integers are decimal ASCII; callers pass bigint for 64-bit values so no
26
+ // millisecond timestamp or sequence number is rounded through a double.
27
+ int(name, v) {
28
+ this.str(name, BigInt(v).toString(10));
29
+ }
30
+ bool(name, v) {
31
+ this.str(name, v ? "true" : "false");
32
+ }
33
+ floats(name, vs) {
34
+ const b = Buffer.alloc(8 * vs.length);
35
+ vs.forEach((v, i) => b.writeDoubleBE(v, 8 * i));
36
+ this.bytes(name, b);
37
+ }
38
+ sum() {
39
+ return this.h.digest("hex");
40
+ }
41
+ }
42
+ /** The request digest of a Run request or a session call (the same fields). */
43
+ export function requestDigest(r) {
44
+ const e = new Encoder(r.protocol >= 2 ? "plimsoll.run-request.v2" : "plimsoll.run-request.v1");
45
+ e.int("protocol", r.protocol);
46
+ e.str("minimum_isolation", r.minimumIsolation);
47
+ e.int("timeout_ms", r.timeoutMs);
48
+ if (r.protocol >= 2) {
49
+ const ids = r.softwareRule?.identities ?? [];
50
+ e.str("software_mode", r.softwareRule?.mode ?? "");
51
+ e.int("software_identities", ids.length);
52
+ for (const id of ids)
53
+ e.str("software_identity", id);
54
+ }
55
+ const p = r.payload;
56
+ e.str("kind", p.kind);
57
+ if (p.kind === "javascript") {
58
+ e.str("code", p.code);
59
+ e.str("grant_profile", p.grantProfile);
60
+ }
61
+ else if (p.kind === "cell") {
62
+ e.str("language", p.language);
63
+ e.str("code", p.code);
64
+ e.int("files", p.files.length);
65
+ for (const f of p.files) {
66
+ e.str("file_path", f.path);
67
+ e.str("file_content", f.content);
68
+ }
69
+ }
70
+ else {
71
+ e.str("grant_profile", p.grantProfile);
72
+ e.int("files", p.files.length);
73
+ for (const f of p.files) {
74
+ e.str("file_path", f.path);
75
+ e.str("file_content", f.content);
76
+ }
77
+ e.int("steps", p.steps.length);
78
+ for (const s of p.steps)
79
+ e.str("step_command", s);
80
+ e.int("artifacts", p.artifacts.length);
81
+ for (const a of p.artifacts)
82
+ e.str("artifact_path", a);
83
+ }
84
+ return e.sum();
85
+ }
86
+ const OUTCOME_NUMBERS = {
87
+ PROJECT_OUTCOME_UNSPECIFIED: 0,
88
+ PROJECT_OUTCOME_COMPLETED: 1,
89
+ PROJECT_OUTCOME_SETUP_FAILED: 2,
90
+ PROJECT_OUTCOME_TIMED_OUT: 3,
91
+ PROJECT_OUTCOME_PROTOCOL_ERROR: 4,
92
+ };
93
+ /** The wire enum's number; an unknown name is undefined, which fails the check. */
94
+ export function outcomeNumber(name) {
95
+ if (name === undefined)
96
+ return 0;
97
+ if (typeof name === "number")
98
+ return name;
99
+ return OUTCOME_NUMBERS[name];
100
+ }
101
+ const b64 = (s) => Buffer.from(s ?? "", "base64");
102
+ /** The result digest of a Run response as it arrived on the wire. */
103
+ export function resultDigest(resp) {
104
+ const e = new Encoder("plimsoll.run-result.v1");
105
+ if (resp.javascript) {
106
+ const j = resp.javascript;
107
+ e.str("kind", "javascript");
108
+ e.int("exit_code", j.exitCode ?? 0);
109
+ e.bool("timed_out", j.timedOut ?? false);
110
+ e.bytes("stdout", b64(j.stdout));
111
+ e.bytes("stderr", b64(j.stderr));
112
+ e.bool("stdout_truncated", j.stdoutTruncated ?? false);
113
+ e.bool("stderr_truncated", j.stderrTruncated ?? false);
114
+ }
115
+ else if (resp.project) {
116
+ const p = resp.project;
117
+ e.str("kind", "project");
118
+ e.int("outcome", outcomeNumber(p.outcome) ?? -1);
119
+ e.str("outcome_detail", p.outcomeDetail ?? "");
120
+ e.bool("artifacts_truncated", p.artifactsTruncated ?? false);
121
+ const steps = p.steps ?? [];
122
+ e.int("steps", steps.length);
123
+ for (const s of steps) {
124
+ e.str("step_command", s.command ?? "");
125
+ e.int("step_exit_code", s.exitCode ?? 0);
126
+ e.bool("step_timed_out", s.timedOut ?? false);
127
+ e.bytes("step_stdout", b64(s.stdout));
128
+ e.bytes("step_stderr", b64(s.stderr));
129
+ e.bool("step_stdout_truncated", s.stdoutTruncated ?? false);
130
+ e.bool("step_stderr_truncated", s.stderrTruncated ?? false);
131
+ }
132
+ const artifacts = p.artifacts ?? [];
133
+ e.int("artifacts", artifacts.length);
134
+ for (const a of artifacts) {
135
+ e.str("artifact_path", a.path ?? "");
136
+ e.bytes("artifact_content", b64(a.content));
137
+ }
138
+ }
139
+ else if (resp.cell) {
140
+ const c = resp.cell;
141
+ e.str("kind", "cell");
142
+ e.int("exit_code", c.exitCode ?? 0);
143
+ e.bool("timed_out", c.timedOut ?? false);
144
+ e.bytes("stdout", b64(c.stdout));
145
+ e.bytes("stderr", b64(c.stderr));
146
+ e.bool("stdout_truncated", c.stdoutTruncated ?? false);
147
+ e.bool("stderr_truncated", c.stderrTruncated ?? false);
148
+ e.bool("interpreter_started", c.interpreterStarted ?? false);
149
+ e.bool("interpreter_ended", c.interpreterEnded ?? false);
150
+ }
151
+ else {
152
+ // A module result, or none: this client sends neither, so the kind check
153
+ // refuses the response before its digest matters.
154
+ e.str("kind", "");
155
+ }
156
+ return e.sum();
157
+ }
158
+ export function recordFromWire(m) {
159
+ return {
160
+ version: m.version ?? 0,
161
+ requestSha256: m.requestSha256 ?? "",
162
+ resultSha256: m.resultSha256 ?? "",
163
+ provider: m.provider ?? "",
164
+ isolation: m.isolation ?? "",
165
+ environment: m.environment ?? "",
166
+ policy: m.policy ?? "",
167
+ softwareIdentity: m.softwareIdentity ?? "",
168
+ softwareRuleId: m.softwareRuleId ?? "",
169
+ startedUnixMs: BigInt(m.startedUnixMs ?? 0),
170
+ endedUnixMs: BigInt(m.endedUnixMs ?? 0),
171
+ session: m.session ?? "",
172
+ sequence: BigInt(m.sequence ?? 0),
173
+ previousSha256: m.previousSha256 ?? "",
174
+ sha256: m.recordSha256 ?? "",
175
+ };
176
+ }
177
+ /** A record's own digest, over every field but its digest. */
178
+ export function recordDigest(r) {
179
+ const e = new Encoder(`plimsoll.run-record.v${r.version}`);
180
+ e.str("request_sha256", r.requestSha256);
181
+ e.str("result_sha256", r.resultSha256);
182
+ e.str("provider", r.provider);
183
+ e.str("isolation", r.isolation);
184
+ e.str("environment", r.environment);
185
+ e.str("policy", r.policy);
186
+ if (r.version >= 2) {
187
+ e.str("software_identity", r.softwareIdentity);
188
+ e.str("software_rule_id", r.softwareRuleId);
189
+ }
190
+ e.int("started_unix_ms", r.startedUnixMs);
191
+ e.int("ended_unix_ms", r.endedUnixMs);
192
+ e.str("session", r.session);
193
+ e.int("sequence", r.sequence);
194
+ e.str("previous_sha256", r.previousSha256);
195
+ return e.sum();
196
+ }
197
+ /** The SHA-256 of a session ID: what a session call's record carries instead of the ID. */
198
+ export function sessionFingerprint(sessionId) {
199
+ return createHash("sha256").update(sessionId, "utf8").digest("hex");
200
+ }
201
+ /**
202
+ * The record ID of a software rule: "exact:<identity>" for one identity, else
203
+ * "approved:sha256:" over the identities sorted in byte order, joined by a zero byte.
204
+ */
205
+ export function softwareRuleId(rule) {
206
+ if (!rule || !rule.mode)
207
+ return "";
208
+ const ids = rule.identities;
209
+ if (ids.length === 1)
210
+ return `exact:${ids[0]}`;
211
+ const sorted = [...ids].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
212
+ return "approved:sha256:" + createHash("sha256").update(sorted.join("\x00"), "utf8").digest("hex");
213
+ }
214
+ export function softwareRuleAllows(rule, identity) {
215
+ if (!rule || !rule.mode)
216
+ return true;
217
+ return identity !== "" && rule.identities.includes(identity);
218
+ }
219
+ /**
220
+ * Checks everything a record states that the caller can recompute: the version,
221
+ * both digests, the evidence the response repeats, the software rule and the
222
+ * record's own digest. Returns the reason it does not check, or undefined.
223
+ */
224
+ export function checkRecord(reqDigest, protocol, rule, resp) {
225
+ if (!resp.record)
226
+ return { problem: "the response carries no run record" };
227
+ const r = recordFromWire(resp.record);
228
+ const result = resultDigest(resp);
229
+ if (r.version !== 1 && r.version !== RECORD_VERSION)
230
+ return { problem: `unknown run record version ${r.version}` };
231
+ if (protocol >= 2 && r.version !== RECORD_VERSION)
232
+ return { problem: `protocol ${protocol} requires record version ${RECORD_VERSION}` };
233
+ if (r.version === 1 && (r.softwareIdentity !== "" || r.softwareRuleId !== ""))
234
+ return { problem: "a version 1 record cannot carry software fields" };
235
+ if (r.requestSha256 !== reqDigest)
236
+ return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
237
+ if (r.resultSha256 !== result)
238
+ return { problem: `result digest ${r.resultSha256}, the result received digests to ${result}` };
239
+ if (r.provider !== (resp.sandbox ?? "") || r.isolation !== (resp.isolation ?? ""))
240
+ return { problem: "the record's provider or tier differs from the response's" };
241
+ if (r.version >= 2 && r.environment !== (resp.environment ?? ""))
242
+ return { problem: "the record's environment differs from the response's" };
243
+ if (r.version >= 2 &&
244
+ (r.softwareIdentity !== (resp.softwareIdentity ?? "") || r.softwareRuleId !== softwareRuleId(rule) || !softwareRuleAllows(rule, r.softwareIdentity))) {
245
+ return { problem: "the selected software or admission rule differs from the request and response" };
246
+ }
247
+ if (r.sha256 !== recordDigest(r))
248
+ return { problem: `record digest ${r.sha256}, its fields digest to ${recordDigest(r)}` };
249
+ return { record: r };
250
+ }
@@ -0,0 +1,116 @@
1
+ import { PlimsollClient, type Isolation, type Language } from "./client.ts";
2
+ export type SessionMode = "auto" | "always" | "never";
3
+ /** The languages a tool offers, the first being the default. */
4
+ export type ToolLanguages = readonly [Language, ...Language[]];
5
+ export declare const DEFAULT_LANGUAGES: ToolLanguages;
6
+ export type CodeSandboxesOptions = {
7
+ /**
8
+ * The daemon's client, or a function that builds it on first use: a
9
+ * module-level tool can then be declared before its environment is read
10
+ * (Trigger.dev indexes task modules at deploy time, without runtime secrets).
11
+ */
12
+ client: PlimsollClient | (() => PlimsollClient);
13
+ /**
14
+ * "auto" (default) keeps a session per key when the daemon supports sessions,
15
+ * else runs each call fresh. "always" fails when it does not; "never" always
16
+ * runs fresh.
17
+ */
18
+ sessions?: SessionMode;
19
+ /** The languages the tool offers, the first being the default. Default python, then javascript. */
20
+ languages?: ToolLanguages;
21
+ /** The weakest tier a run accepts; checked before dispatch and on the answer. */
22
+ minimumIsolation?: Exclude<Isolation, "none">;
23
+ /** Per-call budget. */
24
+ timeoutMs?: number;
25
+ /** Asked of the daemon when a session opens; the daemon's own caps apply. */
26
+ sessionLifetimeMs?: number;
27
+ sessionIdleTimeoutMs?: number;
28
+ /**
29
+ * Close a key's session after this long without a call, so a conversation
30
+ * that never reaches its dispose hook does not hold a daemon slot until the
31
+ * session's lifetime ends. Default 10 minutes; 0 never.
32
+ */
33
+ idleCloseMs?: number;
34
+ /** Characters of stdout and of stderr returned to the model; the rest is cut and marked. */
35
+ maxOutputChars?: number;
36
+ /**
37
+ * Called when closing a sandbox fails. A "data_loss" error here means the
38
+ * daemon counted calls this client did not make: someone else held the
39
+ * session ID. Default: console.warn. The error never contains the session ID.
40
+ */
41
+ onCloseError?: (key: string, err: unknown) => void;
42
+ };
43
+ /** What the executeCode tool takes. */
44
+ export type ExecuteCodeInput = {
45
+ code: string;
46
+ language?: Language;
47
+ files?: {
48
+ path: string;
49
+ content: string;
50
+ }[];
51
+ };
52
+ /** What the executeCode tool returns to the model. */
53
+ export type ExecuteCodeOutput = {
54
+ language: Language;
55
+ exitCode: number;
56
+ timedOut: boolean;
57
+ stdout: string;
58
+ stderr: string;
59
+ /** Output was cut, by the daemon's cap or by maxOutputChars. */
60
+ truncated: boolean;
61
+ /**
62
+ * This call's interpreter, and its sandbox, were still running when it answered, so
63
+ * what it defined can be there for the conversation's next call in this language:
64
+ * false without a kept interpreter, and when a deadline or the sandbox's end ended
65
+ * them. Not a promise: the sandbox can still end before the next call (its lifetime,
66
+ * the disk check after a call), and that call's freshInterpreter says what survived.
67
+ */
68
+ stateKept: boolean;
69
+ /**
70
+ * This call's interpreter had just started: nothing earlier calls defined in this
71
+ * language exists (the first call, a deadline, a crash, a new sandbox).
72
+ */
73
+ freshInterpreter?: true;
74
+ /**
75
+ * This call's sandbox was still running when it answered, so its files can be there
76
+ * for the next call: false without a kept sandbox, and when it ended. The next call's
77
+ * freshSandbox says whether they are.
78
+ */
79
+ filesPersist: boolean;
80
+ /**
81
+ * This call ran in a newly opened sandbox: no file an earlier call wrote or was
82
+ * given is there (the first call, a disposed or idle sandbox, one that ended).
83
+ */
84
+ freshSandbox?: true;
85
+ /** The tier the code ran behind: configuration and provider evidence, not attestation. */
86
+ isolation: string;
87
+ };
88
+ /** @internal A fresh call on a daemon without projects: the code as a snippet, its last value printed. Node and QuickJS alike. */
89
+ export declare function snippetRunner(code: string): string;
90
+ /** @internal A fresh run prints its last expression as a cell does, through these runners. */
91
+ export declare const RUNNERS: Record<Language, {
92
+ path: string;
93
+ file: string;
94
+ step: string;
95
+ source: string;
96
+ }>;
97
+ export declare class CodeSandboxes {
98
+ #private;
99
+ constructor(opts: CodeSandboxesOptions);
100
+ get client(): PlimsollClient;
101
+ /** The languages the tool offers, the first being the default. */
102
+ get languages(): ToolLanguages;
103
+ /** Whether calls under a key share one sandbox on this daemon. */
104
+ persistent(): Promise<boolean>;
105
+ /**
106
+ * Starts creating the key's sandbox and returns at once. A failure here is
107
+ * not lost: the next run under the key opens a session again.
108
+ */
109
+ warm(key: string): void;
110
+ /** Runs one call of the tool under the key. */
111
+ run(key: string | undefined, input: ExecuteCodeInput, signal?: AbortSignal): Promise<ExecuteCodeOutput>;
112
+ /** Closes the key's sandbox, if it has one. Safe to call more than once. */
113
+ dispose(key: string): Promise<void>;
114
+ /** Closes every sandbox this instance holds, for shutdown. */
115
+ disposeAll(): Promise<void>;
116
+ }