@plimsollmark/client 0.15.0 → 0.17.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 +33 -8
- package/dist/client.d.ts +18 -1
- package/dist/client.js +129 -39
- package/dist/errors.d.ts +6 -1
- package/dist/errors.js +16 -3
- package/dist/mastra.d.ts +2 -2
- package/dist/mastra.js +16 -10
- package/dist/record.d.ts +3 -2
- package/dist/record.js +31 -7
- package/dist/sandboxes.js +35 -18
- package/dist/tool.js +1 -1
- package/dist/wire.d.ts +2 -0
- package/package.json +8 -5
package/README.md
CHANGED
|
@@ -76,6 +76,15 @@ conversation
|
|
|
76
76
|
([what a session gives up](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#what-a-session-gives-up)).
|
|
77
77
|
The tool's calls are cells, which carry no grant, so no API access is shared between them.
|
|
78
78
|
|
|
79
|
+
**The key decides who shares a sandbox, so derive it from identities you verified.** A
|
|
80
|
+
sandbox holds one trust domain: everything one call leaves there, later calls with the same
|
|
81
|
+
key see. plimsoll ties a session to the credential that opened it, not to the users behind
|
|
82
|
+
that credential, so if your service runs many users' code through one plimsoll credential,
|
|
83
|
+
two users with the same key share one sandbox, files and variables included. Build the key
|
|
84
|
+
from your own authenticated user and conversation (or job) IDs, never from a string a user
|
|
85
|
+
or the model supplies, or give each customer a plimsoll credential of their own
|
|
86
|
+
([who may share a session](https://github.com/plimsollmark/plimsoll/blob/main/docs/sessions.md#who-may-share-a-session)).
|
|
87
|
+
|
|
79
88
|
`CodeSandboxes` keeps one sandbox per conversation key. With `sessions: "auto"` (the
|
|
80
89
|
default) it asks the daemon once whether it keeps sessions:
|
|
81
90
|
|
|
@@ -111,10 +120,14 @@ mismatch means the daemon counted a call the client has no answer for (one that
|
|
|
111
120
|
abort, a timeout, a dropped connection or a proxy's error), or, if none did, that someone
|
|
112
121
|
else held the session ID. It goes to `onCloseError` (by default a warning) rather than being
|
|
113
122
|
dropped at teardown. A call that may have run but ended in an error comes with its record
|
|
114
|
-
(`PlimsollError.unanswered`, a version 3 record); the session checks it,
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
123
|
+
(`PlimsollError.unanswered`, a version 3 record); the session checks it, hands it back as
|
|
124
|
+
`PlimsollError.record`, keeps it in its chain and goes on, and so does the conversation's
|
|
125
|
+
sandbox. A call whose answer never arrived carries none, so the client sends nothing more
|
|
126
|
+
on that session (`Session.stopped` says why), and the conversation's next call opens a new
|
|
127
|
+
sandbox and reports `freshSandbox: true`. A session call aborted while it waits its turn
|
|
128
|
+
was never sent: it is refused, marked not dispatched, and the session goes on. The
|
|
129
|
+
`.plimsoll/` directory is the runner's: a file under it is refused before anything is
|
|
130
|
+
sent.
|
|
118
131
|
|
|
119
132
|
The session ID is a capability. It lives in the client's memory and nowhere else: not in
|
|
120
133
|
a log line, not in a record, not in Trigger.dev's `chat.local` (which is serialized into
|
|
@@ -150,6 +163,12 @@ export const codeChat = chat.agent({
|
|
|
150
163
|
The full example, with a test that drives real turns through Trigger.dev's `mockChatAgent`:
|
|
151
164
|
[examples/trigger-chat](https://github.com/plimsollmark/plimsoll/tree/main/examples/trigger-chat/).
|
|
152
165
|
|
|
166
|
+
What the hooks cannot cover: a run that dies without reaching `onChatSuspend` or
|
|
167
|
+
`onComplete` (its process killed, a crash) leaves its sandbox open until the add-on's idle
|
|
168
|
+
close (`idleCloseMs`, default 10 minutes) or, if the process is gone too, the daemon's own
|
|
169
|
+
idle suspend and session lifetime (`SANDBOX_SESSION_IDLE`, `SANDBOX_SESSION_LIFETIME`). A
|
|
170
|
+
worker shutting down can close every sandbox it holds with `sandbox.sandboxes.disposeAll()`.
|
|
171
|
+
|
|
153
172
|
## Mastra
|
|
154
173
|
|
|
155
174
|
```ts
|
|
@@ -166,8 +185,12 @@ export const analyst = new Agent({ id: "analyst", name: "analyst", instructions:
|
|
|
166
185
|
```
|
|
167
186
|
|
|
168
187
|
The sandbox is keyed by Mastra's thread and resource (a thread ID is unique only within
|
|
169
|
-
its user).
|
|
170
|
-
|
|
188
|
+
its user). A call without a `resourceId` runs in a fresh sandbox every time: under an empty
|
|
189
|
+
resource, every user without one would share a sandbox with anyone whose thread ID
|
|
190
|
+
collided. Set the resource from your authenticated user, not from anything the user
|
|
191
|
+
typed. Mastra has no hook for "this conversation is going to sleep", so a thread's
|
|
192
|
+
sandbox closes on `dispose(threadId, resourceId)`, or after `idleCloseMs` (default 10
|
|
193
|
+
minutes) without a call.
|
|
171
194
|
|
|
172
195
|
## Tests
|
|
173
196
|
|
|
@@ -177,7 +200,9 @@ project with the plan it received, for the project a fresh call sends) and runs
|
|
|
177
200
|
suites against them: the
|
|
178
201
|
client's (needs only node), the add-ons' (needs `npm install` here), and the Trigger.dev
|
|
179
202
|
example's (needs `npm install` in `examples/trigger-chat`; it waits out Trigger.dev's
|
|
180
|
-
30-second idle window to prove the suspend closes the sandbox).
|
|
181
|
-
|
|
203
|
+
30-second idle window to prove the suspend closes the sandbox). An ordinary Go test
|
|
204
|
+
skips a suite whose runtime or dependencies are absent. CI runs `make clients-suite`,
|
|
205
|
+
which installs both npm lockfiles and sets `PLIMSOLL_REQUIRE_CLIENTS=1`, so a missing
|
|
206
|
+
prerequisite or skipped Go test fails. The client's digests are also checked against the
|
|
182
207
|
golden vectors of `record/record_test.go`, and the fresh-run runners are run on this
|
|
183
208
|
machine's `node` and `python3` to check they print the last expression.
|
package/dist/client.d.ts
CHANGED
|
@@ -157,6 +157,8 @@ export type Info = {
|
|
|
157
157
|
supportsSessions: boolean;
|
|
158
158
|
sessionLifetimeMs: number;
|
|
159
159
|
sessionIdleTimeoutMs: number;
|
|
160
|
+
/** Where a session's calls run (on docker the project image), stated with supportsSessions. */
|
|
161
|
+
sessionEnvironment: PayloadEnvironment;
|
|
160
162
|
environments: {
|
|
161
163
|
javascript: PayloadEnvironment;
|
|
162
164
|
project: PayloadEnvironment;
|
|
@@ -177,6 +179,12 @@ export type SessionOptions = {
|
|
|
177
179
|
lifetimeMs?: number;
|
|
178
180
|
idleTimeoutMs?: number;
|
|
179
181
|
traceId?: string;
|
|
182
|
+
/**
|
|
183
|
+
* The languages the session's cells will use: a hint, so a daemon with a warm pool
|
|
184
|
+
* hands over a sandbox with those interpreters already running. A cell in any
|
|
185
|
+
* language the daemon states still runs.
|
|
186
|
+
*/
|
|
187
|
+
languages?: Language[];
|
|
180
188
|
signal?: AbortSignal;
|
|
181
189
|
};
|
|
182
190
|
export type SessionSummary = {
|
|
@@ -217,6 +225,7 @@ export declare class PlimsollClient {
|
|
|
217
225
|
call<T>(method: string, body: unknown, signal?: AbortSignal): Promise<T>;
|
|
218
226
|
/** The daemon's own statement of its provider, tier and what it supports. */
|
|
219
227
|
describe(signal?: AbortSignal): Promise<Info>;
|
|
228
|
+
private info;
|
|
220
229
|
/** Runs a JavaScript snippet in a fresh sandbox. */
|
|
221
230
|
runJavaScript(code: string, opts?: RunOptions): Promise<JavaScriptResult>;
|
|
222
231
|
/** Writes a multi-file project into a fresh sandbox and runs its steps in order. */
|
|
@@ -230,6 +239,7 @@ export declare class PlimsollClient {
|
|
|
230
239
|
/** @internal */
|
|
231
240
|
envelope(opts: RunOptions, rule: WireSoftwareRule | undefined): WireEnvelope;
|
|
232
241
|
private exchange;
|
|
242
|
+
private checked;
|
|
233
243
|
}
|
|
234
244
|
/** @internal */
|
|
235
245
|
export declare function projectPayload(req: ProjectRequest, grantProfile: string): Payload;
|
|
@@ -247,10 +257,17 @@ export declare class Session {
|
|
|
247
257
|
/** The tier the daemon measured when the session opened. */
|
|
248
258
|
readonly isolation: string;
|
|
249
259
|
readonly sandbox: string;
|
|
260
|
+
/** The selected software the daemon stated at open. */
|
|
261
|
+
readonly softwareIdentity: string;
|
|
250
262
|
readonly expiresAtMs: number;
|
|
251
263
|
readonly idleTimeoutMs: number;
|
|
252
264
|
/** @internal */
|
|
253
|
-
constructor(client: PlimsollClient, m: WireOpenSessionResponse, rule: WireSoftwareRule | undefined);
|
|
265
|
+
constructor(client: PlimsollClient, m: WireOpenSessionResponse, rule: WireSoftwareRule | undefined, floor?: Exclude<Isolation, "none">);
|
|
266
|
+
/**
|
|
267
|
+
* Why this client sends nothing more on the session, once a call ended without an
|
|
268
|
+
* answer it could check (the call may have run); undefined while it is usable.
|
|
269
|
+
*/
|
|
270
|
+
get stopped(): string | undefined;
|
|
254
271
|
/** The session's end once a response reported it, else undefined. */
|
|
255
272
|
get ended(): {
|
|
256
273
|
reason: SessionEnd;
|
package/dist/client.js
CHANGED
|
@@ -17,7 +17,9 @@ const TIERS = ["none", "process", "container", "kernel", "vm"];
|
|
|
17
17
|
/** Whether a tier the daemon reported meets a floor. An unknown tier meets nothing. */
|
|
18
18
|
export function meets(actual, floor) {
|
|
19
19
|
const a = TIERS.indexOf(actual);
|
|
20
|
-
|
|
20
|
+
const f = TIERS.indexOf(floor);
|
|
21
|
+
// A floor is process, container, kernel or vm; anything else is met by nothing.
|
|
22
|
+
return a >= 0 && f >= 1 && a >= f;
|
|
21
23
|
}
|
|
22
24
|
const DEFAULT_REQUEST_TIMEOUT_MS = 6 * 60_000;
|
|
23
25
|
function validateBaseUrl(raw, insecureHttp) {
|
|
@@ -171,6 +173,36 @@ function cellResult(resp, record) {
|
|
|
171
173
|
interpreterEnded: c.interpreterEnded ?? false,
|
|
172
174
|
};
|
|
173
175
|
}
|
|
176
|
+
// A lone surrogate has no UTF-8 form, so no protobuf string can hold one, though JSON
|
|
177
|
+
// carries it as an escape: the daemon would refuse the request after it arrived, with
|
|
178
|
+
// no not-dispatched mark. Every request is checked here before it is sent instead.
|
|
179
|
+
function refuseIllFormed(v, at) {
|
|
180
|
+
if (typeof v === "string") {
|
|
181
|
+
if (!v.isWellFormed()) {
|
|
182
|
+
throw new PlimsollError("invalid_argument", `plimsoll: ${at} is not well-formed text (a lone surrogate)`, { notDispatched: "request" });
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
else if (Array.isArray(v)) {
|
|
186
|
+
v.forEach((x, i) => refuseIllFormed(x, `${at}[${i}]`));
|
|
187
|
+
}
|
|
188
|
+
else if (v !== null && typeof v === "object") {
|
|
189
|
+
for (const [k, x] of Object.entries(v))
|
|
190
|
+
refuseIllFormed(x, `${at}.${k}`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
// Reads an answer the daemon gave. A broken or hostile daemon can answer in any shape, so
|
|
194
|
+
// anything but a PlimsollError thrown while it is checked or decoded (a TypeError from a
|
|
195
|
+
// number where bytes belong, say) is data loss: the call may have run.
|
|
196
|
+
function decoded(read) {
|
|
197
|
+
try {
|
|
198
|
+
return read();
|
|
199
|
+
}
|
|
200
|
+
catch (e) {
|
|
201
|
+
if (e instanceof PlimsollError)
|
|
202
|
+
throw e;
|
|
203
|
+
throw new PlimsollError("data_loss", `plimsoll: the daemon's answer is malformed (${e instanceof Error ? e.message : String(e)})`, { cause: e });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
174
206
|
function digestPayload(p) {
|
|
175
207
|
if ("javascript" in p)
|
|
176
208
|
return { kind: "javascript", code: p.javascript.code, grantProfile: p.javascript.grantProfile ?? "" };
|
|
@@ -199,6 +231,11 @@ export class PlimsollClient {
|
|
|
199
231
|
}
|
|
200
232
|
/** @internal One unary Connect call with the JSON codec. */
|
|
201
233
|
async call(method, body, signal) {
|
|
234
|
+
// Aborted before it was sent (a session call waiting its turn, say): nothing left
|
|
235
|
+
// this process, so it is a refusal, not a call that may have run.
|
|
236
|
+
if (signal?.aborted)
|
|
237
|
+
throw new PlimsollError("canceled", `plimsoll: ${method} was canceled before it was sent`, { notDispatched: "request", cause: signal.reason });
|
|
238
|
+
refuseIllFormed(body, "the request");
|
|
202
239
|
const headers = { "Content-Type": "application/json", "Connect-Protocol-Version": "1" };
|
|
203
240
|
if (this.token)
|
|
204
241
|
headers["Authorization"] = `Bearer ${this.token}`;
|
|
@@ -251,6 +288,9 @@ export class PlimsollClient {
|
|
|
251
288
|
/** The daemon's own statement of its provider, tier and what it supports. */
|
|
252
289
|
async describe(signal) {
|
|
253
290
|
const m = await this.call("Describe", {}, signal);
|
|
291
|
+
return decoded(() => this.info(m));
|
|
292
|
+
}
|
|
293
|
+
info(m) {
|
|
254
294
|
const env = (e) => ({
|
|
255
295
|
identity: e?.identity ?? "",
|
|
256
296
|
softwareIdentity: e?.softwareIdentity ?? "",
|
|
@@ -268,6 +308,7 @@ export class PlimsollClient {
|
|
|
268
308
|
supportsSessions: m.supportsSessions ?? false,
|
|
269
309
|
sessionLifetimeMs: m.sessionLifetimeMs ?? 0,
|
|
270
310
|
sessionIdleTimeoutMs: m.sessionIdleTimeoutMs ?? 0,
|
|
311
|
+
sessionEnvironment: env(m.sessionEnvironment),
|
|
271
312
|
environments: {
|
|
272
313
|
javascript: env(m.javascriptEnvironment),
|
|
273
314
|
project: env(m.projectEnvironment),
|
|
@@ -285,12 +326,12 @@ export class PlimsollClient {
|
|
|
285
326
|
/** Runs a JavaScript snippet in a fresh sandbox. */
|
|
286
327
|
async runJavaScript(code, opts = {}) {
|
|
287
328
|
const resp = await this.exchange("Run", this.envelope(opts, validateRule(opts.software)), { javascript: { code, grantProfile: this.jsGrant || undefined } }, opts);
|
|
288
|
-
return finish(resp.run, resp.record, javascriptResult, "javascript", opts.minimumIsolation);
|
|
329
|
+
return decoded(() => finish(resp.run, resp.record, javascriptResult, "javascript", opts.minimumIsolation));
|
|
289
330
|
}
|
|
290
331
|
/** Writes a multi-file project into a fresh sandbox and runs its steps in order. */
|
|
291
332
|
async runProject(req, opts = {}) {
|
|
292
333
|
const resp = await this.exchange("Run", this.envelope(opts, validateRule(opts.software)), projectPayload(req, this.projectGrant), opts);
|
|
293
|
-
return finish(resp.run, resp.record, projectResult, "project", opts.minimumIsolation);
|
|
334
|
+
return decoded(() => finish(resp.run, resp.record, projectResult, "project", opts.minimumIsolation));
|
|
294
335
|
}
|
|
295
336
|
/**
|
|
296
337
|
* Opens a session: one sandbox kept for many calls, files persisting, and of
|
|
@@ -299,6 +340,11 @@ export class PlimsollClient {
|
|
|
299
340
|
*/
|
|
300
341
|
async openSession(opts = {}) {
|
|
301
342
|
const rule = validateRule(opts.software);
|
|
343
|
+
for (const l of opts.languages ?? []) {
|
|
344
|
+
if (l !== "javascript" && l !== "python") {
|
|
345
|
+
throw new PlimsollError("invalid_argument", `plimsoll: unknown language ${JSON.stringify(l)} in the hint`, { notDispatched: "request" });
|
|
346
|
+
}
|
|
347
|
+
}
|
|
302
348
|
const m = await this.call("OpenSession", {
|
|
303
349
|
protocol: PROTOCOL,
|
|
304
350
|
minimumIsolation: opts.minimumIsolation,
|
|
@@ -306,10 +352,13 @@ export class PlimsollClient {
|
|
|
306
352
|
lifetimeMs: durationMs(opts.lifetimeMs) || undefined,
|
|
307
353
|
idleTimeoutMs: durationMs(opts.idleTimeoutMs) || undefined,
|
|
308
354
|
softwareRule: rule,
|
|
355
|
+
languages: opts.languages?.length ? [...new Set(opts.languages)] : undefined,
|
|
309
356
|
}, opts.signal);
|
|
310
|
-
const s = new Session(this, m, rule);
|
|
311
|
-
if (s.fingerprint !== sessionFingerprint(m.sessionId ?? "")) {
|
|
312
|
-
|
|
357
|
+
const s = decoded(() => new Session(this, m, rule, opts.minimumIsolation));
|
|
358
|
+
if (decoded(() => s.fingerprint !== sessionFingerprint(m.sessionId ?? ""))) {
|
|
359
|
+
// The session exists on the daemon either way, and nothing else holds its ID.
|
|
360
|
+
await s.close().catch(() => undefined);
|
|
361
|
+
throw new PlimsollError("data_loss", "plimsoll: the daemon's session fingerprint does not match its session ID; the session was closed");
|
|
313
362
|
}
|
|
314
363
|
if (opts.minimumIsolation && !meets(s.isolation, opts.minimumIsolation)) {
|
|
315
364
|
await s.close().catch(() => undefined);
|
|
@@ -334,6 +383,9 @@ export class PlimsollClient {
|
|
|
334
383
|
// Sends one Run and checks its record.
|
|
335
384
|
async exchange(method, env, payload, opts) {
|
|
336
385
|
const resp = await this.call(method, { ...env, ...payload }, opts.signal);
|
|
386
|
+
return decoded(() => this.checked(env, payload, resp));
|
|
387
|
+
}
|
|
388
|
+
checked(env, payload, resp) {
|
|
337
389
|
const checked = checkRecord(requestDigest({ protocol: env.protocol, minimumIsolation: env.minimumIsolation ?? "", timeoutMs: env.timeoutMs ?? 0, softwareRule: env.softwareRule, payload: digestPayload(payload) }), env.protocol, env.softwareRule, resp);
|
|
338
390
|
if ("problem" in checked)
|
|
339
391
|
throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { result: resp });
|
|
@@ -382,12 +434,16 @@ export class Session {
|
|
|
382
434
|
/** The tier the daemon measured when the session opened. */
|
|
383
435
|
isolation;
|
|
384
436
|
sandbox;
|
|
437
|
+
/** The selected software the daemon stated at open. */
|
|
438
|
+
softwareIdentity;
|
|
385
439
|
expiresAtMs;
|
|
386
440
|
idleTimeoutMs;
|
|
387
441
|
// The session ID is a capability: it goes to the daemon and nowhere else.
|
|
388
442
|
#id;
|
|
389
443
|
#client;
|
|
390
444
|
#rule;
|
|
445
|
+
// The floor given at open: every call carries it unless the call asks for more.
|
|
446
|
+
#floor;
|
|
391
447
|
#calls = 0n;
|
|
392
448
|
#last = "";
|
|
393
449
|
#end;
|
|
@@ -397,16 +453,25 @@ export class Session {
|
|
|
397
453
|
#unknown;
|
|
398
454
|
#queue = Promise.resolve();
|
|
399
455
|
/** @internal */
|
|
400
|
-
constructor(client, m, rule) {
|
|
456
|
+
constructor(client, m, rule, floor) {
|
|
401
457
|
this.#client = client;
|
|
402
458
|
this.#id = m.sessionId ?? "";
|
|
403
459
|
this.#rule = rule;
|
|
460
|
+
this.#floor = floor;
|
|
404
461
|
this.fingerprint = m.session ?? "";
|
|
405
462
|
this.isolation = m.isolation ?? "";
|
|
406
463
|
this.sandbox = m.sandbox ?? "";
|
|
464
|
+
this.softwareIdentity = m.softwareIdentity ?? "";
|
|
407
465
|
this.expiresAtMs = num(m.expiresUnixMs);
|
|
408
466
|
this.idleTimeoutMs = m.idleTimeoutMs ?? 0;
|
|
409
467
|
}
|
|
468
|
+
/**
|
|
469
|
+
* Why this client sends nothing more on the session, once a call ended without an
|
|
470
|
+
* answer it could check (the call may have run); undefined while it is usable.
|
|
471
|
+
*/
|
|
472
|
+
get stopped() {
|
|
473
|
+
return this.#unknown;
|
|
474
|
+
}
|
|
410
475
|
/** The session's end once a response reported it, else undefined. */
|
|
411
476
|
get ended() {
|
|
412
477
|
return this.#end;
|
|
@@ -416,13 +481,15 @@ export class Session {
|
|
|
416
481
|
return { calls: this.#calls, lastRecordSha256: this.#last };
|
|
417
482
|
}
|
|
418
483
|
async runJavaScript(code, opts = {}) {
|
|
484
|
+
opts = this.#withFloor(opts);
|
|
419
485
|
const run = await this.#call({ javascript: { code, grantProfile: this.#client.jsGrant || undefined } }, opts);
|
|
420
|
-
return finish(run.run, run.record, javascriptResult, "javascript", opts.minimumIsolation);
|
|
486
|
+
return decoded(() => finish(run.run, run.record, javascriptResult, "javascript", opts.minimumIsolation));
|
|
421
487
|
}
|
|
422
488
|
/** Runs a project in the session; its files persist for later calls. */
|
|
423
489
|
async runProject(req, opts = {}) {
|
|
490
|
+
opts = this.#withFloor(opts);
|
|
424
491
|
const run = await this.#call(projectPayload(req, this.#client.projectGrant), opts);
|
|
425
|
-
return finish(run.run, run.record, projectResult, "project", opts.minimumIsolation);
|
|
492
|
+
return decoded(() => finish(run.run, run.record, projectResult, "project", opts.minimumIsolation));
|
|
426
493
|
}
|
|
427
494
|
/**
|
|
428
495
|
* Runs code in the session's interpreter for req.language, which keeps what
|
|
@@ -434,9 +501,18 @@ export class Session {
|
|
|
434
501
|
if (req.language !== "javascript" && req.language !== "python") {
|
|
435
502
|
throw new PlimsollError("invalid_argument", `plimsoll: unknown cell language ${JSON.stringify(req.language)}`, { notDispatched: "request" });
|
|
436
503
|
}
|
|
504
|
+
opts = this.#withFloor(opts);
|
|
437
505
|
const files = (req.files ?? []).map((f) => ({ path: f.path, content: f.content }));
|
|
438
506
|
const run = await this.#call({ cell: { language: req.language, code: req.code, files } }, opts);
|
|
439
|
-
return finish(run.run, run.record, cellResult, "cell", opts.minimumIsolation);
|
|
507
|
+
return decoded(() => finish(run.run, run.record, cellResult, "cell", opts.minimumIsolation));
|
|
508
|
+
}
|
|
509
|
+
// The call's options with the session's floor, unless the call asks for more.
|
|
510
|
+
#withFloor(opts) {
|
|
511
|
+
const a = this.#floor;
|
|
512
|
+
const b = opts.minimumIsolation;
|
|
513
|
+
if (!a || (b && TIERS.indexOf(b) >= TIERS.indexOf(a)))
|
|
514
|
+
return opts;
|
|
515
|
+
return { ...opts, minimumIsolation: a };
|
|
440
516
|
}
|
|
441
517
|
#serial(f) {
|
|
442
518
|
const next = this.#queue.then(f, f);
|
|
@@ -450,6 +526,8 @@ export class Session {
|
|
|
450
526
|
throw new PlimsollError("failed_precondition", `plimsoll: an earlier call of this session ended without an answer this client could check (${this.#unknown}); it may have run, so this client sends nothing more on the session: open a new one`, { notDispatched: "request" });
|
|
451
527
|
}
|
|
452
528
|
const env = this.#client.envelope(opts, rule);
|
|
529
|
+
// Before the digest, which cannot encode such text either.
|
|
530
|
+
refuseIllFormed({ ...env, ...payload }, "the request");
|
|
453
531
|
const digest = requestDigest({ protocol: env.protocol, minimumIsolation: env.minimumIsolation ?? "", timeoutMs: env.timeoutMs ?? 0, softwareRule: rule, payload: digestPayload(payload) });
|
|
454
532
|
try {
|
|
455
533
|
return await this.#exchange(payload, opts, rule, env, digest);
|
|
@@ -460,13 +538,24 @@ export class Session {
|
|
|
460
538
|
if (e instanceof PlimsollError && e.unanswered) {
|
|
461
539
|
// The call may have run, and the daemon chained its record: check it and keep
|
|
462
540
|
// it in the chain, so the session goes on and the call is not hidden.
|
|
463
|
-
|
|
541
|
+
let checked = checkUnanswered(digest, env.minimumIsolation ?? "", rule, e.unanswered, this.fingerprint, this.#calls, this.#last);
|
|
542
|
+
if ("record" in checked) {
|
|
543
|
+
// With no response to compare it with, the record's evidence must be what the
|
|
544
|
+
// session stated at open.
|
|
545
|
+
const r = checked.record;
|
|
546
|
+
if (r.provider !== this.sandbox || r.isolation !== this.isolation || r.softwareIdentity !== this.softwareIdentity) {
|
|
547
|
+
checked = {
|
|
548
|
+
problem: `the unanswered call's record names ${r.provider} at "${r.isolation}" running "${r.softwareIdentity}", the session opened as ${this.sandbox} at "${this.isolation}" running "${this.softwareIdentity}"`,
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
}
|
|
464
552
|
if ("problem" in checked) {
|
|
465
553
|
this.#unknown = checked.problem;
|
|
466
554
|
throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { cause: e });
|
|
467
555
|
}
|
|
468
556
|
this.#calls = checked.record.sequence;
|
|
469
557
|
this.#last = checked.record.sha256;
|
|
558
|
+
e.record = checked.record; // the checked record, as Go's UnansweredCallError carries it
|
|
470
559
|
throw e;
|
|
471
560
|
}
|
|
472
561
|
this.#unknown = e instanceof Error ? e.message : String(e);
|
|
@@ -475,33 +564,34 @@ export class Session {
|
|
|
475
564
|
});
|
|
476
565
|
}
|
|
477
566
|
async #exchange(payload, opts, rule, env, digest) {
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
this.#calls
|
|
502
|
-
this.#last = r.sha256;
|
|
503
|
-
return { run, record: r };
|
|
567
|
+
let m;
|
|
568
|
+
try {
|
|
569
|
+
m = await this.#client.call("SessionRun", { ...env, sessionId: this.#id, ...payload }, opts.signal);
|
|
570
|
+
}
|
|
571
|
+
catch (e) {
|
|
572
|
+
if (e instanceof PlimsollError && e.sessionEnded)
|
|
573
|
+
this.#end = e.sessionEnded;
|
|
574
|
+
throw e;
|
|
575
|
+
}
|
|
576
|
+
return decoded(() => this.#chained(m, env, rule, digest));
|
|
577
|
+
}
|
|
578
|
+
#chained(m, env, rule, digest) {
|
|
579
|
+
const run = m.run;
|
|
580
|
+
if (!run)
|
|
581
|
+
throw new PlimsollError("data_loss", "plimsoll: the session call's answer carries no run");
|
|
582
|
+
const end = sessionEndFromWire(m.ended);
|
|
583
|
+
if (end !== "open")
|
|
584
|
+
this.#end = { reason: end, detail: m.endDetail ?? "" };
|
|
585
|
+
const checked = checkRecord(digest, env.protocol, rule, run);
|
|
586
|
+
if ("problem" in checked)
|
|
587
|
+
throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { result: run });
|
|
588
|
+
const r = checked.record;
|
|
589
|
+
if (r.session !== this.fingerprint || r.sequence !== this.#calls + 1n || r.previousSha256 !== this.#last) {
|
|
590
|
+
throw new PlimsollError("data_loss", `plimsoll: the session's chain is broken: call ${r.sequence} after "${r.previousSha256}", this client's last was call ${this.#calls}, "${this.#last}"`, { result: run });
|
|
504
591
|
}
|
|
592
|
+
this.#calls = r.sequence;
|
|
593
|
+
this.#last = r.sha256;
|
|
594
|
+
return { run, record: r };
|
|
505
595
|
}
|
|
506
596
|
/**
|
|
507
597
|
* Ends the session (or collects one that ended by itself) and checks the
|
|
@@ -510,12 +600,12 @@ export class Session {
|
|
|
510
600
|
close(signal) {
|
|
511
601
|
return this.#serial(async () => {
|
|
512
602
|
const m = await this.#client.call("CloseSession", { protocol: PROTOCOL, sessionId: this.#id }, signal);
|
|
513
|
-
const sum = {
|
|
603
|
+
const sum = decoded(() => ({
|
|
514
604
|
session: m.session ?? "",
|
|
515
605
|
calls: BigInt(m.calls ?? 0),
|
|
516
606
|
lastRecordSha256: m.lastRecordSha256 ?? "",
|
|
517
607
|
end: sessionEndFromWire(m.ended),
|
|
518
|
-
};
|
|
608
|
+
}));
|
|
519
609
|
this.#end ??= { reason: sum.end, detail: "" };
|
|
520
610
|
if (sum.session !== this.fingerprint || sum.calls !== this.#calls || sum.lastRecordSha256 !== this.#last) {
|
|
521
611
|
throw new PlimsollError("data_loss", `plimsoll: the daemon counts ${sum.calls} calls ending "${sum.lastRecordSha256}", this client saw ${this.#calls} ending "${this.#last}"`, { result: sum });
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { RunRecord } from "./record.ts";
|
|
1
2
|
import type { WireError, WireRecord } from "./wire.ts";
|
|
2
3
|
/** Why a request was refused before any code ran (plimsoll.v1.NotDispatchedReason). */
|
|
3
4
|
export type Refusal = "request" | "permission" | "protocol" | "unsupported" | "isolation" | "capacity" | "environment" | "unknown";
|
|
@@ -33,6 +34,11 @@ export declare class PlimsollError extends Error {
|
|
|
33
34
|
* and keeps it in its chain, so the session goes on; the call's outcome is unknown.
|
|
34
35
|
*/
|
|
35
36
|
readonly unanswered: WireRecord | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* That record once the Session has checked it against the call and its chain (Go:
|
|
39
|
+
* UnansweredCallError.Record); undefined otherwise.
|
|
40
|
+
*/
|
|
41
|
+
record: RunRecord | undefined;
|
|
36
42
|
constructor(code: Code, message: string, opts?: {
|
|
37
43
|
notDispatched?: Refusal;
|
|
38
44
|
sessionEnded?: {
|
|
@@ -45,5 +51,4 @@ export declare class PlimsollError extends Error {
|
|
|
45
51
|
});
|
|
46
52
|
}
|
|
47
53
|
export declare function sessionEndFromWire(v: string | number | undefined): SessionEnd;
|
|
48
|
-
/** The error a Connect error body describes, with its plimsoll details restored. */
|
|
49
54
|
export declare function errorFromWire(httpStatus: number, body: WireError | undefined): PlimsollError;
|
package/dist/errors.js
CHANGED
|
@@ -23,6 +23,11 @@ export class PlimsollError extends Error {
|
|
|
23
23
|
* and keeps it in its chain, so the session goes on; the call's outcome is unknown.
|
|
24
24
|
*/
|
|
25
25
|
unanswered;
|
|
26
|
+
/**
|
|
27
|
+
* That record once the Session has checked it against the call and its chain (Go:
|
|
28
|
+
* UnansweredCallError.Record); undefined otherwise.
|
|
29
|
+
*/
|
|
30
|
+
record;
|
|
26
31
|
constructor(code, message, opts = {}) {
|
|
27
32
|
super(message, opts.cause === undefined ? undefined : { cause: opts.cause });
|
|
28
33
|
this.name = "PlimsollError";
|
|
@@ -167,12 +172,20 @@ function decodeRecord(b) {
|
|
|
167
172
|
return m;
|
|
168
173
|
}
|
|
169
174
|
/** The error a Connect error body describes, with its plimsoll details restored. */
|
|
175
|
+
const CODES = new Set([
|
|
176
|
+
"canceled", "unknown", "invalid_argument", "deadline_exceeded", "not_found", "already_exists", "permission_denied", "resource_exhausted",
|
|
177
|
+
"failed_precondition", "aborted", "out_of_range", "unimplemented", "internal", "unavailable", "data_loss", "unauthenticated",
|
|
178
|
+
]);
|
|
179
|
+
// The body is whatever the daemon sent, so each field is used only in the shape Connect
|
|
180
|
+
// gives it, and a code outside Connect's set is "unknown".
|
|
170
181
|
export function errorFromWire(httpStatus, body) {
|
|
171
|
-
const
|
|
182
|
+
const wire = body !== null && typeof body === "object" && !Array.isArray(body) ? body : undefined;
|
|
183
|
+
const code = wire?.code === undefined ? httpStatusCode(httpStatus) : CODES.has(wire.code) ? wire.code : "unknown";
|
|
184
|
+
const message = typeof wire?.message === "string" ? wire.message : `HTTP ${httpStatus}`;
|
|
172
185
|
let notDispatched;
|
|
173
186
|
let sessionEnded;
|
|
174
187
|
let unanswered;
|
|
175
|
-
for (const d of
|
|
188
|
+
for (const d of Array.isArray(wire?.details) ? wire.details : []) {
|
|
176
189
|
try {
|
|
177
190
|
const bytes = Buffer.from(d.value ?? "", "base64");
|
|
178
191
|
if (d.type === "plimsoll.v1.NotDispatched") {
|
|
@@ -190,7 +203,7 @@ export function errorFromWire(httpStatus, body) {
|
|
|
190
203
|
// An undecodable detail states nothing; in particular not that nothing ran.
|
|
191
204
|
}
|
|
192
205
|
}
|
|
193
|
-
return new PlimsollError(code,
|
|
206
|
+
return new PlimsollError(code, message, { notDispatched, sessionEnded, unanswered: notDispatched ? undefined : unanswered });
|
|
194
207
|
}
|
|
195
208
|
// Connect's mapping for a response without a Connect error body.
|
|
196
209
|
function httpStatusCode(status) {
|
package/dist/mastra.d.ts
CHANGED
|
@@ -21,7 +21,7 @@ export declare function plimsollExecuteCode(opts: PlimsollExecuteCodeOptions): {
|
|
|
21
21
|
freshSandbox?: true | undefined;
|
|
22
22
|
isolation: string;
|
|
23
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
|
|
24
|
+
/** Closes a user's thread's sandbox, e.g. when the conversation ends. */
|
|
25
|
+
dispose: (threadId: string, resourceId: string) => Promise<void>;
|
|
26
26
|
sandboxes: CodeSandboxes;
|
|
27
27
|
};
|
package/dist/mastra.js
CHANGED
|
@@ -5,8 +5,12 @@
|
|
|
5
5
|
import { createTool } from "@mastra/core/tools";
|
|
6
6
|
import { CodeSandboxes } from "./sandboxes.js";
|
|
7
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
|
-
|
|
8
|
+
// A thread id is unique only within its resource (the user), so the key is both, and a
|
|
9
|
+
// call without either has no key and runs fresh. An empty resource would put every user
|
|
10
|
+
// without one whose thread id collided into one sandbox, with each other's files and
|
|
11
|
+
// variables. The pair is encoded as JSON, not joined with a separator: a resource ending
|
|
12
|
+
// in the separator and a thread starting with it would name another user's key.
|
|
13
|
+
const threadKey = (threadId, resourceId) => threadId && resourceId ? JSON.stringify([resourceId, threadId]) : undefined;
|
|
10
14
|
export function plimsollExecuteCode(opts) {
|
|
11
15
|
const sandboxes = new CodeSandboxes(opts);
|
|
12
16
|
const executeCode = createTool({
|
|
@@ -14,17 +18,19 @@ export function plimsollExecuteCode(opts) {
|
|
|
14
18
|
description: executeCodeDescription(sandboxes.languages),
|
|
15
19
|
inputSchema: executeCodeInput(sandboxes.languages),
|
|
16
20
|
outputSchema: executeCodeOutput,
|
|
17
|
-
// The thread scopes the sandbox. A call outside a thread
|
|
18
|
-
// sandbox shared across conversations would show one user
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
return sandboxes.run(thread ? threadKey(thread, ctx?.agent?.resourceId) : undefined, input, ctx?.abortSignal);
|
|
22
|
-
},
|
|
21
|
+
// The user's thread scopes the sandbox. A call outside a thread, or without a
|
|
22
|
+
// resource, runs fresh: one sandbox shared across conversations would show one user
|
|
23
|
+
// another's files.
|
|
24
|
+
execute: async (input, ctx) => sandboxes.run(threadKey(ctx?.agent?.threadId, ctx?.agent?.resourceId), input, ctx?.abortSignal),
|
|
23
25
|
});
|
|
24
26
|
return {
|
|
25
27
|
executeCode,
|
|
26
|
-
/** Closes a thread's sandbox, e.g. when the conversation ends. */
|
|
27
|
-
dispose: (threadId, resourceId) =>
|
|
28
|
+
/** Closes a user's thread's sandbox, e.g. when the conversation ends. */
|
|
29
|
+
dispose: async (threadId, resourceId) => {
|
|
30
|
+
const key = threadKey(threadId, resourceId);
|
|
31
|
+
if (key !== undefined)
|
|
32
|
+
await sandboxes.dispose(key);
|
|
33
|
+
},
|
|
28
34
|
sandboxes,
|
|
29
35
|
};
|
|
30
36
|
}
|
package/dist/record.d.ts
CHANGED
|
@@ -73,10 +73,11 @@ export declare function softwareRuleAllows(rule: WireSoftwareRule | undefined, i
|
|
|
73
73
|
/**
|
|
74
74
|
* Checks the record the daemon sends with an unanswered session call's error
|
|
75
75
|
* (record.CheckUnanswered): version 3, no result digest, a Connect code, the digest of
|
|
76
|
-
* the request sent, its software rule
|
|
76
|
+
* the request sent, its software rule and that its software is in it, its own digest,
|
|
77
|
+
* its tier against the call's floor, and its place in the chain.
|
|
77
78
|
* Returns the reason it does not check, or the record.
|
|
78
79
|
*/
|
|
79
|
-
export declare function checkUnanswered(reqDigest: string, rule: WireSoftwareRule | undefined, m: WireRecord, fingerprint: string, prevSeq: bigint, prev: string): {
|
|
80
|
+
export declare function checkUnanswered(reqDigest: string, floor: string, rule: WireSoftwareRule | undefined, m: WireRecord, fingerprint: string, prevSeq: bigint, prev: string): {
|
|
80
81
|
record: RunRecord;
|
|
81
82
|
} | {
|
|
82
83
|
problem: string;
|
package/dist/record.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// SHA-256 over a length-prefixed encoding, never over protobuf or JSON bytes.
|
|
3
3
|
// The golden vectors in record/record_test.go are checked in test/record.test.ts.
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
|
+
import { PlimsollError } from "./errors.js";
|
|
5
6
|
/** The record encoding version of an answered call, which this client computes and checks. */
|
|
6
7
|
export const RECORD_VERSION = 2;
|
|
7
8
|
/** The record encoding version of a session call that may have run but ended in an error. */
|
|
@@ -27,6 +28,10 @@ class Encoder {
|
|
|
27
28
|
this.value(v);
|
|
28
29
|
}
|
|
29
30
|
str(name, v) {
|
|
31
|
+
// A lone surrogate (JSON can escape one) has no UTF-8 form: Buffer would put
|
|
32
|
+
// U+FFFD in its place and digest other bytes than the daemon did.
|
|
33
|
+
if (!v.isWellFormed())
|
|
34
|
+
throw new PlimsollError("data_loss", `plimsoll: ${name} is not well-formed text (a lone surrogate)`);
|
|
30
35
|
this.bytes(name, Buffer.from(v, "utf8"));
|
|
31
36
|
}
|
|
32
37
|
// Integers are decimal ASCII; callers pass bigint for 64-bit values so no
|
|
@@ -162,6 +167,16 @@ export function resultDigest(resp) {
|
|
|
162
167
|
}
|
|
163
168
|
return e.sum();
|
|
164
169
|
}
|
|
170
|
+
// big reads a 64-bit integer field the JSON codec sends as a decimal string (or a
|
|
171
|
+
// number). Anything else is an answer this client cannot read, a PlimsollError,
|
|
172
|
+
// never BigInt's own SyntaxError or RangeError.
|
|
173
|
+
function big(v, name) {
|
|
174
|
+
if (v === undefined)
|
|
175
|
+
return 0n;
|
|
176
|
+
if ((typeof v === "string" && /^-?[0-9]{1,20}$/.test(v)) || (typeof v === "number" && Number.isSafeInteger(v)))
|
|
177
|
+
return BigInt(v);
|
|
178
|
+
throw new PlimsollError("data_loss", `plimsoll: the record's ${name} is not an integer`);
|
|
179
|
+
}
|
|
165
180
|
export function recordFromWire(m) {
|
|
166
181
|
return {
|
|
167
182
|
version: m.version ?? 0,
|
|
@@ -173,10 +188,10 @@ export function recordFromWire(m) {
|
|
|
173
188
|
policy: m.policy ?? "",
|
|
174
189
|
softwareIdentity: m.softwareIdentity ?? "",
|
|
175
190
|
softwareRuleId: m.softwareRuleId ?? "",
|
|
176
|
-
startedUnixMs:
|
|
177
|
-
endedUnixMs:
|
|
191
|
+
startedUnixMs: big(m.startedUnixMs, "startedUnixMs"),
|
|
192
|
+
endedUnixMs: big(m.endedUnixMs, "endedUnixMs"),
|
|
178
193
|
session: m.session ?? "",
|
|
179
|
-
sequence:
|
|
194
|
+
sequence: big(m.sequence, "sequence"),
|
|
180
195
|
previousSha256: m.previousSha256 ?? "",
|
|
181
196
|
unanswered: m.unanswered ?? "",
|
|
182
197
|
sha256: m.recordSha256 ?? "",
|
|
@@ -226,13 +241,16 @@ export function softwareRuleAllows(rule, identity) {
|
|
|
226
241
|
return true;
|
|
227
242
|
return identity !== "" && rule.identities.includes(identity);
|
|
228
243
|
}
|
|
244
|
+
// The tiers, weakest first, as client.ts's TIERS (which imports this module).
|
|
245
|
+
const TIER_ORDER = ["none", "process", "container", "kernel", "vm"];
|
|
229
246
|
/**
|
|
230
247
|
* Checks the record the daemon sends with an unanswered session call's error
|
|
231
248
|
* (record.CheckUnanswered): version 3, no result digest, a Connect code, the digest of
|
|
232
|
-
* the request sent, its software rule
|
|
249
|
+
* the request sent, its software rule and that its software is in it, its own digest,
|
|
250
|
+
* its tier against the call's floor, and its place in the chain.
|
|
233
251
|
* Returns the reason it does not check, or the record.
|
|
234
252
|
*/
|
|
235
|
-
export function checkUnanswered(reqDigest, rule, m, fingerprint, prevSeq, prev) {
|
|
253
|
+
export function checkUnanswered(reqDigest, floor, rule, m, fingerprint, prevSeq, prev) {
|
|
236
254
|
const r = recordFromWire(m);
|
|
237
255
|
if (r.version !== UNANSWERED_RECORD_VERSION)
|
|
238
256
|
return { problem: `an unanswered call's record is version ${r.version}` };
|
|
@@ -240,10 +258,14 @@ export function checkUnanswered(reqDigest, rule, m, fingerprint, prevSeq, prev)
|
|
|
240
258
|
return { problem: "an unanswered call's record states a result or no error code" };
|
|
241
259
|
if (r.requestSha256 !== reqDigest)
|
|
242
260
|
return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
|
|
243
|
-
if (r.softwareRuleId !== softwareRuleId(rule))
|
|
244
|
-
return { problem: "the record's software rule is not the request's" };
|
|
261
|
+
if (r.softwareRuleId !== softwareRuleId(rule) || !softwareRuleAllows(rule, r.softwareIdentity)) {
|
|
262
|
+
return { problem: "the record's software rule is not the request's, or its software is not in it" };
|
|
263
|
+
}
|
|
245
264
|
if (r.sha256 !== recordDigest(r))
|
|
246
265
|
return { problem: `record digest ${r.sha256}, its fields digest to ${recordDigest(r)}` };
|
|
266
|
+
if (floor !== "" && !(TIER_ORDER.indexOf(r.isolation) >= TIER_ORDER.indexOf(floor) && TIER_ORDER.indexOf(r.isolation) >= 0)) {
|
|
267
|
+
return { problem: `the unanswered call's record states ${r.isolation || "unknown"}, below the call's minimum ${floor}; execution may have occurred` };
|
|
268
|
+
}
|
|
247
269
|
if (r.session !== fingerprint || r.sequence !== prevSeq + 1n || r.previousSha256 !== prev) {
|
|
248
270
|
return { problem: `the session's chain is broken: call ${r.sequence} after "${r.previousSha256}", this client's last was call ${prevSeq}, "${prev}"` };
|
|
249
271
|
}
|
|
@@ -265,6 +287,8 @@ export function checkRecord(reqDigest, protocol, rule, resp) {
|
|
|
265
287
|
return { problem: `protocol ${protocol} requires record version ${RECORD_VERSION}` };
|
|
266
288
|
if (r.version === 1 && (r.softwareIdentity !== "" || r.softwareRuleId !== ""))
|
|
267
289
|
return { problem: "a version 1 record cannot carry software fields" };
|
|
290
|
+
if (r.unanswered !== "")
|
|
291
|
+
return { problem: `an answered call's record states an unanswered code, which version ${r.version} does not cover` };
|
|
268
292
|
if (r.requestSha256 !== reqDigest)
|
|
269
293
|
return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
|
|
270
294
|
if (r.resultSha256 !== result)
|
package/dist/sandboxes.js
CHANGED
|
@@ -51,25 +51,25 @@ export const RUNNERS = {
|
|
|
51
51
|
path: ".plimsoll/run.py",
|
|
52
52
|
file: ".plimsoll/cell.py",
|
|
53
53
|
step: "python3 -I .plimsoll/run.py",
|
|
54
|
+
// As the session kernel runs a cell: at module level, an event loop only for code
|
|
55
|
+
// that awaits at the top level, so the cell's own asyncio.run works.
|
|
54
56
|
source: [
|
|
55
|
-
"import ast, asyncio, inspect, sys",
|
|
57
|
+
"import ast, asyncio, inspect, linecache, sys",
|
|
56
58
|
"sys.path.insert(0, '')",
|
|
57
59
|
"src = open('.plimsoll/cell.py').read()",
|
|
60
|
+
"linecache.cache['cell'] = (len(src), None, src.splitlines(True), 'cell')",
|
|
58
61
|
"tree = ast.parse(src, 'cell', 'exec')",
|
|
59
62
|
"last = ast.Expression(tree.body.pop().value) if tree.body and isinstance(tree.body[-1], ast.Expr) else None",
|
|
60
|
-
"ns = {'__name__': '__main__'}",
|
|
63
|
+
"ns = {'__name__': '__main__', '__builtins__': __builtins__}",
|
|
61
64
|
"flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT",
|
|
62
|
-
"
|
|
63
|
-
"
|
|
64
|
-
" if inspect.
|
|
65
|
-
"
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
"
|
|
69
|
-
"
|
|
70
|
-
" if value is not None:",
|
|
71
|
-
" print(repr(value))",
|
|
72
|
-
"asyncio.run(main())",
|
|
65
|
+
"loop = asyncio.new_event_loop()",
|
|
66
|
+
"def settle(r):",
|
|
67
|
+
" return loop.run_until_complete(r) if inspect.isawaitable(r) else r",
|
|
68
|
+
"settle(eval(compile(tree, 'cell', 'exec', flags=flags), ns))",
|
|
69
|
+
"if last is not None:",
|
|
70
|
+
" value = settle(eval(compile(last, 'cell', 'eval', flags=flags), ns))",
|
|
71
|
+
" if value is not None:",
|
|
72
|
+
" print(repr(value))",
|
|
73
73
|
"",
|
|
74
74
|
].join("\n"),
|
|
75
75
|
},
|
|
@@ -79,7 +79,10 @@ export const RUNNERS = {
|
|
|
79
79
|
step: "node --expose-internals .plimsoll/run.cjs",
|
|
80
80
|
source: [
|
|
81
81
|
"const fs = require('node:fs'), util = require('node:util'), vm = require('node:vm');",
|
|
82
|
+
// The names a cell in the session's `node -e` interpreter sees as globals.
|
|
82
83
|
"globalThis.require = require('node:module').createRequire(process.cwd() + '/');",
|
|
84
|
+
"globalThis.module = { exports: {} }; globalThis.exports = globalThis.module.exports;",
|
|
85
|
+
"globalThis.__dirname = '.'; globalThis.__filename = '[eval]';",
|
|
83
86
|
"let tla = null;",
|
|
84
87
|
"try { tla = require('internal/repl/await').processTopLevelAwait; } catch {}",
|
|
85
88
|
"const src = fs.readFileSync('.plimsoll/cell.js', 'utf8');",
|
|
@@ -143,6 +146,14 @@ export class CodeSandboxes {
|
|
|
143
146
|
}
|
|
144
147
|
/** Runs one call of the tool under the key. */
|
|
145
148
|
async run(key, input, signal) {
|
|
149
|
+
// A fresh run's runner and cell file live under .plimsoll/; a file of the call's own
|
|
150
|
+
// there would replace them.
|
|
151
|
+
const reserved = (input.files ?? []).find((f) => f.path === ".plimsoll" || f.path.startsWith(".plimsoll/"));
|
|
152
|
+
if (reserved) {
|
|
153
|
+
throw new PlimsollError("invalid_argument", `plimsoll: ${JSON.stringify(reserved.path)} is under .plimsoll/, which the sandbox's runner reserves`, {
|
|
154
|
+
notDispatched: "request",
|
|
155
|
+
});
|
|
156
|
+
}
|
|
146
157
|
const language = input.language ?? this.languages[0];
|
|
147
158
|
if (!this.languages.includes(language)) {
|
|
148
159
|
throw new PlimsollError("invalid_argument", `plimsoll: this tool runs ${this.languages.join(" or ")}, not ${language}`, { notDispatched: "request" });
|
|
@@ -171,8 +182,10 @@ export class CodeSandboxes {
|
|
|
171
182
|
let session;
|
|
172
183
|
try {
|
|
173
184
|
session = await entry.session;
|
|
174
|
-
const first = !entry.answered;
|
|
175
185
|
const r = await session.runCell({ language, code: input.code, files }, opts);
|
|
186
|
+
// Read once the call has answered: the session runs its calls in order, so of
|
|
187
|
+
// calls made at once only the first to answer finds the sandbox new.
|
|
188
|
+
const first = !entry.answered;
|
|
176
189
|
entry.answered = true;
|
|
177
190
|
// What the call defined, and the files it wrote, can be there for the next call
|
|
178
191
|
// only if its interpreter, and the sandbox, outlived it; the next call's fresh
|
|
@@ -197,10 +210,11 @@ export class CodeSandboxes {
|
|
|
197
210
|
this.#drop(key, session);
|
|
198
211
|
continue;
|
|
199
212
|
}
|
|
200
|
-
// A call that may have run without an answer
|
|
201
|
-
// (the Session refuses its later calls), so the next call
|
|
202
|
-
// sandbox and says so with freshSandbox.
|
|
203
|
-
|
|
213
|
+
// A call that may have run without an answer this client could check leaves
|
|
214
|
+
// the session unusable (the Session refuses its later calls), so the next call
|
|
215
|
+
// opens a new sandbox and says so with freshSandbox. One whose record the
|
|
216
|
+
// Session checked and chained (e.record) leaves it usable, and so does a refusal.
|
|
217
|
+
if (session && (session.stopped !== undefined || session.ended !== undefined))
|
|
204
218
|
this.#drop(key, session);
|
|
205
219
|
throw e;
|
|
206
220
|
}
|
|
@@ -282,10 +296,13 @@ export class CodeSandboxes {
|
|
|
282
296
|
const session = this.persistent().then((ok) => {
|
|
283
297
|
if (!ok)
|
|
284
298
|
throw new PlimsollError("unimplemented", "plimsoll: the daemon does not keep sessions", { notDispatched: "unsupported" });
|
|
299
|
+
// The tool's languages are the hint: a daemon with a warm pool hands over a
|
|
300
|
+
// sandbox with their interpreters running, and drops any it does not run.
|
|
285
301
|
return this.client.openSession({
|
|
286
302
|
minimumIsolation: this.#opts.minimumIsolation,
|
|
287
303
|
lifetimeMs: this.#opts.sessionLifetimeMs,
|
|
288
304
|
idleTimeoutMs: this.#opts.sessionIdleTimeoutMs,
|
|
305
|
+
languages: [...this.languages],
|
|
289
306
|
});
|
|
290
307
|
});
|
|
291
308
|
const e = { session, answered: false, busy: 0 };
|
package/dist/tool.js
CHANGED
|
@@ -6,7 +6,7 @@ const NAMES = { python: "Python", javascript: "JavaScript (Node.js)" };
|
|
|
6
6
|
/** The tool's description for the languages it offers. */
|
|
7
7
|
export function executeCodeDescription(languages = DEFAULT_LANGUAGES) {
|
|
8
8
|
const names = languages.map((l) => NAMES[l]).join(" or ");
|
|
9
|
-
return (`Run ${names} in an isolated sandbox with no network access and return its exit code, stdout and stderr. ` +
|
|
9
|
+
return (`Run ${names} in an isolated sandbox with no network access (beyond any API the operator granted it) and return its exit code, stdout and stderr. ` +
|
|
10
10
|
"The value of the code's last expression is printed, as in a notebook, so the last line can simply name what you want to see. " +
|
|
11
11
|
"Within one conversation the sandbox usually keeps an interpreter per language between calls, so variables, functions, imports and loaded data " +
|
|
12
12
|
"from earlier calls are still defined: the result's stateKept says whether this call's interpreter was still running when it answered, so what it defined can still be there " +
|
package/dist/wire.d.ts
CHANGED
|
@@ -153,6 +153,7 @@ export type WireDescribeResponse = {
|
|
|
153
153
|
supportsSessions?: boolean;
|
|
154
154
|
sessionLifetimeMs?: number;
|
|
155
155
|
sessionIdleTimeoutMs?: number;
|
|
156
|
+
sessionEnvironment?: WirePayloadEnvironment;
|
|
156
157
|
};
|
|
157
158
|
export type WireOpenSessionRequest = {
|
|
158
159
|
protocol: number;
|
|
@@ -161,6 +162,7 @@ export type WireOpenSessionRequest = {
|
|
|
161
162
|
lifetimeMs?: number;
|
|
162
163
|
idleTimeoutMs?: number;
|
|
163
164
|
softwareRule?: WireSoftwareRule;
|
|
165
|
+
languages?: string[];
|
|
164
166
|
};
|
|
165
167
|
export type WireOpenSessionResponse = {
|
|
166
168
|
sessionId?: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plimsollmark/client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"description": "TypeScript client for plimsolld, with Trigger.dev and Mastra executeCode add-ons",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"homepage": "https://github.com/plimsollmark/plimsoll/tree/main/clients/typescript#readme",
|
|
@@ -36,6 +36,9 @@
|
|
|
36
36
|
"files": [
|
|
37
37
|
"dist"
|
|
38
38
|
],
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public"
|
|
41
|
+
},
|
|
39
42
|
"engines": {
|
|
40
43
|
"node": ">=22.18"
|
|
41
44
|
},
|
|
@@ -46,10 +49,10 @@
|
|
|
46
49
|
"test": "cd ../.. && go test ./clients/typescript/"
|
|
47
50
|
},
|
|
48
51
|
"peerDependencies": {
|
|
49
|
-
"@mastra/core": ">=1.0.0",
|
|
50
|
-
"@trigger.dev/sdk": ">=4.5.0",
|
|
51
|
-
"ai": ">=6.0.0",
|
|
52
|
-
"zod": ">=3.25.0"
|
|
52
|
+
"@mastra/core": ">=1.0.0 <2",
|
|
53
|
+
"@trigger.dev/sdk": ">=4.5.0 <5",
|
|
54
|
+
"ai": ">=6.0.0 <8",
|
|
55
|
+
"zod": ">=3.25.0 <5"
|
|
53
56
|
},
|
|
54
57
|
"peerDependenciesMeta": {
|
|
55
58
|
"@mastra/core": {
|