@plimsollmark/client 0.27.1 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -3
- package/dist/ai-sdk.d.ts +20 -1
- package/dist/ai-sdk.js +28 -1
- package/dist/checkpoint.d.ts +41 -0
- package/dist/checkpoint.js +131 -0
- package/dist/client.d.ts +114 -15
- package/dist/client.js +335 -40
- package/dist/errors.d.ts +27 -4
- package/dist/errors.js +60 -10
- package/dist/granted.gen.d.ts +32 -0
- package/dist/granted.gen.js +33 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/mastra.d.ts +38 -1
- package/dist/mastra.js +23 -1
- package/dist/record.d.ts +36 -2
- package/dist/record.js +130 -41
- package/dist/sandboxes.d.ts +59 -1
- package/dist/sandboxes.js +179 -0
- package/dist/tables.gen.d.ts +76 -0
- package/dist/tables.gen.js +85 -2
- package/dist/tool.d.ts +13 -4
- package/dist/tool.js +57 -9
- package/dist/trigger.js +4 -1
- package/dist/wire.d.ts +48 -0
- package/dist/wire.js +25 -1
- package/package.json +2 -2
package/dist/errors.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// anything ran. A refusal raised before dispatch carries the NotDispatched detail
|
|
3
3
|
// and comes back with notDispatched set; anything else may have followed
|
|
4
4
|
// execution and is never a safe automatic retry (docs/run-results.md).
|
|
5
|
-
import { REFUSAL_NAMES, SESSION_END_NAMES } from "./tables.gen.js";
|
|
5
|
+
import { CHECKPOINT_MISMATCH_TEXT, REFUSAL_NAMES, REQUEST_ID_HEADER, SESSION_END_NAMES } from "./tables.gen.js";
|
|
6
6
|
import { wireBytes } from "./wire.js";
|
|
7
7
|
export class PlimsollError extends Error {
|
|
8
8
|
code;
|
|
@@ -50,11 +50,43 @@ export class PlimsollError extends Error {
|
|
|
50
50
|
this.answerNotBound = opts.answerNotBound ?? false;
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
|
-
/**
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
53
|
+
/**
|
|
54
|
+
* A session call, close or attach the daemon refused because another worker attached the
|
|
55
|
+
* session (or its ownership generation is spent): nothing ran, and the session goes on for
|
|
56
|
+
* its new owner. After it on a call or a close, the Session sends nothing more (Go:
|
|
57
|
+
* client.ErrStaleOwner).
|
|
58
|
+
*/
|
|
59
|
+
export class StaleOwnerError extends PlimsollError {
|
|
60
|
+
constructor(message, opts = {}) {
|
|
61
|
+
super("failed_precondition", message, opts);
|
|
62
|
+
this.name = "StaleOwnerError";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* An attach the daemon refused because the checkpoint is not the session's head: a call ran
|
|
67
|
+
* after the checkpoint was saved, its answer perhaps lost. Nothing ran, and ownership did
|
|
68
|
+
* not move (Go: client.ErrCheckpointMismatch).
|
|
69
|
+
*/
|
|
70
|
+
export class CheckpointMismatchError extends PlimsollError {
|
|
71
|
+
constructor(message, opts = {}) {
|
|
72
|
+
super("failed_precondition", message, opts);
|
|
73
|
+
this.name = "CheckpointMismatchError";
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The first call of a session taken over across an explained gap repeats the lost call:
|
|
78
|
+
* that call was already sent once and its answer was lost, so this is a retry of it.
|
|
79
|
+
* Refused before anything was sent (notDispatched "request"), and never a retry signal.
|
|
80
|
+
* Only the first call is checked (Go: client.ErrCallAlreadySent, in the same words).
|
|
81
|
+
* The lost call's record says whether the daemon answered it (session.lostCall).
|
|
82
|
+
*/
|
|
83
|
+
export class CallAlreadySentError extends PlimsollError {
|
|
84
|
+
constructor(message) {
|
|
85
|
+
super("failed_precondition", message, { notDispatched: "request" });
|
|
86
|
+
this.name = "CallAlreadySentError";
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const NOT_BOUND = `the answer does not carry this request's ${REQUEST_ID_HEADER} back (a daemon older than protocol 3, or an intermediary ` +
|
|
58
90
|
"that answered with another request's answer or dropped the header), so what it says about the call is ignored";
|
|
59
91
|
/** The error for a success answer that is not bound to its request: the call may have run. */
|
|
60
92
|
export function unboundSuccess(method) {
|
|
@@ -140,6 +172,7 @@ function bigVarint(b, i) {
|
|
|
140
172
|
const RECORD_STRINGS = {
|
|
141
173
|
2: "requestSha256", 3: "resultSha256", 4: "provider", 5: "isolation", 6: "environment", 7: "policy",
|
|
142
174
|
10: "session", 12: "previousSha256", 13: "recordSha256", 14: "softwareIdentity", 15: "softwareRuleId", 16: "unanswered", 17: "instance",
|
|
175
|
+
18: "isolationQualification", 20: "daemonVersion",
|
|
143
176
|
};
|
|
144
177
|
// Decodes an UnansweredCall detail (field 1, a RunRecord) by hand, into the record's
|
|
145
178
|
// proto3 JSON form, so the record checks exactly as one read off a JSON answer.
|
|
@@ -199,6 +232,8 @@ function decodeRecord(b) {
|
|
|
199
232
|
m.endedUnixMs = BigInt.asIntN(64, v).toString();
|
|
200
233
|
else if (field === 11)
|
|
201
234
|
m.sequence = v.toString();
|
|
235
|
+
else if (field === 19)
|
|
236
|
+
m.warm = v !== 0n;
|
|
202
237
|
}
|
|
203
238
|
else if (wire === 2) {
|
|
204
239
|
const [n, k] = varint(b, i);
|
|
@@ -232,14 +267,20 @@ const CODES = new Set([
|
|
|
232
267
|
// one without a NotDispatched detail is marked by the daemon's header (mark).
|
|
233
268
|
export function errorFromWire(httpStatus, body, answer) {
|
|
234
269
|
const wire = body !== null && typeof body === "object" && !Array.isArray(body) ? body : undefined;
|
|
235
|
-
|
|
270
|
+
// A details list with an element that is not an object (a JSON null, a number) is not a
|
|
271
|
+
// Connect error this client can read; the Go client panicked on a null (finding
|
|
272
|
+
// release-88). Nothing in such an answer is believed, its header mark included: the code
|
|
273
|
+
// is the HTTP status's and the call reads "may have run".
|
|
274
|
+
const details = Array.isArray(wire?.details) ? wire.details : [];
|
|
275
|
+
const unreadable = details.some((d) => d === null || typeof d !== "object" || Array.isArray(d));
|
|
276
|
+
const code = unreadable || wire?.code === undefined ? httpStatusCode(httpStatus) : CODES.has(wire.code) ? wire.code : "unknown";
|
|
236
277
|
const message = typeof wire?.message === "string" ? wire.message : `HTTP ${httpStatus}`;
|
|
237
278
|
if (!answer.bound)
|
|
238
279
|
return new PlimsollError(code, `${message} (${NOT_BOUND})`, { answerNotBound: true });
|
|
239
280
|
let notDispatched;
|
|
240
281
|
let sessionEnded;
|
|
241
282
|
let unanswered;
|
|
242
|
-
for (const d of
|
|
283
|
+
for (const d of (unreadable ? [] : details)) {
|
|
243
284
|
try {
|
|
244
285
|
const bytes = wireBytes(d.value);
|
|
245
286
|
if (d.type === "plimsoll.v1.NotDispatched") {
|
|
@@ -259,12 +300,21 @@ export function errorFromWire(httpStatus, body, answer) {
|
|
|
259
300
|
// An undecodable detail states nothing; in particular not that nothing ran.
|
|
260
301
|
}
|
|
261
302
|
}
|
|
262
|
-
if (notDispatched === undefined && answer.mark) {
|
|
303
|
+
if (notDispatched === undefined && !unreadable && answer.mark) {
|
|
263
304
|
const named = REFUSAL_NAMES.find((r) => r !== "unknown" && r === answer.mark);
|
|
264
305
|
if (named)
|
|
265
306
|
notDispatched = named;
|
|
266
307
|
}
|
|
267
|
-
|
|
308
|
+
const opts = { notDispatched, sessionEnded, unanswered: notDispatched ? undefined : unanswered };
|
|
309
|
+
// The ownership refusals of a session's run, close or attach (protocol 6): reason
|
|
310
|
+
// permission is a stale worker; reason request with the daemon's constant text is a
|
|
311
|
+
// checkpoint that is not the head.
|
|
312
|
+
if (code === "failed_precondition" && !sessionEnded && notDispatched === "permission")
|
|
313
|
+
return new StaleOwnerError(message, opts);
|
|
314
|
+
if (code === "failed_precondition" && !sessionEnded && notDispatched === "request" && message === CHECKPOINT_MISMATCH_TEXT) {
|
|
315
|
+
return new CheckpointMismatchError(message, opts);
|
|
316
|
+
}
|
|
317
|
+
return new PlimsollError(code, message, opts);
|
|
268
318
|
}
|
|
269
319
|
// Connect's mapping for a response without a Connect error body.
|
|
270
320
|
function httpStatusCode(status) {
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Where a granted Python call carries plimsoll_host (sandbox.HostClientPythonPath). */
|
|
2
|
+
export declare const HOST_MODULE_PATH = ".plimsoll/lib/plimsoll_host.py";
|
|
3
|
+
/** The directory a granted Python step puts on its import path (sandbox.HostClientPythonDir). */
|
|
4
|
+
export declare const HOST_MODULE_DIR = ".plimsoll/lib";
|
|
5
|
+
/** plimsoll_host, the standard-library client a granted Python step calls the broker with (sandbox.HostClientPython). */
|
|
6
|
+
export declare const HOST_MODULE_SOURCE = "\"\"\"plimsoll_host: this run's web API, from Python.\n\nA run that carries a grant can call the routes its grant profile allows. plimsoll's\nbroker, outside the sandbox, checks each request's method and path against the\nprofile's routes, adds the API's credential and makes the call; this module only sends\nthe request to the broker, over the Unix socket named by HOST_API_SOCKET, with the\nstandard library. It holds no credential and needs none.\n\n import plimsoll_host\n lights = plimsoll_host.get(\"/v1/lights\")\n plimsoll_host.post(\"/v1/lights/kitchen/on\", {\"level\": 40})\n\nEach call returns the answer's JSON, parsed (its text when it is not JSON), for a 2xx\nstatus, and raises HostAPIError, with the status and the body, for any other. A route\nthe profile does not allow is refused with 403, a run past its call budget with 429.\n\"\"\"\n\nimport http.client\nimport json\nimport os\nimport socket\n\n__all__ = [\"HostAPIError\", \"call\", \"get\", \"post\", \"put\", \"patch\", \"delete\"]\n\n# The broker bounds every call by the run's own deadline; this only keeps a socket that\n# never answers from holding the program past the daemon's five-minute ceiling.\n_TIMEOUT = 300\n\n\nclass HostAPIError(Exception):\n \"\"\"An answer outside 2xx: status is the HTTP status (0 when the broker could not be\n reached), body the answer's JSON parsed (its text when it is not JSON).\"\"\"\n\n def __init__(self, status, body, text):\n super().__init__(\"host api %d: %s\" % (status, text))\n self.status = status\n self.body = body\n\n\nclass _BrokerConnection(http.client.HTTPConnection):\n def __init__(self, path):\n super().__init__(\"localhost\", timeout=_TIMEOUT)\n self._socket_path = path\n\n def connect(self):\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.settimeout(self.timeout)\n try:\n sock.connect(self._socket_path)\n except BaseException:\n sock.close()\n raise\n self.sock = sock\n\n\ndef call(method, path, body=None):\n \"\"\"Sends one request: method (GET, POST, PUT, PATCH, DELETE), a path that starts\n with \"/\" and has no query, and a body that is sent as JSON when it is not None.\"\"\"\n where = os.environ.get(\"HOST_API_SOCKET\", \"\")\n if not where:\n raise HostAPIError(0, None, \"host api broker unavailable: this run carries no grant\")\n method = str(method).upper()\n payload = None if body is None else json.dumps(body).encode(\"utf-8\")\n headers = {\"Content-Type\": \"application/json\"} if payload is not None else {}\n conn = _BrokerConnection(where)\n try:\n try:\n conn.request(method, str(path), body=payload, headers=headers)\n answer = conn.getresponse()\n raw = answer.read()\n except OSError as e:\n raise HostAPIError(0, None, \"host api broker unavailable: %s\" % e) from e\n finally:\n conn.close()\n text = raw.decode(\"utf-8\", \"replace\")\n try:\n data = json.loads(text)\n except ValueError:\n data = text\n if 200 <= answer.status < 300:\n return data\n raise HostAPIError(answer.status, data, text)\n\n\ndef get(path):\n return call(\"GET\", path)\n\n\ndef post(path, body=None):\n return call(\"POST\", path, body)\n\n\ndef put(path, body=None):\n return call(\"PUT\", path, body)\n\n\ndef patch(path, body=None):\n return call(\"PATCH\", path, body)\n\n\ndef delete(path):\n return call(\"DELETE\", path)\n";
|
|
7
|
+
/** The providers whose granted project steps, Python's included, get the broker's socket (sandbox.PythonGrantProviders). */
|
|
8
|
+
export declare const PYTHON_GRANT_PROVIDERS: readonly ["docker", "openshell"];
|
|
9
|
+
/** Each language's granted cell form (sandbox.GrantedCellProject): the files written beside the cell's code, the path the code goes to, and the one step. */
|
|
10
|
+
export declare const GRANTED_CELL: {
|
|
11
|
+
readonly javascript: {
|
|
12
|
+
readonly files: readonly [{
|
|
13
|
+
readonly path: ".plimsoll/run.cjs";
|
|
14
|
+
readonly content: "const fs = require('node:fs'), util = require('node:util'), vm = require('node:vm');\nglobalThis.require = require('node:module').createRequire(process.cwd() + '/');\nglobalThis.module = { exports: {} }; globalThis.exports = globalThis.module.exports;\nglobalThis.__dirname = '.'; globalThis.__filename = '[eval]';\nlet tla = null;\ntry { tla = require('internal/repl/await').processTopLevelAwait; } catch {}\nconst src = fs.readFileSync('.plimsoll/cell.js', 'utf8');\nlet wrapped = null;\nif (tla) { try { wrapped = tla(src); } catch {} }\n(async () => {\n let v;\n if (wrapped) {\n const out = await vm.runInThisContext(wrapped, { filename: 'cell.js' });\n v = out === undefined ? undefined : out.value;\n } else {\n v = vm.runInThisContext(src, { filename: 'cell.js' });\n if (v instanceof Promise) v = await v;\n }\n if (v !== undefined) console.log(util.inspect(v, { depth: 4 }));\n})().catch((e) => { console.error(e); process.exitCode = 1; });\n";
|
|
15
|
+
}];
|
|
16
|
+
readonly codePath: ".plimsoll/cell.js";
|
|
17
|
+
readonly step: "node --expose-internals .plimsoll/run.cjs";
|
|
18
|
+
};
|
|
19
|
+
readonly python: {
|
|
20
|
+
readonly files: readonly [{
|
|
21
|
+
readonly path: ".plimsoll/run.py";
|
|
22
|
+
readonly content: "import ast, asyncio, inspect, linecache, sys\nsys.path.insert(0, '')\nsrc = open('.plimsoll/cell.py', encoding='utf-8').read()\nlinecache.cache['cell'] = (len(src), None, src.splitlines(True), 'cell')\ntree = ast.parse(src, 'cell', 'exec')\nlast = ast.Expression(tree.body.pop().value) if tree.body and isinstance(tree.body[-1], ast.Expr) else None\nns = {'__name__': '__main__', '__builtins__': __builtins__}\nflags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT\nloop = asyncio.new_event_loop()\ndef settle(r):\n return loop.run_until_complete(r) if inspect.isawaitable(r) else r\nsettle(eval(compile(tree, 'cell', 'exec', flags=flags), ns))\nif last is not None:\n value = settle(eval(compile(last, 'cell', 'eval', flags=flags), ns))\n if value is not None:\n print(repr(value))\n";
|
|
23
|
+
}, {
|
|
24
|
+
readonly path: ".plimsoll/lib/plimsoll_host.py";
|
|
25
|
+
readonly content: "\"\"\"plimsoll_host: this run's web API, from Python.\n\nA run that carries a grant can call the routes its grant profile allows. plimsoll's\nbroker, outside the sandbox, checks each request's method and path against the\nprofile's routes, adds the API's credential and makes the call; this module only sends\nthe request to the broker, over the Unix socket named by HOST_API_SOCKET, with the\nstandard library. It holds no credential and needs none.\n\n import plimsoll_host\n lights = plimsoll_host.get(\"/v1/lights\")\n plimsoll_host.post(\"/v1/lights/kitchen/on\", {\"level\": 40})\n\nEach call returns the answer's JSON, parsed (its text when it is not JSON), for a 2xx\nstatus, and raises HostAPIError, with the status and the body, for any other. A route\nthe profile does not allow is refused with 403, a run past its call budget with 429.\n\"\"\"\n\nimport http.client\nimport json\nimport os\nimport socket\n\n__all__ = [\"HostAPIError\", \"call\", \"get\", \"post\", \"put\", \"patch\", \"delete\"]\n\n# The broker bounds every call by the run's own deadline; this only keeps a socket that\n# never answers from holding the program past the daemon's five-minute ceiling.\n_TIMEOUT = 300\n\n\nclass HostAPIError(Exception):\n \"\"\"An answer outside 2xx: status is the HTTP status (0 when the broker could not be\n reached), body the answer's JSON parsed (its text when it is not JSON).\"\"\"\n\n def __init__(self, status, body, text):\n super().__init__(\"host api %d: %s\" % (status, text))\n self.status = status\n self.body = body\n\n\nclass _BrokerConnection(http.client.HTTPConnection):\n def __init__(self, path):\n super().__init__(\"localhost\", timeout=_TIMEOUT)\n self._socket_path = path\n\n def connect(self):\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.settimeout(self.timeout)\n try:\n sock.connect(self._socket_path)\n except BaseException:\n sock.close()\n raise\n self.sock = sock\n\n\ndef call(method, path, body=None):\n \"\"\"Sends one request: method (GET, POST, PUT, PATCH, DELETE), a path that starts\n with \"/\" and has no query, and a body that is sent as JSON when it is not None.\"\"\"\n where = os.environ.get(\"HOST_API_SOCKET\", \"\")\n if not where:\n raise HostAPIError(0, None, \"host api broker unavailable: this run carries no grant\")\n method = str(method).upper()\n payload = None if body is None else json.dumps(body).encode(\"utf-8\")\n headers = {\"Content-Type\": \"application/json\"} if payload is not None else {}\n conn = _BrokerConnection(where)\n try:\n try:\n conn.request(method, str(path), body=payload, headers=headers)\n answer = conn.getresponse()\n raw = answer.read()\n except OSError as e:\n raise HostAPIError(0, None, \"host api broker unavailable: %s\" % e) from e\n finally:\n conn.close()\n text = raw.decode(\"utf-8\", \"replace\")\n try:\n data = json.loads(text)\n except ValueError:\n data = text\n if 200 <= answer.status < 300:\n return data\n raise HostAPIError(answer.status, data, text)\n\n\ndef get(path):\n return call(\"GET\", path)\n\n\ndef post(path, body=None):\n return call(\"POST\", path, body)\n\n\ndef put(path, body=None):\n return call(\"PUT\", path, body)\n\n\ndef patch(path, body=None):\n return call(\"PATCH\", path, body)\n\n\ndef delete(path):\n return call(\"DELETE\", path)\n";
|
|
26
|
+
}];
|
|
27
|
+
readonly codePath: ".plimsoll/cell.py";
|
|
28
|
+
readonly step: "python3 -I -c 'import sys; sys.path.insert(0, \".plimsoll/lib\"); exec(compile(open(\".plimsoll/run.py\", encoding=\"utf-8\").read(), \".plimsoll/run.py\", \"exec\"))'";
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
/** A JavaScript cell as a snippet that prints its final value (sandbox.SnippetCell): SNIPPET_CELL[0], the code as a JSON string literal, SNIPPET_CELL[1]. */
|
|
32
|
+
export declare const SNIPPET_CELL: readonly ["(() => {\n const show = (v) => {\n if (typeof require === \"function\") { try { return require(\"node:util\").inspect(v, { depth: 4 }); } catch (_) {} }\n try { const s = JSON.stringify(v); if (s !== undefined) return s; } catch (_) {}\n return String(v);\n };\n const v = (0, eval)(", ");\n Promise.resolve(v).then((v) => { if (v !== undefined) console.log(show(v)); });\n})();\n"];
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Code generated by internal/wiretables (make generate). DO NOT EDIT.
|
|
2
|
+
// What a granted call of a code tool writes into its project, from package sandbox
|
|
3
|
+
// (hostclient.go, cell_fresh.go): the Python module plimsoll_host, where it goes, the
|
|
4
|
+
// providers whose Python steps can reach the broker through it, and each language's
|
|
5
|
+
// granted cell form.
|
|
6
|
+
/** Where a granted Python call carries plimsoll_host (sandbox.HostClientPythonPath). */
|
|
7
|
+
export const HOST_MODULE_PATH = ".plimsoll/lib/plimsoll_host.py";
|
|
8
|
+
/** The directory a granted Python step puts on its import path (sandbox.HostClientPythonDir). */
|
|
9
|
+
export const HOST_MODULE_DIR = ".plimsoll/lib";
|
|
10
|
+
/** plimsoll_host, the standard-library client a granted Python step calls the broker with (sandbox.HostClientPython). */
|
|
11
|
+
export const HOST_MODULE_SOURCE = "\"\"\"plimsoll_host: this run's web API, from Python.\n\nA run that carries a grant can call the routes its grant profile allows. plimsoll's\nbroker, outside the sandbox, checks each request's method and path against the\nprofile's routes, adds the API's credential and makes the call; this module only sends\nthe request to the broker, over the Unix socket named by HOST_API_SOCKET, with the\nstandard library. It holds no credential and needs none.\n\n import plimsoll_host\n lights = plimsoll_host.get(\"/v1/lights\")\n plimsoll_host.post(\"/v1/lights/kitchen/on\", {\"level\": 40})\n\nEach call returns the answer's JSON, parsed (its text when it is not JSON), for a 2xx\nstatus, and raises HostAPIError, with the status and the body, for any other. A route\nthe profile does not allow is refused with 403, a run past its call budget with 429.\n\"\"\"\n\nimport http.client\nimport json\nimport os\nimport socket\n\n__all__ = [\"HostAPIError\", \"call\", \"get\", \"post\", \"put\", \"patch\", \"delete\"]\n\n# The broker bounds every call by the run's own deadline; this only keeps a socket that\n# never answers from holding the program past the daemon's five-minute ceiling.\n_TIMEOUT = 300\n\n\nclass HostAPIError(Exception):\n \"\"\"An answer outside 2xx: status is the HTTP status (0 when the broker could not be\n reached), body the answer's JSON parsed (its text when it is not JSON).\"\"\"\n\n def __init__(self, status, body, text):\n super().__init__(\"host api %d: %s\" % (status, text))\n self.status = status\n self.body = body\n\n\nclass _BrokerConnection(http.client.HTTPConnection):\n def __init__(self, path):\n super().__init__(\"localhost\", timeout=_TIMEOUT)\n self._socket_path = path\n\n def connect(self):\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.settimeout(self.timeout)\n try:\n sock.connect(self._socket_path)\n except BaseException:\n sock.close()\n raise\n self.sock = sock\n\n\ndef call(method, path, body=None):\n \"\"\"Sends one request: method (GET, POST, PUT, PATCH, DELETE), a path that starts\n with \"/\" and has no query, and a body that is sent as JSON when it is not None.\"\"\"\n where = os.environ.get(\"HOST_API_SOCKET\", \"\")\n if not where:\n raise HostAPIError(0, None, \"host api broker unavailable: this run carries no grant\")\n method = str(method).upper()\n payload = None if body is None else json.dumps(body).encode(\"utf-8\")\n headers = {\"Content-Type\": \"application/json\"} if payload is not None else {}\n conn = _BrokerConnection(where)\n try:\n try:\n conn.request(method, str(path), body=payload, headers=headers)\n answer = conn.getresponse()\n raw = answer.read()\n except OSError as e:\n raise HostAPIError(0, None, \"host api broker unavailable: %s\" % e) from e\n finally:\n conn.close()\n text = raw.decode(\"utf-8\", \"replace\")\n try:\n data = json.loads(text)\n except ValueError:\n data = text\n if 200 <= answer.status < 300:\n return data\n raise HostAPIError(answer.status, data, text)\n\n\ndef get(path):\n return call(\"GET\", path)\n\n\ndef post(path, body=None):\n return call(\"POST\", path, body)\n\n\ndef put(path, body=None):\n return call(\"PUT\", path, body)\n\n\ndef patch(path, body=None):\n return call(\"PATCH\", path, body)\n\n\ndef delete(path):\n return call(\"DELETE\", path)\n";
|
|
12
|
+
/** The providers whose granted project steps, Python's included, get the broker's socket (sandbox.PythonGrantProviders). */
|
|
13
|
+
export const PYTHON_GRANT_PROVIDERS = ["docker", "openshell"];
|
|
14
|
+
/** Each language's granted cell form (sandbox.GrantedCellProject): the files written beside the cell's code, the path the code goes to, and the one step. */
|
|
15
|
+
export const GRANTED_CELL = {
|
|
16
|
+
javascript: {
|
|
17
|
+
files: [
|
|
18
|
+
{ path: ".plimsoll/run.cjs", content: "const fs = require('node:fs'), util = require('node:util'), vm = require('node:vm');\nglobalThis.require = require('node:module').createRequire(process.cwd() + '/');\nglobalThis.module = { exports: {} }; globalThis.exports = globalThis.module.exports;\nglobalThis.__dirname = '.'; globalThis.__filename = '[eval]';\nlet tla = null;\ntry { tla = require('internal/repl/await').processTopLevelAwait; } catch {}\nconst src = fs.readFileSync('.plimsoll/cell.js', 'utf8');\nlet wrapped = null;\nif (tla) { try { wrapped = tla(src); } catch {} }\n(async () => {\n let v;\n if (wrapped) {\n const out = await vm.runInThisContext(wrapped, { filename: 'cell.js' });\n v = out === undefined ? undefined : out.value;\n } else {\n v = vm.runInThisContext(src, { filename: 'cell.js' });\n if (v instanceof Promise) v = await v;\n }\n if (v !== undefined) console.log(util.inspect(v, { depth: 4 }));\n})().catch((e) => { console.error(e); process.exitCode = 1; });\n" },
|
|
19
|
+
],
|
|
20
|
+
codePath: ".plimsoll/cell.js",
|
|
21
|
+
step: "node --expose-internals .plimsoll/run.cjs",
|
|
22
|
+
},
|
|
23
|
+
python: {
|
|
24
|
+
files: [
|
|
25
|
+
{ path: ".plimsoll/run.py", content: "import ast, asyncio, inspect, linecache, sys\nsys.path.insert(0, '')\nsrc = open('.plimsoll/cell.py', encoding='utf-8').read()\nlinecache.cache['cell'] = (len(src), None, src.splitlines(True), 'cell')\ntree = ast.parse(src, 'cell', 'exec')\nlast = ast.Expression(tree.body.pop().value) if tree.body and isinstance(tree.body[-1], ast.Expr) else None\nns = {'__name__': '__main__', '__builtins__': __builtins__}\nflags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT\nloop = asyncio.new_event_loop()\ndef settle(r):\n return loop.run_until_complete(r) if inspect.isawaitable(r) else r\nsettle(eval(compile(tree, 'cell', 'exec', flags=flags), ns))\nif last is not None:\n value = settle(eval(compile(last, 'cell', 'eval', flags=flags), ns))\n if value is not None:\n print(repr(value))\n" },
|
|
26
|
+
{ path: ".plimsoll/lib/plimsoll_host.py", content: "\"\"\"plimsoll_host: this run's web API, from Python.\n\nA run that carries a grant can call the routes its grant profile allows. plimsoll's\nbroker, outside the sandbox, checks each request's method and path against the\nprofile's routes, adds the API's credential and makes the call; this module only sends\nthe request to the broker, over the Unix socket named by HOST_API_SOCKET, with the\nstandard library. It holds no credential and needs none.\n\n import plimsoll_host\n lights = plimsoll_host.get(\"/v1/lights\")\n plimsoll_host.post(\"/v1/lights/kitchen/on\", {\"level\": 40})\n\nEach call returns the answer's JSON, parsed (its text when it is not JSON), for a 2xx\nstatus, and raises HostAPIError, with the status and the body, for any other. A route\nthe profile does not allow is refused with 403, a run past its call budget with 429.\n\"\"\"\n\nimport http.client\nimport json\nimport os\nimport socket\n\n__all__ = [\"HostAPIError\", \"call\", \"get\", \"post\", \"put\", \"patch\", \"delete\"]\n\n# The broker bounds every call by the run's own deadline; this only keeps a socket that\n# never answers from holding the program past the daemon's five-minute ceiling.\n_TIMEOUT = 300\n\n\nclass HostAPIError(Exception):\n \"\"\"An answer outside 2xx: status is the HTTP status (0 when the broker could not be\n reached), body the answer's JSON parsed (its text when it is not JSON).\"\"\"\n\n def __init__(self, status, body, text):\n super().__init__(\"host api %d: %s\" % (status, text))\n self.status = status\n self.body = body\n\n\nclass _BrokerConnection(http.client.HTTPConnection):\n def __init__(self, path):\n super().__init__(\"localhost\", timeout=_TIMEOUT)\n self._socket_path = path\n\n def connect(self):\n sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n sock.settimeout(self.timeout)\n try:\n sock.connect(self._socket_path)\n except BaseException:\n sock.close()\n raise\n self.sock = sock\n\n\ndef call(method, path, body=None):\n \"\"\"Sends one request: method (GET, POST, PUT, PATCH, DELETE), a path that starts\n with \"/\" and has no query, and a body that is sent as JSON when it is not None.\"\"\"\n where = os.environ.get(\"HOST_API_SOCKET\", \"\")\n if not where:\n raise HostAPIError(0, None, \"host api broker unavailable: this run carries no grant\")\n method = str(method).upper()\n payload = None if body is None else json.dumps(body).encode(\"utf-8\")\n headers = {\"Content-Type\": \"application/json\"} if payload is not None else {}\n conn = _BrokerConnection(where)\n try:\n try:\n conn.request(method, str(path), body=payload, headers=headers)\n answer = conn.getresponse()\n raw = answer.read()\n except OSError as e:\n raise HostAPIError(0, None, \"host api broker unavailable: %s\" % e) from e\n finally:\n conn.close()\n text = raw.decode(\"utf-8\", \"replace\")\n try:\n data = json.loads(text)\n except ValueError:\n data = text\n if 200 <= answer.status < 300:\n return data\n raise HostAPIError(answer.status, data, text)\n\n\ndef get(path):\n return call(\"GET\", path)\n\n\ndef post(path, body=None):\n return call(\"POST\", path, body)\n\n\ndef put(path, body=None):\n return call(\"PUT\", path, body)\n\n\ndef patch(path, body=None):\n return call(\"PATCH\", path, body)\n\n\ndef delete(path):\n return call(\"DELETE\", path)\n" },
|
|
27
|
+
],
|
|
28
|
+
codePath: ".plimsoll/cell.py",
|
|
29
|
+
step: "python3 -I -c 'import sys; sys.path.insert(0, \".plimsoll/lib\"); exec(compile(open(\".plimsoll/run.py\", encoding=\"utf-8\").read(), \".plimsoll/run.py\", \"exec\"))'",
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
/** A JavaScript cell as a snippet that prints its final value (sandbox.SnippetCell): SNIPPET_CELL[0], the code as a JSON string literal, SNIPPET_CELL[1]. */
|
|
33
|
+
export const SNIPPET_CELL = ["(() => {\n const show = (v) => {\n if (typeof require === \"function\") { try { return require(\"node:util\").inspect(v, { depth: 4 }); } catch (_) {} }\n try { const s = JSON.stringify(v); if (s !== undefined) return s; } catch (_) {}\n return String(v);\n };\n const v = (0, eval)(", ");\n Promise.resolve(v).then((v) => { if (v !== undefined) console.log(show(v)); });\n})();\n"];
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
export { PlimsollClient, Session, PROTOCOL, meets, type AdviceFinding, type CellRequest, type CellResult, type ClientOptions, type Evidence, type Info, type Isolation, type JavaScriptResult, type Language, type PayloadEnvironment, type ProjectOutcome, type ProjectRequest, type ProjectResult, type RunOptions, type SessionOptions, type SessionSummary, type SoftwareRule, type StepResult, } from "./client.ts";
|
|
2
|
-
export { PlimsollError, type Code, type Refusal, type SessionEnd } from "./errors.ts";
|
|
1
|
+
export { PlimsollClient, Session, PROTOCOL, meets, type AdviceFinding, type CellRequest, type CellResult, type ClientOptions, type Evidence, type Info, type Isolation, type JavaScriptResult, type Language, type PayloadEnvironment, type ProjectOutcome, type ProjectRequest, type ProjectResult, type GrantRunOptions, type RunOptions, type SessionOptions, type SessionSummary, type SoftwareRule, type StepResult, } from "./client.ts";
|
|
2
|
+
export { CallAlreadySentError, CheckpointMismatchError, PlimsollError, StaleOwnerError, type Code, type Refusal, type SessionEnd } from "./errors.ts";
|
|
3
|
+
export { checkpointProblem, checkpointToJSON, parseCheckpoint, validateCheckpoint, type SessionCheckpoint } from "./checkpoint.ts";
|
|
3
4
|
export type { RunRecord } from "./record.ts";
|
|
4
|
-
export { CodeSandboxes, DEFAULT_LANGUAGES, type CodeSandboxesOptions, type ExecuteCodeInput, type ExecuteCodeOutput, type SessionMode, type ToolLanguages, } from "./sandboxes.ts";
|
|
5
|
+
export { CodeSandboxes, DEFAULT_LANGUAGES, type CodeSandboxesOptions, type ExecuteCodeInput, type ExecuteCodeOutput, type GrantPlan, type SessionMode, type ToolGrant, type ToolLanguages, } from "./sandboxes.ts";
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { PlimsollClient, Session, PROTOCOL, meets, } from "./client.js";
|
|
2
|
-
export { PlimsollError } from "./errors.js";
|
|
2
|
+
export { CallAlreadySentError, CheckpointMismatchError, PlimsollError, StaleOwnerError } from "./errors.js";
|
|
3
|
+
export { checkpointProblem, checkpointToJSON, parseCheckpoint, validateCheckpoint } from "./checkpoint.js";
|
|
3
4
|
export { CodeSandboxes, DEFAULT_LANGUAGES, } from "./sandboxes.js";
|
package/dist/mastra.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ToolExecutionContext } from "@mastra/core/tools";
|
|
2
|
-
import { CodeSandboxes, type CodeSandboxesOptions } from "./sandboxes.ts";
|
|
2
|
+
import { CodeSandboxes, type CodeSandboxesOptions, type ToolGrant } from "./sandboxes.ts";
|
|
3
3
|
export type PlimsollExecuteCodeOptions = CodeSandboxesOptions & {
|
|
4
4
|
/**
|
|
5
5
|
* The user a call belongs to, from your app's own authentication (a value your server
|
|
@@ -11,6 +11,42 @@ export type PlimsollExecuteCodeOptions = CodeSandboxesOptions & {
|
|
|
11
11
|
*/
|
|
12
12
|
owner?: (ctx: ToolExecutionContext) => string | undefined;
|
|
13
13
|
};
|
|
14
|
+
/**
|
|
15
|
+
* The executeCode tool with a grant: every call can reach the one web API the operator's
|
|
16
|
+
* profile allows (plimsollGrantedCodeTool's account, in the AI SDK add-on, holds here
|
|
17
|
+
* too). Built after the daemon's Describe, read once, here, which decides the languages it offers; every
|
|
18
|
+
* call runs in a sandbox of its own, whatever the thread, so kept state is not available
|
|
19
|
+
* to it. Its id is executeCode unless id names another, so an agent can hold it beside
|
|
20
|
+
* plimsollExecuteCode's tool.
|
|
21
|
+
*/
|
|
22
|
+
export declare function plimsollGrantedExecuteCode(opts: CodeSandboxesOptions & {
|
|
23
|
+
grant: ToolGrant;
|
|
24
|
+
id?: string;
|
|
25
|
+
}): Promise<{
|
|
26
|
+
executeCode: import("@mastra/core/tools").Tool<{
|
|
27
|
+
code: string;
|
|
28
|
+
language: "javascript" | "python";
|
|
29
|
+
files?: {
|
|
30
|
+
path: string;
|
|
31
|
+
content: string;
|
|
32
|
+
}[] | undefined;
|
|
33
|
+
}, {
|
|
34
|
+
language: string;
|
|
35
|
+
exitCode: number;
|
|
36
|
+
timedOut: boolean;
|
|
37
|
+
stdout: string;
|
|
38
|
+
stderr: string;
|
|
39
|
+
truncated: boolean;
|
|
40
|
+
stateKept: boolean;
|
|
41
|
+
freshInterpreter?: true | undefined;
|
|
42
|
+
filesPersist: boolean;
|
|
43
|
+
freshSandbox?: true | undefined;
|
|
44
|
+
isolation: string;
|
|
45
|
+
isolationQualification?: string | undefined;
|
|
46
|
+
recordSha256: string;
|
|
47
|
+
}, unknown, unknown, ToolExecutionContext<unknown, unknown, unknown>, string, unknown>;
|
|
48
|
+
sandboxes: CodeSandboxes;
|
|
49
|
+
}>;
|
|
14
50
|
export declare function plimsollExecuteCode(opts: PlimsollExecuteCodeOptions): {
|
|
15
51
|
executeCode: import("@mastra/core/tools").Tool<{
|
|
16
52
|
code: string;
|
|
@@ -31,6 +67,7 @@ export declare function plimsollExecuteCode(opts: PlimsollExecuteCodeOptions): {
|
|
|
31
67
|
filesPersist: boolean;
|
|
32
68
|
freshSandbox?: true | undefined;
|
|
33
69
|
isolation: string;
|
|
70
|
+
isolationQualification?: string | undefined;
|
|
34
71
|
recordSha256: string;
|
|
35
72
|
}, unknown, unknown, ToolExecutionContext<unknown, unknown, unknown>, "executeCode", unknown>;
|
|
36
73
|
/** Closes a user's thread's sandbox, e.g. when the conversation ends; owner is the one the option gave. */
|
package/dist/mastra.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// sandbox closes when you call dispose(threadId), or after idleCloseMs without a
|
|
4
4
|
// call, whichever comes first.
|
|
5
5
|
import { createTool } from "@mastra/core/tools";
|
|
6
|
-
import { CodeSandboxes } from "./sandboxes.js";
|
|
6
|
+
import { CodeSandboxes, offeredForGrant, refuseGrant } from "./sandboxes.js";
|
|
7
7
|
import { executeCodeDescription, executeCodeInput, executeCodeOutput } from "./tool.js";
|
|
8
8
|
// A thread id is unique only within its resource (the user), so the key is both, the
|
|
9
9
|
// resource as the owner the per-user cap counts, and a call without either has no key
|
|
@@ -16,7 +16,29 @@ const threadKey = (threadId, resourceId, owner) => !threadId || !resourceId
|
|
|
16
16
|
: owner === undefined
|
|
17
17
|
? { owner: resourceId, conversation: threadId }
|
|
18
18
|
: { owner, conversation: JSON.stringify([resourceId, threadId]) };
|
|
19
|
+
/**
|
|
20
|
+
* The executeCode tool with a grant: every call can reach the one web API the operator's
|
|
21
|
+
* profile allows (plimsollGrantedCodeTool's account, in the AI SDK add-on, holds here
|
|
22
|
+
* too). Built after the daemon's Describe, read once, here, which decides the languages it offers; every
|
|
23
|
+
* call runs in a sandbox of its own, whatever the thread, so kept state is not available
|
|
24
|
+
* to it. Its id is executeCode unless id names another, so an agent can hold it beside
|
|
25
|
+
* plimsollExecuteCode's tool.
|
|
26
|
+
*/
|
|
27
|
+
export async function plimsollGrantedExecuteCode(opts) {
|
|
28
|
+
const sandboxes = new CodeSandboxes(opts);
|
|
29
|
+
const plan = await sandboxes.grantPlan();
|
|
30
|
+
const languages = offeredForGrant(sandboxes.languages, plan);
|
|
31
|
+
const executeCode = createTool({
|
|
32
|
+
id: opts.id ?? "executeCode",
|
|
33
|
+
description: executeCodeDescription(languages, "fresh", plan),
|
|
34
|
+
inputSchema: executeCodeInput(languages, true),
|
|
35
|
+
outputSchema: executeCodeOutput,
|
|
36
|
+
execute: async (input, ctx) => sandboxes.run(undefined, input, ctx?.abortSignal),
|
|
37
|
+
});
|
|
38
|
+
return { executeCode, sandboxes };
|
|
39
|
+
}
|
|
19
40
|
export function plimsollExecuteCode(opts) {
|
|
41
|
+
refuseGrant(opts, "plimsollGrantedExecuteCode");
|
|
20
42
|
const sandboxes = new CodeSandboxes(opts);
|
|
21
43
|
const executeCode = createTool({
|
|
22
44
|
id: "executeCode",
|
package/dist/record.d.ts
CHANGED
|
@@ -1,8 +1,26 @@
|
|
|
1
1
|
import { type WireRecord, type WireRunResponse, type WireSoftwareRule } from "./wire.ts";
|
|
2
|
-
/** The record encoding version this client computes and checks: every field, every time, for an answered call and an unanswered session call alike. */
|
|
3
|
-
export declare const RECORD_VERSION = 4;
|
|
4
2
|
/** A record's instance: "" (the provider names none) or a typed reference such as `k8s-pod-uid:` and a pod's UID. */
|
|
5
3
|
export declare function validInstance(s: string): boolean;
|
|
4
|
+
/**
|
|
5
|
+
* Text a record may state where a reader is shown it as it is: UTF-8 with no control
|
|
6
|
+
* character and none of the format characters that break a line or reorder displayed text,
|
|
7
|
+
* as record.ValidText. A lone surrogate is not UTF-8. The provider's name, the tier and the
|
|
8
|
+
* isolation qualification are held to it (shownFields).
|
|
9
|
+
*/
|
|
10
|
+
export declare function validText(s: string): boolean;
|
|
11
|
+
/** A record's fields a reader is shown as the run's evidence, each with the name a refusal gives it, as record.ShownFields. */
|
|
12
|
+
export declare function shownFields(r: RunRecord): readonly (readonly [string, string])[];
|
|
13
|
+
/**
|
|
14
|
+
* A record's isolation qualification: "" (the provider states none), or at most
|
|
15
|
+
* MAX_QUALIFICATION_BYTES of UTF-8 that validText accepts, as record.ValidQualification.
|
|
16
|
+
*/
|
|
17
|
+
export declare function validQualification(s: string): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* A record's daemon version: "", "(devel)", or a module version such as "v0.28.0" or a
|
|
20
|
+
* pseudo-version, at most MAX_DAEMON_VERSION_BYTES (the grammar is ASCII, so characters are
|
|
21
|
+
* bytes), as record.ValidDaemonVersion.
|
|
22
|
+
*/
|
|
23
|
+
export declare function validDaemonVersion(s: string): boolean;
|
|
6
24
|
/** The payload of a request as the digest sees it. */
|
|
7
25
|
export type DigestPayload = {
|
|
8
26
|
kind: "javascript";
|
|
@@ -59,11 +77,27 @@ export type RunRecord = {
|
|
|
59
77
|
unanswered: string;
|
|
60
78
|
/** The sandbox instance that ran the call, as the response states it, or "". */
|
|
61
79
|
instance: string;
|
|
80
|
+
/** The sentence the provider states beside the tier, as the response states it, or "" (record version 5). */
|
|
81
|
+
isolationQualification: string;
|
|
82
|
+
/** Whether a waiting pool sandbox ran the call, as the response states it (record version 5). */
|
|
83
|
+
warm: boolean;
|
|
84
|
+
/** The answering daemon's plimsoll module version, as the response states it (record version 5). */
|
|
85
|
+
daemonVersion: string;
|
|
62
86
|
sha256: string;
|
|
63
87
|
};
|
|
64
88
|
export declare function recordFromWire(m: WireRecord): RunRecord;
|
|
65
89
|
/** A record's own digest, over the fields its version covers (every field but its digest for an unknown version). */
|
|
66
90
|
export declare function recordDigest(r: RunRecord): string;
|
|
91
|
+
/**
|
|
92
|
+
* The fields a record's version does not cover are unset, it states a result digest or,
|
|
93
|
+
* for an unanswered call, an error code, exactly one, and the code is one of the closed
|
|
94
|
+
* set, its tier is one of TIERS (never "unknown" or empty, whatever floor the request
|
|
95
|
+
* named), it does not end before it starts, answered or not, its qualification and daemon
|
|
96
|
+
* version are in their bounds, and its instance is a typed reference (record.statesOnly).
|
|
97
|
+
* The record of a call lost across a takeover is checked by this alone.
|
|
98
|
+
* Returns the reason it fails, or undefined.
|
|
99
|
+
*/
|
|
100
|
+
export declare function statesOnlyProblem(r: RunRecord): string | undefined;
|
|
67
101
|
/** The SHA-256 of a session ID: what a session call's record carries instead of the ID. */
|
|
68
102
|
export declare function sessionFingerprint(sessionId: string): string;
|
|
69
103
|
/**
|