@plimsollmark/client 0.14.0 → 0.16.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 -4
- package/dist/client.d.ts +13 -2
- package/dist/client.js +87 -8
- package/dist/errors.d.ts +14 -1
- package/dist/errors.js +88 -1
- package/dist/mastra.d.ts +2 -2
- package/dist/mastra.js +15 -10
- package/dist/record.d.ts +17 -1
- package/dist/record.js +61 -4
- package/dist/sandboxes.d.ts +11 -3
- package/dist/sandboxes.js +57 -10
- 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
|
|
|
@@ -107,8 +116,18 @@ across conversations would show one user another's files. A language the daemon'
|
|
|
107
116
|
cannot run is refused before anything is sent.
|
|
108
117
|
|
|
109
118
|
Closing a sandbox checks the daemon's count of calls against the chain the client saw; a
|
|
110
|
-
mismatch means
|
|
111
|
-
a
|
|
119
|
+
mismatch means the daemon counted a call the client has no answer for (one that ended in an
|
|
120
|
+
abort, a timeout, a dropped connection or a proxy's error), or, if none did, that someone
|
|
121
|
+
else held the session ID. It goes to `onCloseError` (by default a warning) rather than being
|
|
122
|
+
dropped at teardown. A call that may have run but ended in an error comes with its record
|
|
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.
|
|
112
131
|
|
|
113
132
|
The session ID is a capability. It lives in the client's memory and nowhere else: not in
|
|
114
133
|
a log line, not in a record, not in Trigger.dev's `chat.local` (which is serialized into
|
|
@@ -144,6 +163,12 @@ export const codeChat = chat.agent({
|
|
|
144
163
|
The full example, with a test that drives real turns through Trigger.dev's `mockChatAgent`:
|
|
145
164
|
[examples/trigger-chat](https://github.com/plimsollmark/plimsoll/tree/main/examples/trigger-chat/).
|
|
146
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
|
+
|
|
147
172
|
## Mastra
|
|
148
173
|
|
|
149
174
|
```ts
|
|
@@ -160,8 +185,12 @@ export const analyst = new Agent({ id: "analyst", name: "analyst", instructions:
|
|
|
160
185
|
```
|
|
161
186
|
|
|
162
187
|
The sandbox is keyed by Mastra's thread and resource (a thread ID is unique only within
|
|
163
|
-
its user).
|
|
164
|
-
|
|
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.
|
|
165
194
|
|
|
166
195
|
## Tests
|
|
167
196
|
|
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;
|
|
@@ -236,7 +238,9 @@ export declare function projectPayload(req: ProjectRequest, grantProfile: string
|
|
|
236
238
|
/**
|
|
237
239
|
* An open session. Calls are serialized here as they are on the daemon, so the
|
|
238
240
|
* chain this client tracks follows the daemon's; a record that does not continue
|
|
239
|
-
* it means someone else holding the session ID made a call.
|
|
241
|
+
* it means someone else holding the session ID made a call. A call that ends
|
|
242
|
+
* without an answer this client can check (any error not marked notDispatched)
|
|
243
|
+
* may have run, so the session refuses every later call, marked notDispatched.
|
|
240
244
|
*/
|
|
241
245
|
export declare class Session {
|
|
242
246
|
#private;
|
|
@@ -245,10 +249,17 @@ export declare class Session {
|
|
|
245
249
|
/** The tier the daemon measured when the session opened. */
|
|
246
250
|
readonly isolation: string;
|
|
247
251
|
readonly sandbox: string;
|
|
252
|
+
/** The selected software the daemon stated at open. */
|
|
253
|
+
readonly softwareIdentity: string;
|
|
248
254
|
readonly expiresAtMs: number;
|
|
249
255
|
readonly idleTimeoutMs: number;
|
|
250
256
|
/** @internal */
|
|
251
|
-
constructor(client: PlimsollClient, m: WireOpenSessionResponse, rule: WireSoftwareRule | undefined);
|
|
257
|
+
constructor(client: PlimsollClient, m: WireOpenSessionResponse, rule: WireSoftwareRule | undefined, floor?: Exclude<Isolation, "none">);
|
|
258
|
+
/**
|
|
259
|
+
* Why this client sends nothing more on the session, once a call ended without an
|
|
260
|
+
* answer it could check (the call may have run); undefined while it is usable.
|
|
261
|
+
*/
|
|
262
|
+
get stopped(): string | undefined;
|
|
252
263
|
/** The session's end once a response reported it, else undefined. */
|
|
253
264
|
get ended(): {
|
|
254
265
|
reason: SessionEnd;
|
package/dist/client.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// isolation evidence against the caller's floor, and tracks a session's chain of
|
|
6
6
|
// records so a call it did not make is caught.
|
|
7
7
|
import { isIP } from "node:net";
|
|
8
|
-
import { checkRecord, requestDigest, sessionFingerprint, softwareRuleAllows, } from "./record.js";
|
|
8
|
+
import { checkRecord, checkUnanswered, requestDigest, sessionFingerprint, softwareRuleAllows, } from "./record.js";
|
|
9
9
|
import { errorFromWire, PlimsollError, sessionEndFromWire } from "./errors.js";
|
|
10
10
|
/** The wire protocol number this client speaks (protocol.Number in Go). */
|
|
11
11
|
export const PROTOCOL = 2;
|
|
@@ -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) {
|
|
@@ -199,6 +201,10 @@ export class PlimsollClient {
|
|
|
199
201
|
}
|
|
200
202
|
/** @internal One unary Connect call with the JSON codec. */
|
|
201
203
|
async call(method, body, signal) {
|
|
204
|
+
// Aborted before it was sent (a session call waiting its turn, say): nothing left
|
|
205
|
+
// this process, so it is a refusal, not a call that may have run.
|
|
206
|
+
if (signal?.aborted)
|
|
207
|
+
throw new PlimsollError("canceled", `plimsoll: ${method} was canceled before it was sent`, { notDispatched: "request", cause: signal.reason });
|
|
202
208
|
const headers = { "Content-Type": "application/json", "Connect-Protocol-Version": "1" };
|
|
203
209
|
if (this.token)
|
|
204
210
|
headers["Authorization"] = `Bearer ${this.token}`;
|
|
@@ -268,6 +274,7 @@ export class PlimsollClient {
|
|
|
268
274
|
supportsSessions: m.supportsSessions ?? false,
|
|
269
275
|
sessionLifetimeMs: m.sessionLifetimeMs ?? 0,
|
|
270
276
|
sessionIdleTimeoutMs: m.sessionIdleTimeoutMs ?? 0,
|
|
277
|
+
sessionEnvironment: env(m.sessionEnvironment),
|
|
271
278
|
environments: {
|
|
272
279
|
javascript: env(m.javascriptEnvironment),
|
|
273
280
|
project: env(m.projectEnvironment),
|
|
@@ -307,9 +314,11 @@ export class PlimsollClient {
|
|
|
307
314
|
idleTimeoutMs: durationMs(opts.idleTimeoutMs) || undefined,
|
|
308
315
|
softwareRule: rule,
|
|
309
316
|
}, opts.signal);
|
|
310
|
-
const s = new Session(this, m, rule);
|
|
317
|
+
const s = new Session(this, m, rule, opts.minimumIsolation);
|
|
311
318
|
if (s.fingerprint !== sessionFingerprint(m.sessionId ?? "")) {
|
|
312
|
-
|
|
319
|
+
// The session exists on the daemon either way, and nothing else holds its ID.
|
|
320
|
+
await s.close().catch(() => undefined);
|
|
321
|
+
throw new PlimsollError("data_loss", "plimsoll: the daemon's session fingerprint does not match its session ID; the session was closed");
|
|
313
322
|
}
|
|
314
323
|
if (opts.minimumIsolation && !meets(s.isolation, opts.minimumIsolation)) {
|
|
315
324
|
await s.close().catch(() => undefined);
|
|
@@ -372,7 +381,9 @@ function finish(resp, record, map, kind, floor) {
|
|
|
372
381
|
/**
|
|
373
382
|
* An open session. Calls are serialized here as they are on the daemon, so the
|
|
374
383
|
* chain this client tracks follows the daemon's; a record that does not continue
|
|
375
|
-
* it means someone else holding the session ID made a call.
|
|
384
|
+
* it means someone else holding the session ID made a call. A call that ends
|
|
385
|
+
* without an answer this client can check (any error not marked notDispatched)
|
|
386
|
+
* may have run, so the session refuses every later call, marked notDispatched.
|
|
376
387
|
*/
|
|
377
388
|
export class Session {
|
|
378
389
|
/** The SHA-256 of the session ID, as the session's records carry it. */
|
|
@@ -380,27 +391,44 @@ export class Session {
|
|
|
380
391
|
/** The tier the daemon measured when the session opened. */
|
|
381
392
|
isolation;
|
|
382
393
|
sandbox;
|
|
394
|
+
/** The selected software the daemon stated at open. */
|
|
395
|
+
softwareIdentity;
|
|
383
396
|
expiresAtMs;
|
|
384
397
|
idleTimeoutMs;
|
|
385
398
|
// The session ID is a capability: it goes to the daemon and nowhere else.
|
|
386
399
|
#id;
|
|
387
400
|
#client;
|
|
388
401
|
#rule;
|
|
402
|
+
// The floor given at open: every call carries it unless the call asks for more.
|
|
403
|
+
#floor;
|
|
389
404
|
#calls = 0n;
|
|
390
405
|
#last = "";
|
|
391
406
|
#end;
|
|
407
|
+
// Set once a call ended without an answer this client could check: the daemon may
|
|
408
|
+
// have run it and moved its chain on, so every later call would run and then fail
|
|
409
|
+
// the chain check. They are refused here instead, before anything is sent.
|
|
410
|
+
#unknown;
|
|
392
411
|
#queue = Promise.resolve();
|
|
393
412
|
/** @internal */
|
|
394
|
-
constructor(client, m, rule) {
|
|
413
|
+
constructor(client, m, rule, floor) {
|
|
395
414
|
this.#client = client;
|
|
396
415
|
this.#id = m.sessionId ?? "";
|
|
397
416
|
this.#rule = rule;
|
|
417
|
+
this.#floor = floor;
|
|
398
418
|
this.fingerprint = m.session ?? "";
|
|
399
419
|
this.isolation = m.isolation ?? "";
|
|
400
420
|
this.sandbox = m.sandbox ?? "";
|
|
421
|
+
this.softwareIdentity = m.softwareIdentity ?? "";
|
|
401
422
|
this.expiresAtMs = num(m.expiresUnixMs);
|
|
402
423
|
this.idleTimeoutMs = m.idleTimeoutMs ?? 0;
|
|
403
424
|
}
|
|
425
|
+
/**
|
|
426
|
+
* Why this client sends nothing more on the session, once a call ended without an
|
|
427
|
+
* answer it could check (the call may have run); undefined while it is usable.
|
|
428
|
+
*/
|
|
429
|
+
get stopped() {
|
|
430
|
+
return this.#unknown;
|
|
431
|
+
}
|
|
404
432
|
/** The session's end once a response reported it, else undefined. */
|
|
405
433
|
get ended() {
|
|
406
434
|
return this.#end;
|
|
@@ -410,11 +438,13 @@ export class Session {
|
|
|
410
438
|
return { calls: this.#calls, lastRecordSha256: this.#last };
|
|
411
439
|
}
|
|
412
440
|
async runJavaScript(code, opts = {}) {
|
|
441
|
+
opts = this.#withFloor(opts);
|
|
413
442
|
const run = await this.#call({ javascript: { code, grantProfile: this.#client.jsGrant || undefined } }, opts);
|
|
414
443
|
return finish(run.run, run.record, javascriptResult, "javascript", opts.minimumIsolation);
|
|
415
444
|
}
|
|
416
445
|
/** Runs a project in the session; its files persist for later calls. */
|
|
417
446
|
async runProject(req, opts = {}) {
|
|
447
|
+
opts = this.#withFloor(opts);
|
|
418
448
|
const run = await this.#call(projectPayload(req, this.#client.projectGrant), opts);
|
|
419
449
|
return finish(run.run, run.record, projectResult, "project", opts.minimumIsolation);
|
|
420
450
|
}
|
|
@@ -428,10 +458,19 @@ export class Session {
|
|
|
428
458
|
if (req.language !== "javascript" && req.language !== "python") {
|
|
429
459
|
throw new PlimsollError("invalid_argument", `plimsoll: unknown cell language ${JSON.stringify(req.language)}`, { notDispatched: "request" });
|
|
430
460
|
}
|
|
461
|
+
opts = this.#withFloor(opts);
|
|
431
462
|
const files = (req.files ?? []).map((f) => ({ path: f.path, content: f.content }));
|
|
432
463
|
const run = await this.#call({ cell: { language: req.language, code: req.code, files } }, opts);
|
|
433
464
|
return finish(run.run, run.record, cellResult, "cell", opts.minimumIsolation);
|
|
434
465
|
}
|
|
466
|
+
// The call's options with the session's floor, unless the call asks for more.
|
|
467
|
+
#withFloor(opts) {
|
|
468
|
+
const a = this.#floor;
|
|
469
|
+
const b = opts.minimumIsolation;
|
|
470
|
+
if (!a || (b && TIERS.indexOf(b) >= TIERS.indexOf(a)))
|
|
471
|
+
return opts;
|
|
472
|
+
return { ...opts, minimumIsolation: a };
|
|
473
|
+
}
|
|
435
474
|
#serial(f) {
|
|
436
475
|
const next = this.#queue.then(f, f);
|
|
437
476
|
this.#queue = next.catch(() => undefined);
|
|
@@ -440,7 +479,47 @@ export class Session {
|
|
|
440
479
|
#call(payload, opts) {
|
|
441
480
|
const rule = mergeRules(this.#rule, validateRule(opts.software));
|
|
442
481
|
return this.#serial(async () => {
|
|
482
|
+
if (this.#unknown !== undefined) {
|
|
483
|
+
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" });
|
|
484
|
+
}
|
|
443
485
|
const env = this.#client.envelope(opts, rule);
|
|
486
|
+
const digest = requestDigest({ protocol: env.protocol, minimumIsolation: env.minimumIsolation ?? "", timeoutMs: env.timeoutMs ?? 0, softwareRule: rule, payload: digestPayload(payload) });
|
|
487
|
+
try {
|
|
488
|
+
return await this.#exchange(payload, opts, rule, env, digest);
|
|
489
|
+
}
|
|
490
|
+
catch (e) {
|
|
491
|
+
if (e instanceof PlimsollError && e.notDispatched)
|
|
492
|
+
throw e;
|
|
493
|
+
if (e instanceof PlimsollError && e.unanswered) {
|
|
494
|
+
// The call may have run, and the daemon chained its record: check it and keep
|
|
495
|
+
// it in the chain, so the session goes on and the call is not hidden.
|
|
496
|
+
let checked = checkUnanswered(digest, env.minimumIsolation ?? "", rule, e.unanswered, this.fingerprint, this.#calls, this.#last);
|
|
497
|
+
if ("record" in checked) {
|
|
498
|
+
// With no response to compare it with, the record's evidence must be what the
|
|
499
|
+
// session stated at open.
|
|
500
|
+
const r = checked.record;
|
|
501
|
+
if (r.provider !== this.sandbox || r.isolation !== this.isolation || r.softwareIdentity !== this.softwareIdentity) {
|
|
502
|
+
checked = {
|
|
503
|
+
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}"`,
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
if ("problem" in checked) {
|
|
508
|
+
this.#unknown = checked.problem;
|
|
509
|
+
throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { cause: e });
|
|
510
|
+
}
|
|
511
|
+
this.#calls = checked.record.sequence;
|
|
512
|
+
this.#last = checked.record.sha256;
|
|
513
|
+
e.record = checked.record; // the checked record, as Go's UnansweredCallError carries it
|
|
514
|
+
throw e;
|
|
515
|
+
}
|
|
516
|
+
this.#unknown = e instanceof Error ? e.message : String(e);
|
|
517
|
+
throw e;
|
|
518
|
+
}
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
async #exchange(payload, opts, rule, env, digest) {
|
|
522
|
+
{
|
|
444
523
|
let m;
|
|
445
524
|
try {
|
|
446
525
|
m = await this.#client.call("SessionRun", { ...env, sessionId: this.#id, ...payload }, opts.signal);
|
|
@@ -456,7 +535,7 @@ export class Session {
|
|
|
456
535
|
const end = sessionEndFromWire(m.ended);
|
|
457
536
|
if (end !== "open")
|
|
458
537
|
this.#end = { reason: end, detail: m.endDetail ?? "" };
|
|
459
|
-
const checked = checkRecord(
|
|
538
|
+
const checked = checkRecord(digest, env.protocol, rule, run);
|
|
460
539
|
if ("problem" in checked)
|
|
461
540
|
throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { result: run });
|
|
462
541
|
const r = checked.record;
|
|
@@ -466,7 +545,7 @@ export class Session {
|
|
|
466
545
|
this.#calls = r.sequence;
|
|
467
546
|
this.#last = r.sha256;
|
|
468
547
|
return { run, record: r };
|
|
469
|
-
}
|
|
548
|
+
}
|
|
470
549
|
}
|
|
471
550
|
/**
|
|
472
551
|
* Ends the session (or collects one that ended by itself) and checks the
|
package/dist/errors.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { RunRecord } from "./record.ts";
|
|
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";
|
|
4
5
|
/** Why a session ended (plimsoll.v1.SessionEnd), "open" while it has not. */
|
|
@@ -27,6 +28,17 @@ export declare class PlimsollError extends Error {
|
|
|
27
28
|
* have executed, and this is what came back.
|
|
28
29
|
*/
|
|
29
30
|
readonly result: unknown;
|
|
31
|
+
/**
|
|
32
|
+
* The record the daemon sends with a session call that may have run but ended in
|
|
33
|
+
* an error (a version 3 record, as it came off the wire). The Session checks it
|
|
34
|
+
* and keeps it in its chain, so the session goes on; the call's outcome is unknown.
|
|
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;
|
|
30
42
|
constructor(code: Code, message: string, opts?: {
|
|
31
43
|
notDispatched?: Refusal;
|
|
32
44
|
sessionEnded?: {
|
|
@@ -34,6 +46,7 @@ export declare class PlimsollError extends Error {
|
|
|
34
46
|
detail: string;
|
|
35
47
|
};
|
|
36
48
|
result?: unknown;
|
|
49
|
+
unanswered?: WireRecord;
|
|
37
50
|
cause?: unknown;
|
|
38
51
|
});
|
|
39
52
|
}
|
package/dist/errors.js
CHANGED
|
@@ -17,6 +17,17 @@ export class PlimsollError extends Error {
|
|
|
17
17
|
* have executed, and this is what came back.
|
|
18
18
|
*/
|
|
19
19
|
result;
|
|
20
|
+
/**
|
|
21
|
+
* The record the daemon sends with a session call that may have run but ended in
|
|
22
|
+
* an error (a version 3 record, as it came off the wire). The Session checks it
|
|
23
|
+
* and keeps it in its chain, so the session goes on; the call's outcome is unknown.
|
|
24
|
+
*/
|
|
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;
|
|
20
31
|
constructor(code, message, opts = {}) {
|
|
21
32
|
super(message, opts.cause === undefined ? undefined : { cause: opts.cause });
|
|
22
33
|
this.name = "PlimsollError";
|
|
@@ -24,6 +35,7 @@ export class PlimsollError extends Error {
|
|
|
24
35
|
this.notDispatched = opts.notDispatched;
|
|
25
36
|
this.sessionEnded = opts.sessionEnded;
|
|
26
37
|
this.result = opts.result;
|
|
38
|
+
this.unanswered = opts.unanswered;
|
|
27
39
|
}
|
|
28
40
|
}
|
|
29
41
|
const REFUSALS = ["unknown", "request", "permission", "protocol", "unsupported", "isolation", "capacity", "environment"];
|
|
@@ -88,11 +100,83 @@ function decodeDetail(b) {
|
|
|
88
100
|
}
|
|
89
101
|
return { reason, detail };
|
|
90
102
|
}
|
|
103
|
+
// Reads one varint at b[i] as a bigint (an int64 or uint64 field); returns [value,
|
|
104
|
+
// next index].
|
|
105
|
+
function bigVarint(b, i) {
|
|
106
|
+
let v = 0n;
|
|
107
|
+
for (let shift = 0n; i < b.length && shift < 70n; shift += 7n) {
|
|
108
|
+
const c = b[i++];
|
|
109
|
+
v |= BigInt(c & 0x7f) << shift;
|
|
110
|
+
if ((c & 0x80) === 0)
|
|
111
|
+
return [v, i];
|
|
112
|
+
}
|
|
113
|
+
throw new Error("bad varint");
|
|
114
|
+
}
|
|
115
|
+
const RECORD_STRINGS = {
|
|
116
|
+
2: "requestSha256", 3: "resultSha256", 4: "provider", 5: "isolation", 6: "environment", 7: "policy",
|
|
117
|
+
10: "session", 12: "previousSha256", 13: "recordSha256", 14: "softwareIdentity", 15: "softwareRuleId", 16: "unanswered",
|
|
118
|
+
};
|
|
119
|
+
// Decodes an UnansweredCall detail (field 1, a RunRecord) by hand, into the record's
|
|
120
|
+
// proto3 JSON form, so the record checks exactly as one read off a JSON answer.
|
|
121
|
+
function decodeUnanswered(b) {
|
|
122
|
+
let rec;
|
|
123
|
+
for (let i = 0; i < b.length;) {
|
|
124
|
+
const [tag, j] = varint(b, i);
|
|
125
|
+
const [n, k] = varint(b, j);
|
|
126
|
+
if ((tag & 7) !== 2 || k + n > b.length)
|
|
127
|
+
throw new Error("bad detail");
|
|
128
|
+
if (tag >>> 3 === 1)
|
|
129
|
+
rec = decodeRecord(b.subarray(k, k + n));
|
|
130
|
+
i = k + n;
|
|
131
|
+
}
|
|
132
|
+
return rec;
|
|
133
|
+
}
|
|
134
|
+
function decodeRecord(b) {
|
|
135
|
+
const m = {};
|
|
136
|
+
for (let i = 0; i < b.length;) {
|
|
137
|
+
const [tag, j] = varint(b, i);
|
|
138
|
+
const field = Math.floor(tag / 8);
|
|
139
|
+
const wire = tag & 7;
|
|
140
|
+
i = j;
|
|
141
|
+
if (wire === 0) {
|
|
142
|
+
const [v, k] = bigVarint(b, i);
|
|
143
|
+
i = k;
|
|
144
|
+
if (field === 1)
|
|
145
|
+
m.version = Number(v);
|
|
146
|
+
else if (field === 8)
|
|
147
|
+
m.startedUnixMs = BigInt.asIntN(64, v).toString();
|
|
148
|
+
else if (field === 9)
|
|
149
|
+
m.endedUnixMs = BigInt.asIntN(64, v).toString();
|
|
150
|
+
else if (field === 11)
|
|
151
|
+
m.sequence = v.toString();
|
|
152
|
+
}
|
|
153
|
+
else if (wire === 2) {
|
|
154
|
+
const [n, k] = varint(b, i);
|
|
155
|
+
if (k + n > b.length)
|
|
156
|
+
throw new Error("bad length");
|
|
157
|
+
const name = RECORD_STRINGS[field];
|
|
158
|
+
if (name)
|
|
159
|
+
m[name] = new TextDecoder("utf-8", { fatal: true }).decode(b.subarray(k, k + n));
|
|
160
|
+
i = k + n;
|
|
161
|
+
}
|
|
162
|
+
else if (wire === 1) {
|
|
163
|
+
i += 8;
|
|
164
|
+
}
|
|
165
|
+
else if (wire === 5) {
|
|
166
|
+
i += 4;
|
|
167
|
+
}
|
|
168
|
+
else {
|
|
169
|
+
throw new Error("unexpected wire type");
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return m;
|
|
173
|
+
}
|
|
91
174
|
/** The error a Connect error body describes, with its plimsoll details restored. */
|
|
92
175
|
export function errorFromWire(httpStatus, body) {
|
|
93
176
|
const code = body?.code ?? httpStatusCode(httpStatus);
|
|
94
177
|
let notDispatched;
|
|
95
178
|
let sessionEnded;
|
|
179
|
+
let unanswered;
|
|
96
180
|
for (const d of body?.details ?? []) {
|
|
97
181
|
try {
|
|
98
182
|
const bytes = Buffer.from(d.value ?? "", "base64");
|
|
@@ -103,12 +187,15 @@ export function errorFromWire(httpStatus, body) {
|
|
|
103
187
|
const m = decodeDetail(bytes);
|
|
104
188
|
sessionEnded = { reason: sessionEndFromWire(m.reason), detail: m.detail };
|
|
105
189
|
}
|
|
190
|
+
else if (d.type === "plimsoll.v1.UnansweredCall") {
|
|
191
|
+
unanswered = decodeUnanswered(bytes);
|
|
192
|
+
}
|
|
106
193
|
}
|
|
107
194
|
catch {
|
|
108
195
|
// An undecodable detail states nothing; in particular not that nothing ran.
|
|
109
196
|
}
|
|
110
197
|
}
|
|
111
|
-
return new PlimsollError(code, body?.message ?? `HTTP ${httpStatus}`, { notDispatched, sessionEnded });
|
|
198
|
+
return new PlimsollError(code, body?.message ?? `HTTP ${httpStatus}`, { notDispatched, sessionEnded, unanswered: notDispatched ? undefined : unanswered });
|
|
112
199
|
}
|
|
113
200
|
// Connect's mapping for a response without a Connect error body.
|
|
114
201
|
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,11 @@
|
|
|
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.
|
|
12
|
+
const threadKey = (threadId, resourceId) => threadId && resourceId ? `${resourceId}\u0000${threadId}` : undefined;
|
|
10
13
|
export function plimsollExecuteCode(opts) {
|
|
11
14
|
const sandboxes = new CodeSandboxes(opts);
|
|
12
15
|
const executeCode = createTool({
|
|
@@ -14,17 +17,19 @@ export function plimsollExecuteCode(opts) {
|
|
|
14
17
|
description: executeCodeDescription(sandboxes.languages),
|
|
15
18
|
inputSchema: executeCodeInput(sandboxes.languages),
|
|
16
19
|
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
|
-
},
|
|
20
|
+
// The user's thread scopes the sandbox. A call outside a thread, or without a
|
|
21
|
+
// resource, runs fresh: one sandbox shared across conversations would show one user
|
|
22
|
+
// another's files.
|
|
23
|
+
execute: async (input, ctx) => sandboxes.run(threadKey(ctx?.agent?.threadId, ctx?.agent?.resourceId), input, ctx?.abortSignal),
|
|
23
24
|
});
|
|
24
25
|
return {
|
|
25
26
|
executeCode,
|
|
26
|
-
/** Closes a thread's sandbox, e.g. when the conversation ends. */
|
|
27
|
-
dispose: (threadId, resourceId) =>
|
|
27
|
+
/** Closes a user's thread's sandbox, e.g. when the conversation ends. */
|
|
28
|
+
dispose: async (threadId, resourceId) => {
|
|
29
|
+
const key = threadKey(threadId, resourceId);
|
|
30
|
+
if (key !== undefined)
|
|
31
|
+
await sandboxes.dispose(key);
|
|
32
|
+
},
|
|
28
33
|
sandboxes,
|
|
29
34
|
};
|
|
30
35
|
}
|
package/dist/record.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { WireRecord, WireRunResponse, WireSoftwareRule } from "./wire.ts";
|
|
2
|
-
/** The record encoding version this client computes and checks. */
|
|
2
|
+
/** The record encoding version of an answered call, which this client computes and checks. */
|
|
3
3
|
export declare const RECORD_VERSION = 2;
|
|
4
|
+
/** The record encoding version of a session call that may have run but ended in an error. */
|
|
5
|
+
export declare const UNANSWERED_RECORD_VERSION = 3;
|
|
4
6
|
/** The payload of a request as the digest sees it. */
|
|
5
7
|
export type DigestPayload = {
|
|
6
8
|
kind: "javascript";
|
|
@@ -53,6 +55,8 @@ export type RunRecord = {
|
|
|
53
55
|
session: string;
|
|
54
56
|
sequence: bigint;
|
|
55
57
|
previousSha256: string;
|
|
58
|
+
/** On a version 3 record, the Connect code a session call that may have run ended with. */
|
|
59
|
+
unanswered: string;
|
|
56
60
|
sha256: string;
|
|
57
61
|
};
|
|
58
62
|
export declare function recordFromWire(m: WireRecord): RunRecord;
|
|
@@ -66,6 +70,18 @@ export declare function sessionFingerprint(sessionId: string): string;
|
|
|
66
70
|
*/
|
|
67
71
|
export declare function softwareRuleId(rule: WireSoftwareRule | undefined): string;
|
|
68
72
|
export declare function softwareRuleAllows(rule: WireSoftwareRule | undefined, identity: string): boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Checks the record the daemon sends with an unanswered session call's error
|
|
75
|
+
* (record.CheckUnanswered): version 3, no result digest, a Connect code, the digest of
|
|
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.
|
|
78
|
+
* Returns the reason it does not check, or the record.
|
|
79
|
+
*/
|
|
80
|
+
export declare function checkUnanswered(reqDigest: string, floor: string, rule: WireSoftwareRule | undefined, m: WireRecord, fingerprint: string, prevSeq: bigint, prev: string): {
|
|
81
|
+
record: RunRecord;
|
|
82
|
+
} | {
|
|
83
|
+
problem: string;
|
|
84
|
+
};
|
|
69
85
|
/**
|
|
70
86
|
* Checks everything a record states that the caller can recompute: the version,
|
|
71
87
|
* both digests, the evidence the response repeats, the software rule and the
|
package/dist/record.js
CHANGED
|
@@ -2,8 +2,16 @@
|
|
|
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
|
-
|
|
5
|
+
import { PlimsollError } from "./errors.js";
|
|
6
|
+
/** The record encoding version of an answered call, which this client computes and checks. */
|
|
6
7
|
export const RECORD_VERSION = 2;
|
|
8
|
+
/** The record encoding version of a session call that may have run but ended in an error. */
|
|
9
|
+
export const UNANSWERED_RECORD_VERSION = 3;
|
|
10
|
+
const UNANSWERED_CODES = new Set([
|
|
11
|
+
"canceled", "unknown", "invalid_argument", "deadline_exceeded", "not_found", "already_exists", "permission_denied",
|
|
12
|
+
"resource_exhausted", "failed_precondition", "aborted", "out_of_range", "unimplemented", "internal", "unavailable",
|
|
13
|
+
"data_loss", "unauthenticated",
|
|
14
|
+
]);
|
|
7
15
|
class Encoder {
|
|
8
16
|
h = createHash("sha256");
|
|
9
17
|
constructor(domain) {
|
|
@@ -20,6 +28,10 @@ class Encoder {
|
|
|
20
28
|
this.value(v);
|
|
21
29
|
}
|
|
22
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)`);
|
|
23
35
|
this.bytes(name, Buffer.from(v, "utf8"));
|
|
24
36
|
}
|
|
25
37
|
// Integers are decimal ASCII; callers pass bigint for 64-bit values so no
|
|
@@ -155,6 +167,16 @@ export function resultDigest(resp) {
|
|
|
155
167
|
}
|
|
156
168
|
return e.sum();
|
|
157
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
|
+
}
|
|
158
180
|
export function recordFromWire(m) {
|
|
159
181
|
return {
|
|
160
182
|
version: m.version ?? 0,
|
|
@@ -166,11 +188,12 @@ export function recordFromWire(m) {
|
|
|
166
188
|
policy: m.policy ?? "",
|
|
167
189
|
softwareIdentity: m.softwareIdentity ?? "",
|
|
168
190
|
softwareRuleId: m.softwareRuleId ?? "",
|
|
169
|
-
startedUnixMs:
|
|
170
|
-
endedUnixMs:
|
|
191
|
+
startedUnixMs: big(m.startedUnixMs, "startedUnixMs"),
|
|
192
|
+
endedUnixMs: big(m.endedUnixMs, "endedUnixMs"),
|
|
171
193
|
session: m.session ?? "",
|
|
172
|
-
sequence:
|
|
194
|
+
sequence: big(m.sequence, "sequence"),
|
|
173
195
|
previousSha256: m.previousSha256 ?? "",
|
|
196
|
+
unanswered: m.unanswered ?? "",
|
|
174
197
|
sha256: m.recordSha256 ?? "",
|
|
175
198
|
};
|
|
176
199
|
}
|
|
@@ -179,6 +202,8 @@ export function recordDigest(r) {
|
|
|
179
202
|
const e = new Encoder(`plimsoll.run-record.v${r.version}`);
|
|
180
203
|
e.str("request_sha256", r.requestSha256);
|
|
181
204
|
e.str("result_sha256", r.resultSha256);
|
|
205
|
+
if (r.version >= 3)
|
|
206
|
+
e.str("unanswered", r.unanswered);
|
|
182
207
|
e.str("provider", r.provider);
|
|
183
208
|
e.str("isolation", r.isolation);
|
|
184
209
|
e.str("environment", r.environment);
|
|
@@ -216,6 +241,36 @@ export function softwareRuleAllows(rule, identity) {
|
|
|
216
241
|
return true;
|
|
217
242
|
return identity !== "" && rule.identities.includes(identity);
|
|
218
243
|
}
|
|
244
|
+
// The tiers, weakest first, as client.ts's TIERS (which imports this module).
|
|
245
|
+
const TIER_ORDER = ["none", "process", "container", "kernel", "vm"];
|
|
246
|
+
/**
|
|
247
|
+
* Checks the record the daemon sends with an unanswered session call's error
|
|
248
|
+
* (record.CheckUnanswered): version 3, no result digest, a Connect code, the digest of
|
|
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.
|
|
251
|
+
* Returns the reason it does not check, or the record.
|
|
252
|
+
*/
|
|
253
|
+
export function checkUnanswered(reqDigest, floor, rule, m, fingerprint, prevSeq, prev) {
|
|
254
|
+
const r = recordFromWire(m);
|
|
255
|
+
if (r.version !== UNANSWERED_RECORD_VERSION)
|
|
256
|
+
return { problem: `an unanswered call's record is version ${r.version}` };
|
|
257
|
+
if (r.resultSha256 !== "" || !UNANSWERED_CODES.has(r.unanswered))
|
|
258
|
+
return { problem: "an unanswered call's record states a result or no error code" };
|
|
259
|
+
if (r.requestSha256 !== reqDigest)
|
|
260
|
+
return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
|
|
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
|
+
}
|
|
264
|
+
if (r.sha256 !== recordDigest(r))
|
|
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
|
+
}
|
|
269
|
+
if (r.session !== fingerprint || r.sequence !== prevSeq + 1n || r.previousSha256 !== prev) {
|
|
270
|
+
return { problem: `the session's chain is broken: call ${r.sequence} after "${r.previousSha256}", this client's last was call ${prevSeq}, "${prev}"` };
|
|
271
|
+
}
|
|
272
|
+
return { record: r };
|
|
273
|
+
}
|
|
219
274
|
/**
|
|
220
275
|
* Checks everything a record states that the caller can recompute: the version,
|
|
221
276
|
* both digests, the evidence the response repeats, the software rule and the
|
|
@@ -232,6 +287,8 @@ export function checkRecord(reqDigest, protocol, rule, resp) {
|
|
|
232
287
|
return { problem: `protocol ${protocol} requires record version ${RECORD_VERSION}` };
|
|
233
288
|
if (r.version === 1 && (r.softwareIdentity !== "" || r.softwareRuleId !== ""))
|
|
234
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` };
|
|
235
292
|
if (r.requestSha256 !== reqDigest)
|
|
236
293
|
return { problem: `request digest ${r.requestSha256}, the request sent digests to ${reqDigest}` };
|
|
237
294
|
if (r.resultSha256 !== result)
|
package/dist/sandboxes.d.ts
CHANGED
|
@@ -35,8 +35,10 @@ export type CodeSandboxesOptions = {
|
|
|
35
35
|
maxOutputChars?: number;
|
|
36
36
|
/**
|
|
37
37
|
* Called when closing a sandbox fails. A "data_loss" error here means the
|
|
38
|
-
* daemon counted calls this client
|
|
39
|
-
*
|
|
38
|
+
* daemon counted calls this client has no answer for: a call that ended
|
|
39
|
+
* without one (an abort, a timeout, a dropped connection, a proxy's error),
|
|
40
|
+
* or, if none did, someone else holding the session ID. Default: console.warn.
|
|
41
|
+
* The error never contains the session ID.
|
|
40
42
|
*/
|
|
41
43
|
onCloseError?: (key: string, err: unknown) => void;
|
|
42
44
|
};
|
|
@@ -87,7 +89,13 @@ export type ExecuteCodeOutput = {
|
|
|
87
89
|
};
|
|
88
90
|
/** @internal A fresh call on a daemon without projects: the code as a snippet, its last value printed. Node and QuickJS alike. */
|
|
89
91
|
export declare function snippetRunner(code: string): string;
|
|
90
|
-
/**
|
|
92
|
+
/**
|
|
93
|
+
* @internal A fresh run prints its last expression as a cell does, through these
|
|
94
|
+
* runners, and takes what a cell takes: top-level await, and imports from the work
|
|
95
|
+
* directory (Python's own imports first, in isolated mode, as the session kernel
|
|
96
|
+
* does; Node's require resolving from the work directory, and the image's baked
|
|
97
|
+
* packages above it).
|
|
98
|
+
*/
|
|
91
99
|
export declare const RUNNERS: Record<Language, {
|
|
92
100
|
path: string;
|
|
93
101
|
file: string;
|
package/dist/sandboxes.js
CHANGED
|
@@ -39,21 +39,35 @@ export function snippetRunner(code) {
|
|
|
39
39
|
"",
|
|
40
40
|
].join("\n");
|
|
41
41
|
}
|
|
42
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* @internal A fresh run prints its last expression as a cell does, through these
|
|
44
|
+
* runners, and takes what a cell takes: top-level await, and imports from the work
|
|
45
|
+
* directory (Python's own imports first, in isolated mode, as the session kernel
|
|
46
|
+
* does; Node's require resolving from the work directory, and the image's baked
|
|
47
|
+
* packages above it).
|
|
48
|
+
*/
|
|
43
49
|
export const RUNNERS = {
|
|
44
50
|
python: {
|
|
45
51
|
path: ".plimsoll/run.py",
|
|
46
52
|
file: ".plimsoll/cell.py",
|
|
47
|
-
step: "python3 .plimsoll/run.py",
|
|
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.
|
|
48
56
|
source: [
|
|
49
|
-
"import ast",
|
|
57
|
+
"import ast, asyncio, inspect, linecache, sys",
|
|
58
|
+
"sys.path.insert(0, '')",
|
|
50
59
|
"src = open('.plimsoll/cell.py').read()",
|
|
60
|
+
"linecache.cache['cell'] = (len(src), None, src.splitlines(True), 'cell')",
|
|
51
61
|
"tree = ast.parse(src, 'cell', 'exec')",
|
|
52
62
|
"last = ast.Expression(tree.body.pop().value) if tree.body and isinstance(tree.body[-1], ast.Expr) else None",
|
|
53
|
-
"ns = {'__name__': '__main__'}",
|
|
54
|
-
"
|
|
63
|
+
"ns = {'__name__': '__main__', '__builtins__': __builtins__}",
|
|
64
|
+
"flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT",
|
|
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))",
|
|
55
69
|
"if last is not None:",
|
|
56
|
-
" value = eval(compile(last, 'cell', 'eval'), ns)",
|
|
70
|
+
" value = settle(eval(compile(last, 'cell', 'eval', flags=flags), ns))",
|
|
57
71
|
" if value is not None:",
|
|
58
72
|
" print(repr(value))",
|
|
59
73
|
"",
|
|
@@ -62,12 +76,29 @@ export const RUNNERS = {
|
|
|
62
76
|
javascript: {
|
|
63
77
|
path: ".plimsoll/run.cjs",
|
|
64
78
|
file: ".plimsoll/cell.js",
|
|
65
|
-
step: "node .plimsoll/run.cjs",
|
|
79
|
+
step: "node --expose-internals .plimsoll/run.cjs",
|
|
66
80
|
source: [
|
|
67
81
|
"const fs = require('node:fs'), util = require('node:util'), vm = require('node:vm');",
|
|
68
|
-
|
|
82
|
+
// The names a cell in the session's `node -e` interpreter sees as globals.
|
|
83
|
+
"globalThis.require = require('node:module').createRequire(process.cwd() + '/');",
|
|
84
|
+
"globalThis.module = { exports: {} }; globalThis.exports = globalThis.module.exports;",
|
|
85
|
+
"globalThis.__dirname = '.'; globalThis.__filename = '[eval]';",
|
|
86
|
+
"let tla = null;",
|
|
87
|
+
"try { tla = require('internal/repl/await').processTopLevelAwait; } catch {}",
|
|
88
|
+
"const src = fs.readFileSync('.plimsoll/cell.js', 'utf8');",
|
|
89
|
+
"let wrapped = null;",
|
|
90
|
+
"if (tla) { try { wrapped = tla(src); } catch {} }",
|
|
91
|
+
"(async () => {",
|
|
92
|
+
" let v;",
|
|
93
|
+
" if (wrapped) {",
|
|
94
|
+
" const out = await vm.runInThisContext(wrapped, { filename: 'cell.js' });",
|
|
95
|
+
" v = out === undefined ? undefined : out.value;",
|
|
96
|
+
" } else {",
|
|
97
|
+
" v = vm.runInThisContext(src, { filename: 'cell.js' });",
|
|
98
|
+
" if (v instanceof Promise) v = await v;",
|
|
99
|
+
" }",
|
|
69
100
|
" if (v !== undefined) console.log(util.inspect(v, { depth: 4 }));",
|
|
70
|
-
"});",
|
|
101
|
+
"})().catch((e) => { console.error(e); process.exitCode = 1; });",
|
|
71
102
|
"",
|
|
72
103
|
].join("\n"),
|
|
73
104
|
},
|
|
@@ -115,6 +146,14 @@ export class CodeSandboxes {
|
|
|
115
146
|
}
|
|
116
147
|
/** Runs one call of the tool under the key. */
|
|
117
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
|
+
}
|
|
118
157
|
const language = input.language ?? this.languages[0];
|
|
119
158
|
if (!this.languages.includes(language)) {
|
|
120
159
|
throw new PlimsollError("invalid_argument", `plimsoll: this tool runs ${this.languages.join(" or ")}, not ${language}`, { notDispatched: "request" });
|
|
@@ -143,8 +182,10 @@ export class CodeSandboxes {
|
|
|
143
182
|
let session;
|
|
144
183
|
try {
|
|
145
184
|
session = await entry.session;
|
|
146
|
-
const first = !entry.answered;
|
|
147
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;
|
|
148
189
|
entry.answered = true;
|
|
149
190
|
// What the call defined, and the files it wrote, can be there for the next call
|
|
150
191
|
// only if its interpreter, and the sandbox, outlived it; the next call's fresh
|
|
@@ -169,6 +210,12 @@ export class CodeSandboxes {
|
|
|
169
210
|
this.#drop(key, session);
|
|
170
211
|
continue;
|
|
171
212
|
}
|
|
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))
|
|
218
|
+
this.#drop(key, session);
|
|
172
219
|
throw e;
|
|
173
220
|
}
|
|
174
221
|
finally {
|
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
|
@@ -51,6 +51,7 @@ export type WireRecord = {
|
|
|
51
51
|
session?: string;
|
|
52
52
|
sequence?: string | number;
|
|
53
53
|
previousSha256?: string;
|
|
54
|
+
unanswered?: string;
|
|
54
55
|
softwareIdentity?: string;
|
|
55
56
|
softwareRuleId?: string;
|
|
56
57
|
recordSha256?: string;
|
|
@@ -152,6 +153,7 @@ export type WireDescribeResponse = {
|
|
|
152
153
|
supportsSessions?: boolean;
|
|
153
154
|
sessionLifetimeMs?: number;
|
|
154
155
|
sessionIdleTimeoutMs?: number;
|
|
156
|
+
sessionEnvironment?: WirePayloadEnvironment;
|
|
155
157
|
};
|
|
156
158
|
export type WireOpenSessionRequest = {
|
|
157
159
|
protocol: number;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plimsollmark/client",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.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": {
|