@plimsollmark/client 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/errors.d.ts CHANGED
@@ -2,8 +2,12 @@ import type { RunRecord } from "./record.ts";
2
2
  import type { WireError, WireRecord } from "./wire.ts";
3
3
  /** Why a request was refused before any code ran (plimsoll.v1.NotDispatchedReason). */
4
4
  export type Refusal = "request" | "permission" | "protocol" | "unsupported" | "isolation" | "capacity" | "environment" | "unknown";
5
- /** Why a session ended (plimsoll.v1.SessionEnd), "open" while it has not. */
6
- export type SessionEnd = "open" | "closed" | "expired" | "disk_exceeded" | "main_process_ended" | "boundary_failed" | "sandbox_changed" | "shutdown";
5
+ /**
6
+ * Why a session ended (plimsoll.v1.SessionEnd), "open" while it has not. "unknown" is
7
+ * an end this client has no name for (a daemon newer than the client): the session
8
+ * ended, for a reason it cannot name.
9
+ */
10
+ export type SessionEnd = "open" | "closed" | "expired" | "disk_exceeded" | "main_process_ended" | "boundary_failed" | "sandbox_changed" | "shutdown" | "replaced" | "not_found" | "unclaimed" | "unknown";
7
11
  /**
8
12
  * Connect's status codes, plus the two this client raises itself:
9
13
  * "data_loss" for an answer that does not check (the run may have executed),
@@ -23,9 +27,10 @@ export declare class PlimsollError extends Error {
23
27
  detail: string;
24
28
  } | undefined;
25
29
  /**
26
- * The result the daemon returned, on a "data_loss" error raised after it
27
- * answered: the record or the isolation evidence did not check, the run may
28
- * have executed, and this is what came back.
30
+ * The result the daemon returned, on an error raised after it answered, so the
31
+ * run may have executed: "data_loss" when the record or the isolation evidence
32
+ * did not check, and "unknown" from CodeSandboxes when a fresh run came back
33
+ * with no step report. This is what came back.
29
34
  */
30
35
  readonly result: unknown;
31
36
  /**
@@ -39,6 +44,13 @@ export declare class PlimsollError extends Error {
39
44
  * UnansweredCallError.Record); undefined otherwise.
40
45
  */
41
46
  record: RunRecord | undefined;
47
+ /**
48
+ * True when the error comes from an answer that did not carry this request's
49
+ * Plimsoll-Request-Id back (Go: client.ErrAnswerNotBound): nothing it said about the
50
+ * call was believed, so it has no notDispatched, sessionEnded or unanswered. On a
51
+ * success the code is "data_loss": the call may have run.
52
+ */
53
+ readonly answerNotBound: boolean;
42
54
  constructor(code: Code, message: string, opts?: {
43
55
  notDispatched?: Refusal;
44
56
  sessionEnded?: {
@@ -47,8 +59,18 @@ export declare class PlimsollError extends Error {
47
59
  };
48
60
  result?: unknown;
49
61
  unanswered?: WireRecord;
62
+ answerNotBound?: boolean;
50
63
  cause?: unknown;
51
64
  });
52
65
  }
66
+ /** The request ID a client sends and the daemon echoes (Go: protocol.RequestIDHeader). */
67
+ export declare const REQUEST_ID_HEADER = "Plimsoll-Request-Id";
68
+ /** The daemon's mark on an answer written before any handler ran (Go: protocol.NotDispatchedHeader). */
69
+ export declare const NOT_DISPATCHED_HEADER = "Plimsoll-Not-Dispatched";
70
+ /** The error for a success answer that is not bound to its request: the call may have run. */
71
+ export declare function unboundSuccess(method: string): PlimsollError;
53
72
  export declare function sessionEndFromWire(v: string | number | undefined): SessionEnd;
