@nylorun/agents 0.19.0-beta → 0.20.0-beta

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.
@@ -3,10 +3,10 @@
3
3
  * which resolves the connection from the environment or the Project link.
4
4
  */
5
5
  import type { AgentManifest, BuiltAgent, BuiltWorkflow, JsonValue, SandboxToolName, WorkflowManifest } from "@nylorun/core/define";
6
- import { type SessionItemsResponse, type SessionSummary, type ListAgentsResponse, type ListPublicAgentsResponse, type SubjectScope, type CredentialSelection, type MessagePart, type SandboxRequest, type SessionCommand } from "@nylorun/core/contracts";
6
+ import { type SessionItemsResponse, type SessionSummary, type ListAgentsResponse, type ListPublicAgentsResponse, type SubjectScope, type MessagePart, type SessionCommand } from "@nylorun/core/contracts";
7
7
  import { SessionsReadClient } from "./reads.js";
8
8
  import { AccessClient } from "./access.js";
9
- import { SandboxesClient } from "./sandboxes.js";
9
+ import { EnvironmentsClient } from "./environments.js";
10
10
  import { ArtifactsClient } from "./artifacts.js";
11
11
  import { FilesClient } from "./files.js";
12
12
  import { Transport, type Destination } from "./http.js";
@@ -38,16 +38,12 @@ export interface CreateSessionOptions {
38
38
  ownerUserId: string;
39
39
  info?: Record<string, unknown>;
40
40
  requestId?: string;
41
- vaultIds?: readonly string[];
42
- credentialSelections?: readonly CredentialSelection[];
43
41
  /**
44
- * The session's sandbox: omit for the Tenant default, `false` for none, `{ id }` to attach a
45
- * sandbox resource (`client.sandboxes`, Host feature `sandboxes`), or an inline sandbox
46
- * (`image`, `network.allow`, `resources`) checked against the Tenant's limits. `{ session }`
47
- * shares another session's and is deprecated: use `client.sandboxes.forSession()` or
48
- * `ensure()` and `{ id }`. Fixed once the session exists.
42
+ * The Environment the session runs in (`client.environments`): its sandbox, and its vault's
43
+ * credentials for the session's shell, MCP servers and HTTP tools. Omit for no sandbox and no
44
+ * credentials. Fixed once the session exists.
49
45
  */
50
- sandbox?: SandboxRequest;
46
+ environment?: string;
51
47
  }