54
- export declare function errorFromWire(httpStatus: number, body: WireError | undefined): PlimsollError;
73
+ export declare function errorFromWire(httpStatus: number, body: WireError | undefined, answer: {
74
+ bound: boolean;
75
+ mark?: string | null;
76
+ }): PlimsollError;
package/dist/errors.js CHANGED
@@ -12,9 +12,10 @@ export class PlimsollError extends Error {
12
12
  /** Set when a session call was refused because its session had ended. */
13
13
  sessionEnded;
14
14
  /**
15
- * The result the daemon returned, on a "data_loss" error raised after it
16
- * answered: the record or the isolation evidence did not check, the run may
17
- * have executed, and this is what came back.
15
+ * The result the daemon returned, on an error raised after it answered, so the
16
+ * run may have executed: "data_loss" when the record or the isolation evidence
17
+ * did not check, and "unknown" from CodeSandboxes when a fresh run came back
18
+ * with no step report. This is what came back.
18
19
  */
19
20
  result;
20
21
  /**
@@ -28,6 +29,13 @@ export class PlimsollError extends Error {
28
29
  * UnansweredCallError.Record); undefined otherwise.
29
30
  */
30
31
  record;
32
+ /**
33
+ * True when the error comes from an answer that did not carry this request's
34
+ * Plimsoll-Request-Id back (Go: client.ErrAnswerNotBound): nothing it said about the
35
+ * call was believed, so it has no notDispatched, sessionEnded or unanswered. On a
36
+ * success the code is "data_loss": the call may have run.
37
+ */
38
+ answerNotBound;
31
39
  constructor(code, message, opts = {}) {
32
40
  super(message, opts.cause === undefined ? undefined : { cause: opts.cause });
33
41
  this.name = "PlimsollError";
@@ -36,8 +44,19 @@ export class PlimsollError extends Error {
36
44
  this.sessionEnded = opts.sessionEnded;
37
45
  this.result = opts.result;
38
46
  this.unanswered = opts.unanswered;
47
+ this.answerNotBound = opts.answerNotBound ?? false;
39
48
  }
40
49
  }
50
+ /** The request ID a client sends and the daemon echoes (Go: protocol.RequestIDHeader). */
51
+ export const REQUEST_ID_HEADER = "Plimsoll-Request-Id";
52
+ /** The daemon's mark on an answer written before any handler ran (Go: protocol.NotDispatchedHeader). */
53
+ export const NOT_DISPATCHED_HEADER = "Plimsoll-Not-Dispatched";
54
+ const NOT_BOUND = "the answer does not carry this request's Plimsoll-Request-Id back (a daemon older than protocol 3, or an intermediary " +
55
+ "that answered with another request's answer or dropped the header), so what it says about the call is ignored";
56
+ /** The error for a success answer that is not bound to its request: the call may have run. */
57
+ export function unboundSuccess(method) {
58
+ return new PlimsollError("data_loss", `plimsoll: ${method}: ${NOT_BOUND}; the call may have run`, { answerNotBound: true });
59
+ }
41
60
  const REFUSALS = ["unknown", "request", "permission", "protocol", "unsupported", "isolation", "capacity", "environment"];
42
61
  const SESSION_ENDS = [
43
62
  "open",
@@ -48,14 +67,23 @@ const SESSION_ENDS = [
48
67
  "boundary_failed",
49
68
  "sandbox_changed",
50
69
  "shutdown",
70
+ "replaced",
71
+ "not_found",
72
+ "unclaimed",
51
73
  ];
74
+ // Only an absent or unspecified end means open. Any other value says the session
75
+ // ended, so one this client has no name for is "unknown", never "open": read as open,
76
+ // an ended session would be reported as still holding its state and files. The
77
+ // refusal decode below keeps its mark the same way.
52
78
  export function sessionEndFromWire(v) {
53
- if (v === undefined)
79
+ if (v === undefined || v === 0)
54
80
  return "open";
55
81
  if (typeof v === "number")
56
- return SESSION_ENDS[v] ?? "open";
82
+ return SESSION_ENDS[v] ?? "unknown";
57
83
  const name = v.replace(/^SESSION_END_/, "").toLowerCase();
58
- return name === "unspecified" ? "open" : (SESSION_ENDS.includes(name) ? name : "open");
84
+ if (name === "unspecified")
85
+ return "open";
86
+ return name !== "open" && name !== "unknown" && SESSION_ENDS.includes(name) ? name : "unknown";
59
87
  }
60
88
  // Reads one varint at b[i]; returns [value, next index].
61
89
  function varint(b, i) {
@@ -178,10 +206,14 @@ const CODES = new Set([
178
206
  ]);
179
207
  // The body is whatever the daemon sent, so each field is used only in the shape Connect
180
208
  // gives it, and a code outside Connect's set is "unknown".
181
- export function errorFromWire(httpStatus, body) {
209
+ // An answer that is not bound to its request keeps only its code and message; a bound
210
+ // one without a NotDispatched detail is marked by the daemon's header (mark).
211
+ export function errorFromWire(httpStatus, body, answer) {
182
212
  const wire = body !== null && typeof body === "object" && !Array.isArray(body) ? body : undefined;
183
213
  const code = wire?.code === undefined ? httpStatusCode(httpStatus) : CODES.has(wire.code) ? wire.code : "unknown";
184
214
  const message = typeof wire?.message === "string" ? wire.message : `HTTP ${httpStatus}`;
215
+ if (!answer.bound)
216
+ return new PlimsollError(code, `${message} (${NOT_BOUND})`, { answerNotBound: true });
185
217
  let notDispatched;
186
218
  let sessionEnded;
187
219
  let unanswered;
@@ -192,8 +224,10 @@ export function errorFromWire(httpStatus, body) {
192
224
  notDispatched = REFUSALS[decodeDetail(bytes).reason] ?? "unknown";
193
225
  }
194
226
  else if (d.type === "plimsoll.v1.SessionEnded") {
227
+ // The detail itself says the session ended, so an unspecified reason is not "open".
195
228
  const m = decodeDetail(bytes);
196
- sessionEnded = { reason: sessionEndFromWire(m.reason), detail: m.detail };
229
+ const reason = sessionEndFromWire(m.reason);
230
+ sessionEnded = { reason: reason === "open" ? "unknown" : reason, detail: m.detail };
197
231
  }
198
232
  else if (d.type === "plimsoll.v1.UnansweredCall") {
199
233
  unanswered = decodeUnanswered(bytes);
@@ -203,6 +237,11 @@ export function errorFromWire(httpStatus, body) {
203
237
  // An undecodable detail states nothing; in particular not that nothing ran.
204
238
  }
205
239
  }
240
+ if (notDispatched === undefined && answer.mark) {
241
+ const named = REFUSALS.find((r) => r !== "unknown" && r === answer.mark);
242
+ if (named)
243
+ notDispatched = named;
244
+ }
206
245
  return new PlimsollError(code, message, { notDispatched, sessionEnded, unanswered: notDispatched ? undefined : unanswered });
207
246
  }
208
247
  // Connect's mapping for a response without a Connect error body.
package/dist/mastra.d.ts CHANGED
@@ -1,5 +1,16 @@
1
+ import { type ToolExecutionContext } from "@mastra/core/tools";
1
2
  import { CodeSandboxes, type CodeSandboxesOptions } from "./sandboxes.ts";
2
- export type PlimsollExecuteCodeOptions = CodeSandboxesOptions;
3
+ export type PlimsollExecuteCodeOptions = CodeSandboxesOptions & {
4
+ /**
5
+ * The user a call belongs to, from your app's own authentication (a value your server
6
+ * put in Mastra's requestContext, say). Default: the call's resourceId. Set it for an
7
+ * agent network: Mastra fills a missing resourceId with the network's name, so every
8
+ * user of the network would count as one owner under maxSessionsPerOwner and the
9
+ * daemon's SANDBOX_MAX_SESSIONS_PER_OWNER, and close each other's sandboxes. Pass the
10
+ * same owner to dispose.
11
+ */
12
+ owner?: (ctx: ToolExecutionContext) => string | undefined;
13
+ };
3
14
  export declare function plimsollExecuteCode(opts: PlimsollExecuteCodeOptions): {
4
15
  executeCode: import("@mastra/core/tools").Tool<{
5
16
  code: string;
@@ -21,8 +32,8 @@ export declare function plimsollExecuteCode(opts: PlimsollExecuteCodeOptions): {
21
32
  freshSandbox?: true | undefined;
22
33
  isolation: string;
23
34
  recordSha256: string;
24
- }, unknown, unknown, import("@mastra/core/tools").ToolExecutionContext<unknown, unknown, unknown>, "executeCode", unknown>;
25
- /** Closes a user's thread's sandbox, e.g. when the conversation ends. */
26
- dispose: (threadId: string, resourceId: string) => Promise<void>;
35
+ }, unknown, unknown, ToolExecutionContext<unknown, unknown, unknown>, "executeCode", unknown>;
36
+ /** Closes a user's thread's sandbox, e.g. when the conversation ends; owner is the one the option gave. */
37
+ dispose: (threadId: string, resourceId: string, owner?: string) => Promise<void>;
27
38
  sandboxes: CodeSandboxes;
28
39
  };
package/dist/mastra.js CHANGED
@@ -5,12 +5,17 @@
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, and a
9
- // call without either has no key and runs fresh. An empty resource would put every user
10
- // without one whose thread id collided into one sandbox, with each other's files and
11
- // variables. The pair is encoded as JSON, not joined with a separator: a resource ending
12
- // in the separator and a thread starting with it would name another user's key.
13
- const threadKey = (threadId, resourceId) => threadId && resourceId ? JSON.stringify([resourceId, threadId]) : undefined;
8
+ // A thread id is unique only within its resource (the user), so the key is both, the
9
+ // resource as the owner the per-user cap counts, and a call without either has no key
10
+ // and runs fresh. An empty resource would put every user without one whose thread id
11
+ // collided into one sandbox, with each other's files and variables. An owner of the
12
+ // app's own replaces the resource as what the caps count, and the conversation keeps
13
+ // both IDs, so the sandbox is still the resource's thread's.
14
+ const threadKey = (threadId, resourceId, owner) => !threadId || !resourceId
15
+ ? undefined
16
+ : owner === undefined
17
+ ? { owner: resourceId, conversation: threadId }
18
+ : { owner, conversation: JSON.stringify([resourceId, threadId]) };
14
19
  export function plimsollExecuteCode(opts) {
15
20
  const sandboxes = new CodeSandboxes(opts);
16
21
  const executeCode = createTool({
@@ -20,14 +25,15 @@ export function plimsollExecuteCode(opts) {
20
25
  outputSchema: executeCodeOutput,
21
26
  // The user's thread scopes the sandbox. A call outside a thread, or without a
22
27
  // resource, runs fresh: one sandbox shared across conversations would show one user
23
- // another's files.
24
- execute: async (input, ctx) => sandboxes.run(threadKey(ctx?.agent?.threadId, ctx?.agent?.resourceId), input, ctx?.abortSignal),
28
+ // another's files. The key is read inside run, so an owner resolver that throws is
29
+ // refused as nothing ran.
30
+ execute: async (input, ctx) => sandboxes.run(() => threadKey(ctx?.agent?.threadId, ctx?.agent?.resourceId, ctx && opts.owner ? opts.owner(ctx) : undefined), input, ctx?.abortSignal),
25
31
  });
26
32
  return {
27
33
  executeCode,
28
- /** Closes a user's thread's sandbox, e.g. when the conversation ends. */
29
- dispose: async (threadId, resourceId) => {
30
- const key = threadKey(threadId, resourceId);
34
+ /** Closes a user's thread's sandbox, e.g. when the conversation ends; owner is the one the option gave. */
35
+ dispose: async (threadId, resourceId, owner) => {
36
+ const key = threadKey(threadId, resourceId, owner);
31
37
  if (key !== undefined)
32
38
  await sandboxes.dispose(key);
33
39
  },
@@ -3,6 +3,18 @@ export type SessionMode = "auto" | "always" | "never";
3
3
  /** The languages a tool offers, the first being the default. */
4
4
  export type ToolLanguages = readonly [Language, ...Language[]];
5
5
  export declare const DEFAULT_LANGUAGES: ToolLanguages;
6
+ /**
7
+ * Which sandbox a call uses, from the application, never from a model's tool call. A
8
+ * conversation names its owner, the user it belongs to, whom maxSessionsPerOwner
9
+ * counts; a string (a Trigger.dev run id) names no owner and counts only against
10
+ * maxSessions.
11
+ */
12
+ export type SandboxKey = string | {
13
+ owner: string;
14
+ conversation: string;
15
+ };
16
+ /** @internal The first 12 hex digits of the key's SHA-256: names it in a log line without its IDs. */
17
+ export declare function keyDigest(key: SandboxKey): string;
6
18
  export type CodeSandboxesOptions = {
7
19
  /**
8
20
  * The daemon's client, or a function that builds it on first use: a
@@ -18,7 +30,11 @@ export type CodeSandboxesOptions = {
18
30
  sessions?: SessionMode;
19
31
  /** The languages the tool offers, the first being the default. Default python, then javascript. */
20
32
  languages?: ToolLanguages;
21
- /** The weakest tier a run accepts; checked before dispatch and on the answer. */
33
+ /**
34
+ * The weakest tier a run accepts; checked before dispatch and on the answer. Default
35
+ * kernel (a verified gVisor runtime), the weakest tier fit for hostile code; set
36
+ * "container" for local development against an ordinary docker daemon.
37
+ */
22
38
  minimumIsolation?: Exclude<Isolation, "none">;
23
39
  /** Per-call budget. */
24
40
  timeoutMs?: number;
@@ -31,16 +47,35 @@ export type CodeSandboxesOptions = {
31
47
  * session's lifetime ends. Default 10 minutes; 0 never.
32
48
  */
33
49
  idleCloseMs?: number;
50
+ /**
51
+ * Sandboxes one owner may hold in this instance. Default 3: a person rarely works in
52
+ * more than a few conversations at once, and the conversation whose sandbox is closed
53
+ * loses its variables and files, never an answer (its next call says freshSandbox).
54
+ * 0 = no cap. It counts this instance only; for an app running as many processes
55
+ * (serverless functions, Trigger.dev workers), set the daemon's
56
+ * SANDBOX_MAX_SESSIONS_PER_OWNER, which counts them all.
57
+ */
58
+ maxSessionsPerOwner?: number;
59
+ /**
60
+ * Sandboxes this instance holds across owners, closed the same way: the share of
61
+ * the daemon's SANDBOX_MAX_SESSIONS this app may take, which only the operator knows.
62
+ * Default 0, no cap of its own. A daemon at its cap refuses the open (not dispatched,
63
+ * reason capacity); closing an idle sandbox then is not done for you, because the
64
+ * daemon gives the same refusal for its rate limit, which a close does not help.
65
+ */
66
+ maxSessions?: number;
34
67
  /** Characters of stdout and of stderr returned to the model; the rest is cut and marked. */
35
68
  maxOutputChars?: number;
36
69
  /**
37
70
  * Called when closing a sandbox fails. A "data_loss" error here means the
38
71
  * daemon counted calls this client has no answer for: a call that ended
39
72
  * 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.
73
+ * or, if none did, someone else holding the session ID. Default: console.warn, naming
74
+ * the key only by a digest, since a key can hold a user's ID. The error never
75
+ * contains the session ID. A callback that throws, or returns a promise that
76
+ * rejects, is logged the same way; it never stops a close or the next open.
42
77
  */
43
- onCloseError?: (key: string, err: unknown) => void;
78
+ onCloseError?: (key: SandboxKey, err: unknown) => void;
44
79
  };
45
80
  /** What the executeCode tool takes. */
46
81
  export type ExecuteCodeInput = {
@@ -114,13 +149,29 @@ export declare class CodeSandboxes {
114
149
  persistent(): Promise<boolean>;
115
150
  /**
116
151
  * Starts creating the key's sandbox and returns at once. A failure here is
117
- * not lost: the next run under the key opens a session again.
152
+ * not lost: the next run under the key opens a session again. A warm is a guess
153
+ * (a new chat the user may never type in), so it never closes another sandbox to
154
+ * make room: with the key's owner, or this instance, at its cap it does nothing,
155
+ * and the key's first call opens the sandbox, closing the least recently used idle
156
+ * one then. On a daemon with SANDBOX_MAX_SESSIONS_PER_OWNER a warm that opens is an
157
+ * open like any other: the daemon counts it, and at its cap closes that user's least
158
+ * recently used session there.
159
+ */
160
+ warm(key: SandboxKey): void;
161
+ /**
162
+ * Runs one call of the tool under the key, or under the key a function returns (an
163
+ * add-on reading it from its framework's context, so a failure to find it is this
164
+ * call's refusal). Every error it throws is a PlimsollError whose message starts with
165
+ * whether the code ran: "Nothing ran (<reason>): " when it carries a not-dispatched
166
+ * mark, "The code may have run, and there is no checked answer for it: " otherwise. A
167
+ * failure before the code was sent (the key, the client, the Describe, the sandbox's
168
+ * open) is marked, reason environment unless the daemon gave one. A framework hands
169
+ * its model only the message (Mastra's error-text, the AI SDK's tool error), and that
170
+ * is the one thing the model must not guess.
118
171
  */
119
- warm(key: string): void;
120
- /** Runs one call of the tool under the key. */
121
- run(key: string | undefined, input: ExecuteCodeInput, signal?: AbortSignal): Promise<ExecuteCodeOutput>;
172
+ run(key: SandboxKey | undefined | (() => SandboxKey | undefined), input: ExecuteCodeInput, signal?: AbortSignal): Promise<ExecuteCodeOutput>;
122
173
  /** Closes the key's sandbox, if it has one. Safe to call more than once. */
123
- dispose(key: string): Promise<void>;
174
+ dispose(key: SandboxKey): Promise<void>;
124
175
  /** Closes every sandbox this instance holds, for shutdown. */
125
176
  disposeAll(): Promise<void>;
126
177
  }