52
48
  export interface ActAsOptions {
53
49
  /** What the subject may do; the Runtime grants nothing else. Default `["sessions:own"]`. */
@@ -61,17 +57,18 @@ export declare class AgentsClient {
61
57
  /**
62
58
  * A client that acts for `subject`: every call sends `Nylorun-Subject` and
63
59
  * `Nylorun-Scopes`, and the Runtime limits it to the scopes and to the subject's own sessions
64
- * and vaults (Host feature `subject-headers`). For app servers, which authenticate the person
60
+ * (Host feature `subject-headers`). For app servers, which authenticate the person
65
61
  * themselves and hold the key; nothing is minted, cached or refreshed.
66
62
  */
67
63
  as(subject: string, options?: ActAsOptions): AgentsClient;
68
64
  /** The public keys that verify the tokens the Tenant signs. */
69
65
  get access(): AccessClient;
70
66
  /**
71
- * Sandboxes as a resource (Host feature `sandboxes`): `ensure` one by id, `list` them by
72
- * label, `delete` one, or give a session its own with `forSession`.
67
+ * Environments (protocol 11): `put` one by id (create, find or change), write its `secrets`,
68
+ * `list` them by label, `stop`, `reset` or `delete` one, or give a session its own with
69
+ * `forSession`.
73
70
  */
74
- get sandboxes(): SandboxesClient;
71
+ get environments(): EnvironmentsClient;
75
72
  /** File artifacts: upload, list, download with Range, capability links (protocol 6). */
76
73
  get artifacts(): ArtifactsClient;
77
74
  /** Definition files: the skill files a definition names, by content hash. */
@@ -98,7 +95,7 @@ export declare class AgentsClient {
98
95
  * Registers the agent's definition (`PUT /v1/agents/{id}`), first uploading the skill files
99
96
  * it names that the Runtime does not hold. A definition with a tool that runs your code
100
97
  * (`tool({ run })`, a flow's tool stage) is refused before anything is sent: the Runtime runs
101
- * no code of yours during a session. `implementationVersion` defaults to
98
+ * agents from their manifests alone. `implementationVersion` defaults to
102
99
  * `NYLORUN_IMPLEMENTATION_VERSION`, else `dev`.
103
100
  */
104
101
  saveAgent(agent: AgentSource | BuiltWorkflow, options?: {
@@ -206,6 +203,7 @@ export declare class SessionClient {
206
203
  }): Promise<{
207
204
  calls: {
208
205
  id: string;
206
+ effectId: string;
209
207
  sessionId: string;
210
208
  turnId: string;
211
209
  agentId: string;
@@ -229,6 +227,87 @@ export declare class SessionClient {
229
227
  nextCursor: string | null;
230
228
  asOf: string;
231
229
  }>;
230
+ /**
231
+ * The session's tool calls (R5, Host feature `tool-calls`), in the order they were first sent:
232
+ * each one's tool, input, status and sends. `attempts` above 1: a crash re-sent it.
233
+ */
234
+ toolCalls(options?: {
235
+ turnId?: string;
236
+ limit?: number;
237
+ cursor?: string;
238
+ signal?: AbortSignal;
239
+ }): Promise<{
240
+ calls: {
241
+ effectId: string;
242
+ turnId: string;
243
+ callId: string | null;
244
+ capabilityId: string | null;
245
+ toolName: string | null;
246
+ kind: "http" | "mcp" | "platform" | "sandbox" | null;
247
+ server: string | null;
248
+ status: "cancelled" | "completed" | "failed" | "held" | "invoking" | "uncertain";
249
+ attempts: number;
250
+ input: unknown;
251
+ error: {
252
+ code: string;
253
+ message: string;
254
+ } | null;
255
+ startedAt: string | null;
256
+ settledAt: string | null;
257
+ durationMs: number | null;
258
+ }[];
259
+ nextCursor: string | null;
260
+ asOf: string;
261
+ }>;
262
+ /**
263
+ * A turn's trace (R7, Host feature `traces`): its spans as OTLP/HTTP JSON (`resourceSpans`), as
264
+ * the Runtime posts them to an OTLP collector. Post it to a collector's `/v1/traces` to backfill
265
+ * one, or read it without one.
266
+ */
267
+ trace(turnId: string, options?: {
268
+ signal?: AbortSignal;
269
+ }): Promise<{
270
+ [x: string]: unknown;
271
+ resourceSpans: {
272
+ [x: string]: unknown;
273
+ resource: {
274
+ [x: string]: unknown;
275
+ attributes: {
276
+ [x: string]: unknown;
277
+ key: string;
278
+ value: Record<string, unknown>;
279
+ }[];
280
+ };
281
+ scopeSpans: {
282
+ [x: string]: unknown;
283
+ scope: {
284
+ [x: string]: unknown;
285
+ name: string;
286
+ version?: string | undefined;
287
+ };
288
+ spans: {
289
+ [x: string]: unknown;
290
+ traceId: string;
291
+ spanId: string;
292
+ parentSpanId?: string | undefined;
293
+ name: string;
294
+ kind: number;
295
+ startTimeUnixNano: string;
296
+ endTimeUnixNano: string;
297
+ attributes: {
298
+ [x: string]: unknown;
299
+ key: string;
300
+ value: Record<string, unknown>;
301
+ }[];
302
+ status: {
303
+ [x: string]: unknown;
304
+ code: number;
305
+ message?: string | undefined;
306
+ };
307
+ }[];
308
+ }[];
309
+ }[];
310
+ }>;
232
311
  /** `agent` narrows to one agent used as a tool: its delegationId or its path. */
233
312
  history(options: {
234
313
  cursor?: string;
@@ -261,10 +340,14 @@ export declare class SessionClient {
261
340
  time: string;
262
341
  schemaVersion: number;
263
342
  source: {
264
- kind: "api" | "controller" | "edge" | "egress-gate" | "evidence" | "harness" | "human" | "init" | "loop" | "model-gate" | "operator" | "sandboxes" | "supervisor" | "tool-gate";
343
+ kind: "api" | "client" | "controller" | "core" | "edge" | "egress-gate" | "evidence" | "harness" | "human" | "init" | "loop" | "model-gate" | "operator" | "sandboxes" | "supervisor" | "tool-gate";
265
344
  id: string;
266
345
  };
267
346
  evidence: "asserted" | "attested" | "claimed" | "measured" | "observed";
347
+ principal?: {
348
+ kind: "application" | "core" | "flow-host" | "subject";
349
+ id: string;
350
+ } | undefined;
268
351
  trace?: {
269
352
  traceId: string;
270
353
  spanId: string;
@@ -286,5 +369,5 @@ export { RuntimeError, IncompatibleRuntimeError } from "./http.js";
286
369
  export type { Destination, IncompatibleReason } from "./http.js";
287
370
  export type { LiveEvent } from "@nylorun/core/contracts";
288
371
  export { AccessClient } from "./access.js";
289
- export { SandboxesClient } from "./sandboxes.js";
290
- export type { ForSessionOptions, SandboxSpec, SessionSandboxHandle } from "./sandboxes.js";
372
+ export { EnvironmentSecretsClient, EnvironmentsClient } from "./environments.js";
373
+ export type { EnvironmentRecipeInput, EnvironmentSecretInput, ForSessionOptions, SessionEnvironmentHandle, } from "./environments.js";
@@ -1,10 +1,10 @@
1
- import { SANDBOX_TOOL_NAMES, codeToolRefusal, delegateOf, isBuiltWorkflow, isSandboxToolName, } from "@nylorun/core/define";
1
+ import { SANDBOX_TOOL_NAMES, approvalRefusal, codeToolRefusal, delegateOf, isBuiltWorkflow, isSandboxToolName, } from "@nylorun/core/define";
2
2
  import { z } from "zod";
3
3
  import { SCOPES_HEADER, SUBJECT_HEADER } from "@nylorun/core/compatibility";
4
- import { SessionManifestViewSchema, SessionUsageTotalsSchema, ModelCallsPageSchema, parseSessionEvent, parseSubjectHeaders, } from "@nylorun/core/contracts";
4
+ import { SessionManifestViewSchema, SessionUsageTotalsSchema, ModelCallsPageSchema, ToolCallsPageSchema, TurnTraceSchema, parseSessionEvent, parseSubjectHeaders, } from "@nylorun/core/contracts";
5
5
  import { SessionsReadClient } from "./reads.js";
6
6
  import { AccessClient } from "./access.js";
7
- import { SandboxesClient } from "./sandboxes.js";
7
+ import { EnvironmentsClient } from "./environments.js";
8
8
  import { ArtifactsClient } from "./artifacts.js";
9
9
  import { FilesClient } from "./files.js";
10
10
  import { Transport, env, id, segment } from "./http.js";
@@ -74,7 +74,7 @@ export class AgentsClient {
74
74
  /**
75
75
  * A client that acts for `subject`: every call sends `Nylorun-Subject` and
76
76
  * `Nylorun-Scopes`, and the Runtime limits it to the scopes and to the subject's own sessions
77
- * and vaults (Host feature `subject-headers`). For app servers, which authenticate the person
77
+ * (Host feature `subject-headers`). For app servers, which authenticate the person
78
78
  * themselves and hold the key; nothing is minted, cached or refreshed.
79
79
  */
80
80
  as(subject, options = {}) {
@@ -98,11 +98,12 @@ export class AgentsClient {
98
98
  return new AccessClient(this.transport);
99
99
  }
100
100
  /**
101
- * Sandboxes as a resource (Host feature `sandboxes`): `ensure` one by id, `list` them by
102
- * label, `delete` one, or give a session its own with `forSession`.
101
+ * Environments (protocol 11): `put` one by id (create, find or change), write its `secrets`,
102
+ * `list` them by label, `stop`, `reset` or `delete` one, or give a session its own with
103
+ * `forSession`.
103
104
  */
104
- get sandboxes() {
105
- return new SandboxesClient(this.transport, (options) => this.createSession(options));
105
+ get environments() {
106
+ return new EnvironmentsClient(this.transport, (options) => this.createSession(options));
106
107
  }
107
108
  /** File artifacts: upload, list, download with Range, capability links (protocol 6). */
108
109
  get artifacts() {
@@ -132,7 +133,7 @@ export class AgentsClient {
132
133
  * Registers the agent's definition (`PUT /v1/agents/{id}`), first uploading the skill files
133
134
  * it names that the Runtime does not hold. A definition with a tool that runs your code
134
135
  * (`tool({ run })`, a flow's tool stage) is refused before anything is sent: the Runtime runs
135
- * no code of yours during a session. `implementationVersion` defaults to
136
+ * agents from their manifests alone. `implementationVersion` defaults to
136
137
  * `NYLORUN_IMPLEMENTATION_VERSION`, else `dev`.
137
138
  */
138
139
  async saveAgent(agent, options = {}) {
@@ -149,7 +150,8 @@ export class AgentsClient {
149
150
  assertNoMiddlewareClosures(agent);
150
151
  skillFilesOf(agent, files);
151
152
  }
152
- const refusal = codeToolRefusal(agent.manifest);
153
+ const refusal = codeToolRefusal(agent.manifest) ??
154
+ approvalRefusal(agent.manifest);
153
155
  if (refusal)
154
156
  throw new Error(refusal);
155
157
  await this.files.ensure(files);
@@ -166,11 +168,7 @@ export class AgentsClient {
166
168
  agentId: options.agentId,
167
169
  ownerUserId: options.ownerUserId,
168
170
  ...(options.info ? { info: options.info } : {}),
169
- ...(options.vaultIds ? { vaultIds: options.vaultIds } : {}),
170
- ...(options.credentialSelections
171
- ? { credentialSelections: options.credentialSelections }
172
- : {}),
173
- ...(options.sandbox === undefined ? {} : { sandbox: options.sandbox }),
171
+ ...(options.environment === undefined ? {} : { environment: options.environment }),
174
172
  });
175
173
  return this.session(sessionId);
176
174
  }
@@ -274,6 +272,28 @@ export class SessionClient {
274
272
  query.set("cursor", options.cursor);
275
273
  return ModelCallsPageSchema.parse(await this.transport.json(`${this.path}/calls/model?${query}`, "GET", undefined, options.signal));
276
274
  }
275
+ /**
276
+ * The session's tool calls (R5, Host feature `tool-calls`), in the order they were first sent:
277
+ * each one's tool, input, status and sends. `attempts` above 1: a crash re-sent it.
278
+ */
279
+ async toolCalls(options = {}) {
280
+ await this.transport.requireFeature("tool-calls", options.signal);
281
+ const query = new URLSearchParams({ limit: String(options.limit ?? 50) });
282
+ if (options.turnId !== undefined)
283
+ query.set("turnId", options.turnId);
284
+ if (options.cursor !== undefined)
285
+ query.set("cursor", options.cursor);
286
+ return ToolCallsPageSchema.parse(await this.transport.json(`${this.path}/calls/tool?${query}`, "GET", undefined, options.signal));
287
+ }
288
+ /**
289
+ * A turn's trace (R7, Host feature `traces`): its spans as OTLP/HTTP JSON (`resourceSpans`), as
290
+ * the Runtime posts them to an OTLP collector. Post it to a collector's `/v1/traces` to backfill
291
+ * one, or read it without one.
292
+ */
293
+ async trace(turnId, options = {}) {
294
+ await this.transport.requireFeature("traces", options.signal);
295
+ return TurnTraceSchema.parse(await this.transport.json(`${this.path}/turns/${encodeURIComponent(turnId)}/trace`, "GET", undefined, options.signal));
296
+ }
277
297
  async history(options = {}) {
278
298
  const query = new URLSearchParams();
279
299
  if (options.cursor)
@@ -372,4 +392,4 @@ export class SessionClient {
372
392
  }
373
393
  export { RuntimeError, IncompatibleRuntimeError } from "./http.js";
374
394
  export { AccessClient } from "./access.js";
375
- export { SandboxesClient } from "./sandboxes.js";
395
+ export { EnvironmentSecretsClient, EnvironmentsClient } from "./environments.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nylorun/agents",
3
- "version": "0.19.0-beta",
3
+ "version": "0.20.0-beta",
4
4
  "description": "Nylorun agent definitions and session client",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -43,14 +43,14 @@
43
43
  "test": "vitest run --passWithNoTests"
44
44
  },
45
45
  "dependencies": {
46
- "@nylorun/core": "0.18.0-beta",
46
+ "@nylorun/core": "0.20.0-beta",
47
47
  "gray-matter": "^4.0.3"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "zod": "^4.6.5"
51
51
  },
52
52
  "devDependencies": {
53
- "@types/node": "^24.0.0",
53
+ "@types/node": "^26.6.4",
54
54
  "typescript": "npm:@typescript/typescript6@^6.0.2",
55
55
  "vitest": "^5.0.2"
56
56
  },
@@ -60,7 +60,7 @@
60
60
  "repository": {
61
61
  "type": "git",
62
62
  "url": "git+https://github.com/nylorun/agents.git",
63
- "directory": "agents"
63
+ "directory": "sdks/agents"
64
64
  },
65
65
  "publishConfig": {
66
66
  "access": "public",
@@ -1,106 +0,0 @@
1
- /**
2
- * Sandboxes as a resource (Host feature `sandboxes`): `client.sandboxes`. A sandbox has its own
3
- * id and outlives the sessions attached to it; whether it serves one session, one person or a
4
- * project is the app's choice, made here:
5
- *
6
- * - `sandboxes.forSession(...)`: one sandbox for one session. It creates the sandbox, opens the
7
- * session attached to it, and `release()` deletes the sandbox when the session is done. It
8
- * replaces sharing through another session (`sandbox: { session }`, `sandboxOwnerId`).
9
- * - `sandboxes.ensure(id, spec)`: one sandbox per person or per project, by a deterministic id
10
- * (`user-42`, `team-a/proj-42`); get-or-create in one call. Attach sessions to it with
11
- * `createSession({ sandbox: { id } })`.
12
- *
13
- * Ids may hold `/`; they are sent percent-encoded as one path segment.
14
- */
15
- import { type DeleteSandboxResponse, type PutSandboxRequest, type SandboxEvent, type SandboxView } from "@nylorun/core/contracts";
16
- import { type Transport } from "./http.js";
17
- import type { CreateSessionOptions, SessionClient } from "./session-client.js";
18
- /** What a sandbox is made of: fixed once it exists, except its labels. */
19
- export type SandboxSpec = Omit<PutSandboxRequest, "requestId">;
20
- /** A session opened on a sandbox of its own (`sandboxes.forSession`). */
21
- export interface SessionSandboxHandle {
22
- readonly session: SessionClient;
23
- readonly sandbox: SandboxView;
24
- /** Deletes the sandbox and its files; call it when the session is done. */
25
- release(options?: {
26
- signal?: AbortSignal;
27
- }): Promise<DeleteSandboxResponse>;
28
- }
29
- export interface ForSessionOptions {
30
- /** The session to open, as `createSession` takes it, without `sandbox`. */
31
- readonly session: Omit<CreateSessionOptions, "sandbox">;
32
- /** The sandbox's spec and labels. Default: a virtual sandbox within the Tenant's defaults. */
33
- readonly spec?: SandboxSpec;
34
- /** The sandbox's id. Default: `sessions/<session id>`. */
35
- readonly sandboxId?: string;
36
- readonly signal?: AbortSignal;
37
- }
38
- export declare class SandboxesClient {
39
- private readonly transport;
40
- /** `AgentsClient.createSession`, bound. */
41
- private readonly createSession;
42
- constructor(transport: Transport,
43
- /** `AgentsClient.createSession`, bound. */
44
- createSession: (options: CreateSessionOptions) => Promise<SessionClient>);
45
- private path;
46
- /**
47
- * Creates the sandbox, or finds the one with this id (`PUT /v1/sandboxes/{id}`). Its spec is
48
- * fixed once it exists: a different one is a 409. Labels, when given, replace its labels.
49
- */
50
- ensure(sandboxId: string, spec?: SandboxSpec, options?: {
51
- signal?: AbortSignal;
52
- }): Promise<SandboxView>;
53
- get(sandboxId: string, options?: {
54
- signal?: AbortSignal;
55
- }): Promise<SandboxView>;
56
- /** The sandboxes with every label in `labels` that this client reaches. */
57
- list(options?: {
58
- labels?: Readonly<Record<string, string>>;
59
- signal?: AbortSignal;
60
- }): Promise<SandboxView[]>;
61
- page(options?: {
62
- labels?: Readonly<Record<string, string>>;
63
- limit?: number;
64
- cursor?: string;
65
- signal?: AbortSignal;
66
- }): Promise<{
67
- sandboxes: {
68
- id: string;
69
- kind: "pod" | "virtual";
70
- labels: Record<string, string>;
71
- spec: Record<string, unknown>;
72
- state: "creating" | "ready" | "running" | "stopped";
73
- pod?: {
74
- desired: "deleted" | "running" | "suspended";
75
- observed: "creating" | "deleting" | "expired" | "failed" | "lost" | "running" | "suspended";
76
- volumeGeneration: number;
77
- hostEpoch: number;
78
- expiresAt?: string | undefined;
79
- reason?: string | undefined;
80
- } | undefined;
81
- sessions: {
82
- id: string;
83
- activeTurnId: string | null;
84
- }[];
85
- createdAt: string;
86
- updatedAt: string;
87
- }[];
88
- nextCursor: string | null;
89
- }>;
90
- /** Deletes the sandbox and its files; `deleted` is false when there was none. */
91
- delete(sandboxId: string, options?: {
92
- signal?: AbortSignal;
93
- }): Promise<DeleteSandboxResponse>;
94
- /** The sandbox's lifecycle events, from `from` on. */
95
- events(sandboxId: string, options?: {
96
- from?: number;
97
- signal?: AbortSignal;
98
- }): Promise<SandboxEvent[]>;
99
- /**
100
- * One sandbox for one session: creates the sandbox (`sessions/<session id>` unless
101
- * `sandboxId` names another), opens the session attached to it, and returns both with
102
- * `release()`, which deletes the sandbox. If the session cannot be opened, the sandbox is
103
- * deleted again.
104
- */
105
- forSession(options: ForSessionOptions): Promise<SessionSandboxHandle>;
106
- }
package/dist/sandboxes.js DELETED
@@ -1,109 +0,0 @@
1
- /**
2
- * Sandboxes as a resource (Host feature `sandboxes`): `client.sandboxes`. A sandbox has its own
3
- * id and outlives the sessions attached to it; whether it serves one session, one person or a
4
- * project is the app's choice, made here:
5
- *
6
- * - `sandboxes.forSession(...)`: one sandbox for one session. It creates the sandbox, opens the
7
- * session attached to it, and `release()` deletes the sandbox when the session is done. It
8
- * replaces sharing through another session (`sandbox: { session }`, `sandboxOwnerId`).
9
- * - `sandboxes.ensure(id, spec)`: one sandbox per person or per project, by a deterministic id
10
- * (`user-42`, `team-a/proj-42`); get-or-create in one call. Attach sessions to it with
11
- * `createSession({ sandbox: { id } })`.
12
- *
13
- * Ids may hold `/`; they are sent percent-encoded as one path segment.
14
- */
15
- import { SandboxPageSchema, isSandboxId, } from "@nylorun/core/contracts";
16
- import { id, segment } from "./http.js";
17
- const FEATURE = "sandboxes";
18
- export class SandboxesClient {
19
- transport;
20
- createSession;
21
- constructor(transport,
22
- /** `AgentsClient.createSession`, bound. */
23
- createSession) {
24
- this.transport = transport;
25
- this.createSession = createSession;
26
- }
27
- path(sandboxId) {
28
- if (!isSandboxId(sandboxId))
29
- throw new TypeError(`${sandboxId} is not a sandbox id: up to 200 characters, /-separated segments of letters, digits, '.', '_' and '-'`);
30
- return `/v1/sandboxes/${segment(sandboxId)}`;
31
- }
32
- /**
33
- * Creates the sandbox, or finds the one with this id (`PUT /v1/sandboxes/{id}`). Its spec is
34
- * fixed once it exists: a different one is a 409. Labels, when given, replace its labels.
35
- */
36
- async ensure(sandboxId, spec = {}, options = {}) {
37
- const path = this.path(sandboxId);
38
- await this.transport.requireFeature(FEATURE, options.signal);
39
- return this.transport.json(path, "PUT", { requestId: id(), ...spec }, options.signal);
40
- }
41
- async get(sandboxId, options = {}) {
42
- const path = this.path(sandboxId);
43
- await this.transport.requireFeature(FEATURE, options.signal);
44
- return this.transport.json(path, "GET", undefined, options.signal);
45
- }
46
- /** The sandboxes with every label in `labels` that this client reaches. */
47
- async list(options = {}) {
48
- await this.transport.requireFeature(FEATURE, options.signal);
49
- const query = new URLSearchParams();
50
- for (const [key, value] of Object.entries(options.labels ?? {}))
51
- query.append("label", `${key}=${value}`);
52
- const search = query.toString();
53
- const reply = await this.transport.json(`/v1/sandboxes${search ? `?${search}` : ""}`, "GET", undefined, options.signal);
54
- return reply.sandboxes;
55
- }
56
- async page(options = {}) {
57
- await this.transport.requireFeature("session-reads", options.signal);
58
- const query = new URLSearchParams({ limit: String(options.limit ?? 50) });
59
- if (options.cursor !== undefined)
60
- query.set("cursor", options.cursor);
61
- for (const [key, value] of Object.entries(options.labels ?? {}))
62
- query.append("label", `${key}=${value}`);
63
- return SandboxPageSchema.parse(await this.transport.json(`/v1/sandboxes?${query}`, "GET", undefined, options.signal));
64
- }
65
- /** Deletes the sandbox and its files; `deleted` is false when there was none. */
66
- async delete(sandboxId, options = {}) {
67
- const path = this.path(sandboxId);
68
- await this.transport.requireFeature(FEATURE, options.signal);
69
- return this.transport.json(path, "DELETE", undefined, options.signal);
70
- }
71
- /** The sandbox's lifecycle events, from `from` on. */
72
- async events(sandboxId, options = {}) {
73
- const path = this.path(sandboxId);
74
- await this.transport.requireFeature(FEATURE, options.signal);
75
- const reply = await this.transport.json(`${path}/events${options.from === undefined ? "" : `?from=${options.from}`}`, "GET", undefined, options.signal);
76
- return reply.events;
77
- }
78
- /**
79
- * One sandbox for one session: creates the sandbox (`sessions/<session id>` unless
80
- * `sandboxId` names another), opens the session attached to it, and returns both with
81
- * `release()`, which deletes the sandbox. If the session cannot be opened, the sandbox is
82
- * deleted again.
83
- */
84
- async forSession(options) {
85
- const sessionId = options.session.id ?? id();
86
- const sandboxId = options.sandboxId ??
87
- (isSandboxId(`sessions/${sessionId}`) ? `sessions/${sessionId}` : `sessions/${id()}`);
88
- const sandbox = await this.ensure(sandboxId, options.spec ?? {}, {
89
- ...(options.signal ? { signal: options.signal } : {}),
90
- });
91
- let session;
92
- try {
93
- session = await this.createSession({
94
- ...options.session,
95
- id: sessionId,
96
- sandbox: { id: sandboxId },
97
- });
98
- }
99
- catch (error) {
100
- await this.delete(sandboxId).catch(() => undefined);
101
- throw error;
102
- }
103
- return {
104
- session,
105
- sandbox,
106
- release: (release = {}) => this.delete(sandboxId, release),
107
- };
108
- }
109
- }