agental-sdk 0.9.0 → 0.10.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 CHANGED
@@ -95,13 +95,22 @@ await sandbox.schedules.update(tick.id, { enabled: false }); // paused
95
95
 
96
96
  ## Files
97
97
 
98
- Paths are relative to the work folder, `/opt/agental`. A file can be up to 10 MB.
98
+ A path is relative to the work folder, `/opt/agental`, or absolute: anywhere on the machine, as root sees it. A file can be up to 10 MB.
99
99
 
100
100
  ```ts
101
101
  await sandbox.files.write("notes.txt", "hi");
102
102
  await sandbox.files.read("notes.txt"); // "hi"
103
103
  await sandbox.files.write("logo.png", bytes); // a Uint8Array
104
104
  await sandbox.files.readBytes("logo.png");
105
+ await sandbox.files.read("/etc/hostname");
106
+
107
+ const file = await sandbox.files.get("notes.txt"); // { path, bytes, modifiedAt, text }
108
+ await sandbox.files.write("notes.txt", "ho", { ifModifiedAt: file.modifiedAt }); // file_changed if it was changed since
109
+
110
+ await sandbox.files.list("/var/log"); // { path, entries: [{ name, kind, bytes, modifiedAt }], truncated }
111
+ await sandbox.files.makeFolder("out/today");
112
+ await sandbox.files.move("notes.txt", "out/today/notes.txt"); // file_exists if something is there
113
+ await sandbox.files.delete("out", { recursive: true });
105
114
  ```
106
115
 
107
116
  ## Stop, start, fork, snapshot
@@ -188,7 +197,23 @@ for await (const chunk of terminal) process.stdout.write(chunk); // Uint8Array,
188
197
  const { exitCode, closeCode } = await terminal.exited; // 3, 1000
189
198
  ```
190
199
 
191
- It needs a key with the `exec` action, and the sandbox running. It is opened with the runtime's own `WebSocket` (Node 22 and later, browsers, Deno, Bun); in Node 20 pass `new Agental({ WebSocket })` from the `ws` package. The API closes it when the shell ends (`closeCode` 1000, with `exitCode`), when the key or the sandbox no longer lets it be open (4003), after 30 minutes with nothing typed (4008), and when its sandbox stops answering (4011); `error` says why when the API did. `close()`, or leaving the `for await`, hangs the shell up, as an SSH session's end does: start what must outlive it with `nohup` or `setsid`. The command's `agental shell <sandbox-id>` opens one in your own terminal.
200
+ It needs a key with the `exec` action, and the sandbox running. It is opened with the runtime's own `WebSocket` (Node 22 and later, browsers, Deno, Bun); in Node 20 pass `new Agental({ WebSocket })` from the `ws` package. The API closes it when the shell ends (`closeCode` 1000, with `exitCode`), when the key or the sandbox no longer lets it be open (4003), after 30 minutes with nothing typed (4008), and when its sandbox stops answering (4011); `error` says why when the API did. `close()`, or leaving the `for await`, hangs the shell up, as an SSH session's end does, unless the shell is kept. The command's `agental shell <sandbox-id>` opens one in your own terminal.
201
+
202
+ A kept shell runs on when its terminal closes, until it exits, is closed, or the sandbox stops, and is opened again by its id, with the last 256 KiB it printed first:
203
+
204
+ ```ts
205
+ const first = await sandbox.terminal({ keep: true });
206
+ first.write("npm run dev\n");
207
+ await first.whenStarted();
208
+ const { id, n } = first.kept!; // "pty_…", 1; null on a sandbox whose agent is from before kept shells
209
+ first.close(); // npm run dev runs on
210
+
211
+ await sandbox.terminals(); // [{ id, n, running: "npm run dev", cwd: "/root/app", attached: false, exit: null, … }]
212
+ const again = await sandbox.terminal({ attach: id });
213
+ await sandbox.closeTerminal(id); // ends it: what runs in it is sent SIGHUP
214
+ ```
215
+
216
+ Opening a kept shell again closes the terminal that had it with 4009 (`TERMINAL_CLOSE.elsewhere`): it runs on in the new one.
192
217
 
193
218
  ## Desktop
194
219
 
package/dist/index.d.ts CHANGED
@@ -4,9 +4,9 @@ export type { BurstRefusalCode } from "./errors.js";
4
4
  export type { AgentalOptions } from "./http.js";
5
5
  export { Browser, Commands, Desktop, Email, Files, Sandbox, Schedules, Ssh } from "./sandbox.js";
6
6
  export { Secrets, Template, Templates } from "./template.js";
7
- export { Terminal, TERMINAL_CLOSE, TERMINAL_PROTOCOL } from "./terminal.js";
7
+ export { KEPT_TERMINAL_ID, Terminal, TERMINAL_CLOSE, TERMINAL_PROTOCOL } from "./terminal.js";
8
8
  export type { TerminalExit, TerminalOptions, WebSocketConstructor, WebSocketLike } from "./terminal.js";
9
9
  export type { TemplateChanges } from "./template.js";
10
- export type { BurstOptions, CommandLine, CreateOptions, DesktopButton, ExecEvent, ExecOptions, SandboxChanges, ScreenshotOptions, SendEmailOptions, StartOptions, StopOptions, WaitOptions } from "./sandbox.js";
11
- export type { AccountEmail, ApiKey, ApiKeyAction, ApiKeyPreset, ApiKeyUsage, Billing, BrowserState, BurstFee, BurstQuote, Headroom, HeadroomNow, HeadroomRange, HeadroomStep, Catalog, Region, AutoReload, BillingCard, BillingDetails, BillingInvoice, BillingInvoices, Checkout, Command, CreateSchedule, CreateApiKey, CreatedApiKey, DesktopLink, DesktopScreenshot, DesktopState, Egress, EgressAccount, EgressInput, EmailMessage, EmailMessageList, EmailMessageSummary, ExecResult, HiddenVariable, HostRoute, Invite, Me, Member, Organization, MetricsAtMoment, MetricsReading, NetworkRule, Operation, PlainVariable, Plan, Policy, Prices, RunningOverTime, SandboxAutoStop, SandboxEmail, SandboxInfo, SandboxSummary, SandboxJob, SandboxJobItem, SandboxJobPreview, SandboxMetrics, SandboxNetwork, SandboxNetworkDetail, SandboxOwnNetwork, SandboxStatus, SandboxTemplate, SandboxUsage, Schedule, ScheduleRun, SecretVariable, SendEmail, SetAutoStop, Size, Snapshot, SshKey, SshState, UpdateSchedule, Team, TeamRole, Telemetry, DataRetention, AccountExport, TelemetryTest, ClaudeConnection, ClaudeSession, RunsOnRepository, RunsOnRepositories, TemplateApplied, TemplateInfo, TemplateNetwork, TemplateSandbox, TemplateStart, TemplateSsh, Usage, Webhook, WebhookDelivery, } from "./types.js";
10
+ export type { BurstOptions, CommandLine, CreateOptions, DesktopButton, ExecEvent, ExecOptions, ResizeOptions, SandboxChanges, ScreenshotOptions, SendEmailOptions, StartOptions, StopOptions, WaitOptions } from "./sandbox.js";
11
+ export type { AccountEmail, ApiKey, ApiKeyAction, ApiKeyPreset, ApiKeyUsage, Billing, BrowserState, BurstFee, BurstQuote, Headroom, HeadroomNow, HeadroomRange, HeadroomStep, Catalog, Region, AutoReload, BillingCard, BillingDetails, BillingInvoice, BillingInvoices, Checkout, Command, CreateSchedule, CreateApiKey, CreatedApiKey, DesktopLink, DesktopScreenshot, DesktopState, Egress, EgressAccount, EgressInput, EmailMessage, EmailMessageList, EmailMessageSummary, ExecResult, FileContents, FileWritten, Folder, FolderEntry, HiddenVariable, HostRoute, Invite, Me, Member, Organization, MetricsAtMoment, MetricsReading, NetworkRule, Operation, PlainVariable, Plan, Policy, Prices, RunningOverTime, SandboxAutoStop, SandboxEmail, SandboxInfo, SandboxSummary, SandboxJob, SandboxJobItem, SandboxJobPreview, SandboxMetrics, SandboxNetwork, SandboxNetworkDetail, SandboxOwnNetwork, SandboxStatus, SandboxTemplate, SandboxUsage, Schedule, ScheduleRun, SecretVariable, SendEmail, SetAutoStop, Size, Snapshot, SshKey, KeptTerminal, SshState, UpdateSchedule, Team, TeamRole, Telemetry, DataRetention, AccountExport, TelemetryTest, ClaudeConnection, ClaudeSession, RunsOnRepository, RunsOnRepositories, TemplateApplied, TemplateInfo, TemplateNetwork, TemplateSandbox, TemplateStart, TemplateSsh, Usage, Webhook, WebhookDelivery, } from "./types.js";
12
12
  export { verifyWebhook } from "./webhooks.js";
package/dist/index.js CHANGED
@@ -2,5 +2,5 @@ export { Agental } from "./client.js";
2
2
  export { AgentalError, ApiError, ConnectionError, ProxyError, TimeoutError } from "./errors.js";
3
3
  export { Browser, Commands, Desktop, Email, Files, Sandbox, Schedules, Ssh } from "./sandbox.js";
4
4
  export { Secrets, Template, Templates } from "./template.js";
5
- export { Terminal, TERMINAL_CLOSE, TERMINAL_PROTOCOL } from "./terminal.js";
5
+ export { KEPT_TERMINAL_ID, Terminal, TERMINAL_CLOSE, TERMINAL_PROTOCOL } from "./terminal.js";
6
6
  export { verifyWebhook } from "./webhooks.js";
package/dist/openapi.d.ts CHANGED
@@ -250,6 +250,22 @@ export interface paths {
250
250
  patch?: never;
251
251
  trace?: never;
252
252
  };
253
+ "/v1/sandboxes/{id}/resize": {
254
+ parameters: {
255
+ query?: never;
256
+ header?: never;
257
+ path?: never;
258
+ cookie?: never;
259
+ };
260
+ get?: never;
261
+ put?: never;
262
+ post: operations["resizeSandbox"];
263
+ delete?: never;
264
+ options?: never;
265
+ head?: never;
266
+ patch?: never;
267
+ trace?: never;
268
+ };
253
269
  "/v1/sandboxes/{id}/exec": {
254
270
  parameters: {
255
271
  query?: never;
@@ -441,6 +457,38 @@ export interface paths {
441
457
  get: operations["readFile"];
442
458
  put: operations["writeFile"];
443
459
  post?: never;
460
+ delete: operations["deleteFile"];
461
+ options?: never;
462
+ head?: never;
463
+ patch?: never;
464
+ trace?: never;
465
+ };
466
+ "/v1/sandboxes/{id}/files/move": {
467
+ parameters: {
468
+ query?: never;
469
+ header?: never;
470
+ path?: never;
471
+ cookie?: never;
472
+ };
473
+ get?: never;
474
+ put?: never;
475
+ post: operations["moveFile"];
476
+ delete?: never;
477
+ options?: never;
478
+ head?: never;
479
+ patch?: never;
480
+ trace?: never;
481
+ };
482
+ "/v1/sandboxes/{id}/folders": {
483
+ parameters: {
484
+ query?: never;
485
+ header?: never;
486
+ path?: never;
487
+ cookie?: never;
488
+ };
489
+ get: operations["listFolder"];
490
+ put?: never;
491
+ post: operations["makeFolder"];
444
492
  delete?: never;
445
493
  options?: never;
446
494
  head?: never;
@@ -1345,7 +1393,7 @@ export interface paths {
1345
1393
  /** @description Whether a terminal can be opened on the sandbox now. A WebSocket handshake to this address opens one instead, with a ticket from POST /v1/sandboxes/{id}/terminal. */
1346
1394
  get: operations["getSandboxTerminal"];
1347
1395
  put?: never;
1348
- /** @description A ticket to open a terminal on the sandbox: a login shell in it, as root in /root, with what a command runs with. Open a WebSocket to path on this API's address within 30 seconds, with the subprotocols agental.terminal.v1 and ticket.<ticket>. Send challenge, the base64url SHA-256 (unpadded) of a verifier of 43 to 128 base64url characters that you keep, as OAuth's PKCE does with S256, and add the subprotocol verifier.<verifier>: the ticket then opens a terminal only with it, from any address. Without a challenge, it opens one only from the address it was asked from. Send what is typed as binary messages, and {"type":"resize","cols":n,"rows":n} as text. The terminal's output comes as binary messages; {"type":"started"}, {"type":"exit","code","signal","timedOut"} and {"type":"error","code","message"} come as text. It is closed when the shell ends (1000), when what let it be opened no longer does, as a key taken away, a session ended or the sandbox stopped (4003), after 30 minutes with nothing typed (4008), and when it could not be opened or its sandbox stopped answering (4011). Closing it hangs the shell up: what runs in it is sent SIGHUP, as when an SSH session ends. */
1396
+ /** @description A ticket to open a terminal on the sandbox: a login shell in it, as root in /root, with what a command runs with. Open a WebSocket to path on this API's address within 30 seconds, with the subprotocols agental.terminal.v1 and ticket.<ticket>. Send challenge, the base64url SHA-256 (unpadded) of a verifier of 43 to 128 base64url characters that you keep, as OAuth's PKCE does with S256, and add the subprotocol verifier.<verifier>: the ticket then opens a terminal only with it, from any address. Without a challenge, it opens one only from the address it was asked from. Send what is typed as binary messages, and {"type":"resize","cols":n,"rows":n} as text. The terminal's output comes as binary messages; {"type":"started"}, {"type":"exit","code","signal","timedOut"} and {"type":"error","code","message"} come as text. It is closed when the shell ends (1000), when what let it be opened no longer does, as a key taken away, a session ended or the sandbox stopped (4003), after 30 minutes with nothing typed (4008), and when it could not be opened or its sandbox stopped answering (4011). Closing it hangs the shell up: what runs in it is sent SIGHUP, as when an SSH session ends. Asked with keep, the shell runs on instead, and is opened again with its id as terminal; its started message names it as terminal and n. A kept shell opened elsewhere closes this one with 4009. */
1349
1397
  post: operations["openSandboxTerminal"];
1350
1398
  delete?: never;
1351
1399
  options?: never;
@@ -1353,6 +1401,40 @@ export interface paths {
1353
1401
  patch?: never;
1354
1402
  trace?: never;
1355
1403
  };
1404
+ "/v1/sandboxes/{id}/terminals": {
1405
+ parameters: {
1406
+ query?: never;
1407
+ header?: never;
1408
+ path?: never;
1409
+ cookie?: never;
1410
+ };
1411
+ /** @description The shells kept in the sandbox (opened with keep), oldest first: what runs in each one's foreground and where, whether a WebSocket has it open, and how it ended. A stopped sandbox keeps none. */
1412
+ get: operations["listSandboxTerminals"];
1413
+ put?: never;
1414
+ post?: never;
1415
+ delete?: never;
1416
+ options?: never;
1417
+ head?: never;
1418
+ patch?: never;
1419
+ trace?: never;
1420
+ };
1421
+ "/v1/sandboxes/{id}/terminals/{terminalId}": {
1422
+ parameters: {
1423
+ query?: never;
1424
+ header?: never;
1425
+ path?: never;
1426
+ cookie?: never;
1427
+ };
1428
+ get?: never;
1429
+ put?: never;
1430
+ post?: never;
1431
+ /** @description Closes a kept shell: what runs in it is sent SIGHUP, as when an SSH session ends, and it is no longer listed. A WebSocket that has it open is sent its exit. */
1432
+ delete: operations["closeSandboxTerminal"];
1433
+ options?: never;
1434
+ head?: never;
1435
+ patch?: never;
1436
+ trace?: never;
1437
+ };
1356
1438
  "/v1/sandboxes/{id}/schedules": {
1357
1439
  parameters: {
1358
1440
  query?: never;
@@ -1705,6 +1787,22 @@ export interface paths {
1705
1787
  patch?: never;
1706
1788
  trace?: never;
1707
1789
  };
1790
+ "/v1/console/misses": {
1791
+ parameters: {
1792
+ query?: never;
1793
+ header?: never;
1794
+ path?: never;
1795
+ cookie?: never;
1796
+ };
1797
+ get?: never;
1798
+ put?: never;
1799
+ post: operations["reportConsoleMiss"];
1800
+ delete?: never;
1801
+ options?: never;
1802
+ head?: never;
1803
+ patch?: never;
1804
+ trace?: never;
1805
+ };
1708
1806
  "/v1/templates": {
1709
1807
  parameters: {
1710
1808
  query?: never;
@@ -3121,6 +3219,11 @@ export interface components {
3121
3219
  memoryKept: boolean;
3122
3220
  /** @description Why the memory its last stop kept was not put back by its last start, which started it from its disk: as after an upgrade of the server it is on, which the memory cannot be put back across. Null when it was put back, or none was kept. */
3123
3221
  memoryLost: string | null;
3222
+ /**
3223
+ * @description A larger size its next start gives it, asked for by POST /v1/sandboxes/{id}/resize while it ran without restart: it runs, and is billed, at its size until it is stopped and started. Null when none waits.
3224
+ * @enum {string|null}
3225
+ */
3226
+ pendingSize: "tiny" | "small" | "medium" | "large" | null;
3124
3227
  network: components["schemas"]["SandboxNetwork"];
3125
3228
  /** @description What it is doing, as last read: null when it is not running, not read yet, or where GET /v1/policy says metrics is false. */
3126
3229
  activity: {
@@ -3549,15 +3652,62 @@ export interface components {
3549
3652
  encoding: "text" | "base64";
3550
3653
  text?: string;
3551
3654
  base64?: string;
3655
+ bytes: number;
3656
+ /** @description When the file was last changed, to send back as ifModifiedAt. Null for a sandbox made before this could be read. */
3657
+ modifiedAt: string | null;
3552
3658
  };
3553
3659
  FileWritten: {
3554
3660
  path: string;
3555
3661
  bytes: number;
3662
+ /** @description When it was last changed, to the nanosecond, as 2026-11-15T10:04:05.123456789Z. */
3663
+ modifiedAt: string | null;
3556
3664
  };
3557
3665
  FileWrite: {
3666
+ /** @description Relative to the work folder, /opt/agental, or absolute: anywhere on the sandbox's machine, as root sees it. Outside the work folder, an API key needs the action exec as well. */
3558
3667
  path: string;
3559
3668
  text?: string;
3560
3669
  base64?: string;
3670
+ /** @description The modifiedAt the file was read with: the write is refused 409 file_changed if the file was changed or deleted since. */
3671
+ ifModifiedAt?: string;
3672
+ };
3673
+ FileMoved: {
3674
+ from: string;
3675
+ to: string;
3676
+ };
3677
+ FileMove: {
3678
+ /** @description Relative to the work folder, /opt/agental, or absolute: anywhere on the sandbox's machine, as root sees it. Outside the work folder, an API key needs the action exec as well. */
3679
+ from: string;
3680
+ /** @description Relative to the work folder, /opt/agental, or absolute: anywhere on the sandbox's machine, as root sees it. Outside the work folder, an API key needs the action exec as well. */
3681
+ to: string;
3682
+ };
3683
+ Folder: {
3684
+ path: string;
3685
+ entries: components["schemas"]["FolderEntry"][];
3686
+ /** @description The folder holds more than the first 10,000 entries by name, listed here. */
3687
+ truncated: boolean;
3688
+ };
3689
+ FolderEntry: {
3690
+ name: string;
3691
+ /** @enum {string} */
3692
+ kind: "file" | "folder" | "link" | "other";
3693
+ /** @description A file's size; 0 for a folder. */
3694
+ bytes: number;
3695
+ /** @description When it was last changed, to the nanosecond, as 2026-11-15T10:04:05.123456789Z. */
3696
+ modifiedAt: string;
3697
+ /** @description A link's: what it points to. */
3698
+ target?: string;
3699
+ /**
3700
+ * @description A link's, outside the work folder: what it leads to. None where it leads nowhere.
3701
+ * @enum {string}
3702
+ */
3703
+ leadsTo?: "file" | "folder" | "link" | "other";
3704
+ };
3705
+ FolderMade: {
3706
+ path: string;
3707
+ };
3708
+ FolderMake: {
3709
+ /** @description Relative to the work folder, /opt/agental, or absolute: anywhere on the sandbox's machine, as root sees it. Outside the work folder, an API key needs the action exec as well. */
3710
+ path: string;
3561
3711
  };
3562
3712
  StartedCommand: {
3563
3713
  id: string;
@@ -4070,6 +4220,42 @@ export interface components {
4070
4220
  * @example E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
4071
4221
  */
4072
4222
  challenge?: string;
4223
+ /** @description Keep the shell: it runs on when the WebSocket closes, with the last 256 KiB of its output, until it is closed (DELETE /v1/sandboxes/{id}/terminals/{terminalId}), it exits, or the sandbox stops. GET /v1/sandboxes/{id}/terminals lists the kept ones. Without it, closing the WebSocket hangs the shell up. A sandbox whose agent is from before kept shells opens one that is not kept: its started message then names no terminal. */
4224
+ keep?: boolean;
4225
+ /**
4226
+ * @description A kept shell's id, to open it again: what it kept is sent first, then the terminal as it goes on. A WebSocket that had it is closed with 4009. Not taken with keep.
4227
+ * @example pty_0123456789abcdef
4228
+ */
4229
+ terminal?: string;
4230
+ };
4231
+ SandboxKeptTerminals: {
4232
+ terminals: components["schemas"]["SandboxKeptTerminal"][];
4233
+ };
4234
+ SandboxKeptTerminal: {
4235
+ /** @example pty_0123456789abcdef */
4236
+ id: string;
4237
+ /** @description Its number in the sandbox, from 1, in the order the shells were opened. */
4238
+ n: number;
4239
+ startedAt: string;
4240
+ /**
4241
+ * @description What runs in its foreground now (a command line, or the shell's own name at its prompt). Null once it has ended, or where it cannot be read.
4242
+ * @example npm run build
4243
+ */
4244
+ running: string | null;
4245
+ /**
4246
+ * @description The foreground program's working directory.
4247
+ * @example /root/app
4248
+ */
4249
+ cwd: string | null;
4250
+ /** @description Whether a WebSocket has it open now. */
4251
+ attached: boolean;
4252
+ /** @description The bytes it has printed: more than when last looked at means new output. */
4253
+ output: number;
4254
+ /** @description How it ended; null while it runs. An ended shell stays listed, with its output, until it is closed. */
4255
+ exit: {
4256
+ code: number;
4257
+ signal: number;
4258
+ } | null;
4073
4259
  };
4074
4260
  Schedule: {
4075
4261
  /** @example sch_0123456789abcdef */
@@ -7162,6 +7348,79 @@ export interface operations {
7162
7348
  };
7163
7349
  };
7164
7350
  };
7351
+ resizeSandbox: {
7352
+ parameters: {
7353
+ query?: never;
7354
+ header?: {
7355
+ /** @description The most this start may cost in burst fees, in millionths of a US dollar: 0 refuses any fee. A start that would cost more is refused with 429 burst_fee_too_high, which says when it would cost nothing. Left out, it pays what the account's monthly budget allows. See GET /v1/burst. */
7356
+ "agental-max-burst-fee"?: string;
7357
+ };
7358
+ path: {
7359
+ id: string;
7360
+ };
7361
+ cookie?: never;
7362
+ };
7363
+ requestBody: {
7364
+ content: {
7365
+ "application/json": {
7366
+ /**
7367
+ * @description The size it is to have: larger than its own, which gives it more vCPUs, memory and disk, with its files in place. Its own size takes away a size that waits for its next start. GET /v1/sizes lists them.
7368
+ * @enum {string}
7369
+ */
7370
+ size: "tiny" | "small" | "medium" | "large";
7371
+ /** @description For a running sandbox: true stops it and starts it again at the new size now, and every process in it ends, as on a stop; its files stay. Left out, it keeps running at its size, and the new one waits as pendingSize for its next start. A key needs sandbox.stop and sandbox.resume as well to restart one. A stopped sandbox takes the size at once, and its next start boots it at it. */
7372
+ restart?: boolean;
7373
+ };
7374
+ };
7375
+ };
7376
+ responses: {
7377
+ /** @description The sandbox, with its new size, or with pendingSize, the size its next start gives it. A stopped one is billed its new size's stopped price from now, and every start is billed the price of the size it runs at. Memory its last stop kept is let go, and memoryLost says why: a machine of another size cannot take it back. */
7378
+ 200: {
7379
+ headers: {
7380
+ [name: string]: unknown;
7381
+ };
7382
+ content: {
7383
+ "application/json": components["schemas"]["Sandbox"];
7384
+ };
7385
+ };
7386
+ /** @description Missing or invalid API key. */
7387
+ 401: {
7388
+ headers: {
7389
+ [name: string]: unknown;
7390
+ };
7391
+ content: {
7392
+ "application/json": components["schemas"]["Error"];
7393
+ };
7394
+ };
7395
+ /** @description size_not_on_plan: the plan does not make sandboxes of this size, and the message names the plan that does. Nothing was changed. */
7396
+ 402: {
7397
+ headers: {
7398
+ [name: string]: unknown;
7399
+ };
7400
+ content: {
7401
+ "application/json": components["schemas"]["Error"];
7402
+ };
7403
+ };
7404
+ /** @description Not found. */
7405
+ 404: {
7406
+ headers: {
7407
+ [name: string]: unknown;
7408
+ };
7409
+ content: {
7410
+ "application/json": components["schemas"]["Error"];
7411
+ };
7412
+ };
7413
+ /** @description size_smaller: the size is smaller than its own; a smaller size has a smaller disk, which is not made smaller. under_way: it is being started or stopped. invalid_state: it is neither running nor stopped. Nothing was changed. */
7414
+ 409: {
7415
+ headers: {
7416
+ [name: string]: unknown;
7417
+ };
7418
+ content: {
7419
+ "application/json": components["schemas"]["Error"];
7420
+ };
7421
+ };
7422
+ };
7423
+ };
7165
7424
  execCommand: {
7166
7425
  parameters: {
7167
7426
  query?: never;
@@ -7974,6 +8233,7 @@ export interface operations {
7974
8233
  readFile: {
7975
8234
  parameters: {
7976
8235
  query: {
8236
+ /** @description Relative to the work folder, /opt/agental, or absolute: anywhere on the sandbox's machine, as root sees it. Outside the work folder, an API key needs the action exec as well. */
7977
8237
  path: string;
7978
8238
  encoding?: "text" | "base64";
7979
8239
  };
@@ -8047,7 +8307,7 @@ export interface operations {
8047
8307
  };
8048
8308
  };
8049
8309
  responses: {
8050
- /** @description File written into the sandbox directory. */
8310
+ /** @description File written. */
8051
8311
  200: {
8052
8312
  headers: {
8053
8313
  [name: string]: unknown;
@@ -8083,11 +8343,222 @@ export interface operations {
8083
8343
  "application/json": components["schemas"]["Error"];
8084
8344
  };
8085
8345
  };
8346
+ /** @description file_changed: the file was changed or deleted after the ifModifiedAt it was read with. */
8347
+ 409: {
8348
+ headers: {
8349
+ [name: string]: unknown;
8350
+ };
8351
+ content: {
8352
+ "application/json": components["schemas"]["Error"];
8353
+ };
8354
+ };
8355
+ };
8356
+ };
8357
+ deleteFile: {
8358
+ parameters: {
8359
+ query: {
8360
+ /** @description Relative to the work folder, /opt/agental, or absolute: anywhere on the sandbox's machine, as root sees it. Outside the work folder, an API key needs the action exec as well. */
8361
+ path: string;
8362
+ /** @description true deletes a folder with everything in it. A symlink is deleted, never what it leads to. */
8363
+ recursive?: "true" | "false";
8364
+ };
8365
+ header?: never;
8366
+ path: {
8367
+ id: string;
8368
+ };
8369
+ cookie?: never;
8370
+ };
8371
+ requestBody?: never;
8372
+ responses: {
8373
+ /** @description Deleted. */
8374
+ 204: {
8375
+ headers: {
8376
+ [name: string]: unknown;
8377
+ };
8378
+ content?: never;
8379
+ };
8380
+ /** @description Missing or invalid API key. */
8381
+ 401: {
8382
+ headers: {
8383
+ [name: string]: unknown;
8384
+ };
8385
+ content: {
8386
+ "application/json": components["schemas"]["Error"];
8387
+ };
8388
+ };
8389
+ /** @description Not found. */
8390
+ 404: {
8391
+ headers: {
8392
+ [name: string]: unknown;
8393
+ };
8394
+ content: {
8395
+ "application/json": components["schemas"]["Error"];
8396
+ };
8397
+ };
8398
+ /** @description folder_not_empty: a folder with things in it, without recursive=true. */
8399
+ 409: {
8400
+ headers: {
8401
+ [name: string]: unknown;
8402
+ };
8403
+ content: {
8404
+ "application/json": components["schemas"]["Error"];
8405
+ };
8406
+ };
8407
+ };
8408
+ };
8409
+ moveFile: {
8410
+ parameters: {
8411
+ query?: never;
8412
+ header?: never;
8413
+ path: {
8414
+ id: string;
8415
+ };
8416
+ cookie?: never;
8417
+ };
8418
+ requestBody: {
8419
+ content: {
8420
+ "application/json": components["schemas"]["FileMove"];
8421
+ };
8422
+ };
8423
+ responses: {
8424
+ /** @description Moved, or renamed. */
8425
+ 200: {
8426
+ headers: {
8427
+ [name: string]: unknown;
8428
+ };
8429
+ content: {
8430
+ "application/json": components["schemas"]["FileMoved"];
8431
+ };
8432
+ };
8433
+ /** @description Missing or invalid API key. */
8434
+ 401: {
8435
+ headers: {
8436
+ [name: string]: unknown;
8437
+ };
8438
+ content: {
8439
+ "application/json": components["schemas"]["Error"];
8440
+ };
8441
+ };
8442
+ /** @description Not found. */
8443
+ 404: {
8444
+ headers: {
8445
+ [name: string]: unknown;
8446
+ };
8447
+ content: {
8448
+ "application/json": components["schemas"]["Error"];
8449
+ };
8450
+ };
8451
+ /** @description file_exists: something is at to already. Nothing is replaced. */
8452
+ 409: {
8453
+ headers: {
8454
+ [name: string]: unknown;
8455
+ };
8456
+ content: {
8457
+ "application/json": components["schemas"]["Error"];
8458
+ };
8459
+ };
8460
+ };
8461
+ };
8462
+ listFolder: {
8463
+ parameters: {
8464
+ query: {
8465
+ /** @description Relative to the work folder, /opt/agental, or absolute: anywhere on the sandbox's machine, as root sees it. Outside the work folder, an API key needs the action exec as well. */
8466
+ path: string;
8467
+ };
8468
+ header?: never;
8469
+ path: {
8470
+ id: string;
8471
+ };
8472
+ cookie?: never;
8473
+ };
8474
+ requestBody?: never;
8475
+ responses: {
8476
+ /** @description What the folder holds, by name. */
8477
+ 200: {
8478
+ headers: {
8479
+ [name: string]: unknown;
8480
+ };
8481
+ content: {
8482
+ "application/json": components["schemas"]["Folder"];
8483
+ };
8484
+ };
8485
+ /** @description Missing or invalid API key. */
8486
+ 401: {
8487
+ headers: {
8488
+ [name: string]: unknown;
8489
+ };
8490
+ content: {
8491
+ "application/json": components["schemas"]["Error"];
8492
+ };
8493
+ };
8494
+ /** @description Not found. */
8495
+ 404: {
8496
+ headers: {
8497
+ [name: string]: unknown;
8498
+ };
8499
+ content: {
8500
+ "application/json": components["schemas"]["Error"];
8501
+ };
8502
+ };
8503
+ /** @description sandbox_agent_outdated: the sandbox was made before folders could be listed. */
8504
+ 409: {
8505
+ headers: {
8506
+ [name: string]: unknown;
8507
+ };
8508
+ content: {
8509
+ "application/json": components["schemas"]["Error"];
8510
+ };
8511
+ };
8512
+ };
8513
+ };
8514
+ makeFolder: {
8515
+ parameters: {
8516
+ query?: never;
8517
+ header?: never;
8518
+ path: {
8519
+ id: string;
8520
+ };
8521
+ cookie?: never;
8522
+ };
8523
+ requestBody: {
8524
+ content: {
8525
+ "application/json": components["schemas"]["FolderMake"];
8526
+ };
8527
+ };
8528
+ responses: {
8529
+ /** @description The folder, made with any missing above it. One there already is no error. */
8530
+ 200: {
8531
+ headers: {
8532
+ [name: string]: unknown;
8533
+ };
8534
+ content: {
8535
+ "application/json": components["schemas"]["FolderMade"];
8536
+ };
8537
+ };
8538
+ /** @description Missing or invalid API key. */
8539
+ 401: {
8540
+ headers: {
8541
+ [name: string]: unknown;
8542
+ };
8543
+ content: {
8544
+ "application/json": components["schemas"]["Error"];
8545
+ };
8546
+ };
8547
+ /** @description Not found. */
8548
+ 404: {
8549
+ headers: {
8550
+ [name: string]: unknown;
8551
+ };
8552
+ content: {
8553
+ "application/json": components["schemas"]["Error"];
8554
+ };
8555
+ };
8086
8556
  };
8087
8557
  };
8088
8558
  downloadArtifact: {
8089
8559
  parameters: {
8090
8560
  query: {
8561
+ /** @description Relative to the work folder, /opt/agental, or absolute: anywhere on the sandbox's machine, as root sees it. Outside the work folder, an API key needs the action exec as well. */
8091
8562
  path: string;
8092
8563
  };
8093
8564
  header?: never;
@@ -8098,7 +8569,7 @@ export interface operations {
8098
8569
  };
8099
8570
  requestBody?: never;
8100
8571
  responses: {
8101
- /** @description Raw file bytes from the sandbox directory. */
8572
+ /** @description Raw file bytes from the sandbox. */
8102
8573
  200: {
8103
8574
  headers: {
8104
8575
  [name: string]: unknown;
@@ -12305,6 +12776,94 @@ export interface operations {
12305
12776
  };
12306
12777
  };
12307
12778
  };
12779
+ listSandboxTerminals: {
12780
+ parameters: {
12781
+ query?: never;
12782
+ header?: never;
12783
+ path: {
12784
+ id: string;
12785
+ };
12786
+ cookie?: never;
12787
+ };
12788
+ requestBody?: never;
12789
+ responses: {
12790
+ /** @description The kept shells. */
12791
+ 200: {
12792
+ headers: {
12793
+ [name: string]: unknown;
12794
+ };
12795
+ content: {
12796
+ "application/json": components["schemas"]["SandboxKeptTerminals"];
12797
+ };
12798
+ };
12799
+ /** @description Missing or invalid API key. */
12800
+ 401: {
12801
+ headers: {
12802
+ [name: string]: unknown;
12803
+ };
12804
+ content: {
12805
+ "application/json": components["schemas"]["Error"];
12806
+ };
12807
+ };
12808
+ /** @description Not found. */
12809
+ 404: {
12810
+ headers: {
12811
+ [name: string]: unknown;
12812
+ };
12813
+ content: {
12814
+ "application/json": components["schemas"]["Error"];
12815
+ };
12816
+ };
12817
+ };
12818
+ };
12819
+ closeSandboxTerminal: {
12820
+ parameters: {
12821
+ query?: never;
12822
+ header?: never;
12823
+ path: {
12824
+ id: string;
12825
+ terminalId: string;
12826
+ };
12827
+ cookie?: never;
12828
+ };
12829
+ requestBody?: never;
12830
+ responses: {
12831
+ /** @description Closed. */
12832
+ 204: {
12833
+ headers: {
12834
+ [name: string]: unknown;
12835
+ };
12836
+ content?: never;
12837
+ };
12838
+ /** @description Missing or invalid API key. */
12839
+ 401: {
12840
+ headers: {
12841
+ [name: string]: unknown;
12842
+ };
12843
+ content: {
12844
+ "application/json": components["schemas"]["Error"];
12845
+ };
12846
+ };
12847
+ /** @description Not found. */
12848
+ 404: {
12849
+ headers: {
12850
+ [name: string]: unknown;
12851
+ };
12852
+ content: {
12853
+ "application/json": components["schemas"]["Error"];
12854
+ };
12855
+ };
12856
+ /** @description sandbox_not_running: start it first. */
12857
+ 409: {
12858
+ headers: {
12859
+ [name: string]: unknown;
12860
+ };
12861
+ content: {
12862
+ "application/json": components["schemas"]["Error"];
12863
+ };
12864
+ };
12865
+ };
12866
+ };
12308
12867
  listSchedules: {
12309
12868
  parameters: {
12310
12869
  query?: never;
@@ -13767,6 +14326,51 @@ export interface operations {
13767
14326
  };
13768
14327
  };
13769
14328
  };
14329
+ reportConsoleMiss: {
14330
+ parameters: {
14331
+ query?: never;
14332
+ header?: never;
14333
+ path?: never;
14334
+ cookie?: never;
14335
+ };
14336
+ requestBody: {
14337
+ content: {
14338
+ "application/json": {
14339
+ /** @description The address the console's 404 page was shown at, as the browser shows it. */
14340
+ path: string;
14341
+ /** @description The console page the person was on before, where they came from one. */
14342
+ cameFrom?: string | null;
14343
+ };
14344
+ };
14345
+ };
14346
+ responses: {
14347
+ /** @description Counted, or let go where the address is not one kept. The answer is the same either way. */
14348
+ 204: {
14349
+ headers: {
14350
+ [name: string]: unknown;
14351
+ };
14352
+ content?: never;
14353
+ };
14354
+ /** @description Missing or invalid API key or session. */
14355
+ 401: {
14356
+ headers: {
14357
+ [name: string]: unknown;
14358
+ };
14359
+ content: {
14360
+ "application/json": components["schemas"]["Error"];
14361
+ };
14362
+ };
14363
+ /** @description session_required: only the console, signed in, reports a missing page. */
14364
+ 403: {
14365
+ headers: {
14366
+ [name: string]: unknown;
14367
+ };
14368
+ content: {
14369
+ "application/json": components["schemas"]["Error"];
14370
+ };
14371
+ };
14372
+ };
14373
+ };
13770
14374
  listTemplates: {
13771
14375
  parameters: {
13772
14376
  query?: never;
package/dist/sandbox.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type Http } from "./http.js";
2
2
  import { Secrets, type Template } from "./template.js";
3
3
  import { Terminal, type TerminalOptions } from "./terminal.js";
4
- import type { BrowserState, CreateSchedule, Schedule, ScheduleRun, UpdateSchedule, SshKey, SshState, Command, DesktopLink, DesktopScreenshot, DesktopState, EmailMessage, EmailMessageList, EmailMessageSummary, ExecResult, HostRoute, SandboxAutoStop, SandboxEmail, SandboxInfo, SandboxMetrics, SandboxNetworkDetail, SandboxOwnNetwork, SandboxTemplate, SandboxUsage, SendEmail, SetAutoStop, Size, Snapshot, Egress, EgressInput } from "./types.js";
4
+ import type { BrowserState, CreateSchedule, Schedule, ScheduleRun, UpdateSchedule, SshKey, SshState, Command, DesktopLink, DesktopScreenshot, DesktopState, EmailMessage, EmailMessageList, EmailMessageSummary, ExecResult, HostRoute, KeptTerminal, SandboxAutoStop, SandboxEmail, SandboxInfo, SandboxMetrics, SandboxNetworkDetail, SandboxOwnNetwork, SandboxTemplate, SandboxUsage, SendEmail, SetAutoStop, Size, Snapshot, Egress, EgressInput, FileContents, FileWritten, Folder } from "./types.js";
5
5
  /** A create answers when the machine is ready, usually in under a minute. The API says to allow it three. */
6
6
  declare const CREATE_TIMEOUT_MS = 180000;
7
7
  /** A list is the arguments exactly as given, with no shell. A string is a line of shell, run by `sh -c`. */
@@ -130,6 +130,21 @@ export interface WaitOptions {
130
130
  /** How long to wait, in milliseconds. Default 600000. */
131
131
  timeoutMs?: number;
132
132
  }
133
+ /** How to resize a sandbox. */
134
+ export interface ResizeOptions {
135
+ /**
136
+ * For a running sandbox: true stops it and starts it again at the new size now, and every
137
+ * process in it ends, as on a stop; its files stay. Left out, it keeps running at its size,
138
+ * and the new one waits as pendingSize for its next start. An API key needs sandbox.stop and
139
+ * sandbox.resume as well to restart one. A stopped sandbox takes the size at once either way.
140
+ */
141
+ restart?: boolean;
142
+ /**
143
+ * With restart: the most its start may cost in burst fees, in millionths of a US dollar, as
144
+ * for start(). burstFeeMicros says what it paid afterwards.
145
+ */
146
+ maxBurstFeeMicros?: number;
147
+ }
133
148
  /** How to stop a sandbox. */
134
149
  export interface StopOptions {
135
150
  /**
@@ -171,19 +186,47 @@ export declare function makeSandbox(http: Http, path: string, body: unknown, key
171
186
  info: SandboxInfo;
172
187
  burstFeeMicros: number | null;
173
188
  }>;
174
- /** The files in a sandbox's work folder, /opt/agental. Paths are relative to it. */
189
+ /**
190
+ * The files on a sandbox's machine. A path is relative to the work folder, /opt/agental, or
191
+ * absolute: anywhere on the machine, as root sees it.
192
+ */
175
193
  export declare class Files {
176
194
  private readonly http;
177
195
  private readonly path;
178
- constructor(http: Http, path: string);
196
+ private readonly folders;
197
+ constructor(http: Http, path: string, folders: string);
179
198
  /** The text of a file. One that is not UTF-8 is refused: read it with readBytes. */
180
199
  read(path: string): Promise<string>;
181
200
  readBytes(path: string): Promise<Uint8Array>;
182
- /** Writes a file of up to 10 MB, making the folders it needs. */
183
- write(path: string, contents: string | Uint8Array): Promise<{
201
+ /** A file with its size and when it was last changed: modifiedAt is what write takes as ifModifiedAt. */
202
+ get(path: string, options?: {
203
+ encoding?: "text" | "base64";
204
+ }): Promise<FileContents>;
205
+ /**
206
+ * Writes a file of up to 10 MB, making the folders it needs. With ifModifiedAt, the modifiedAt
207
+ * the file was read with, it is refused with file_changed if the file was changed or deleted since.
208
+ */
209
+ write(path: string, contents: string | Uint8Array, options?: {
210
+ ifModifiedAt?: string;
211
+ }): Promise<FileWritten>;
212
+ /** What a folder holds, by name: its first 10,000 entries, and truncated if there are more. */
213
+ list(path: string): Promise<Folder>;
214
+ /** Makes a folder, and any missing above it. One there already is no error. */
215
+ makeFolder(path: string): Promise<{
184
216
  path: string;
185
- bytes: number;
186
217
  }>;
218
+ /** Moves or renames a file or folder. Something at to already is refused with file_exists, and nothing is replaced. */
219
+ move(from: string, to: string): Promise<{
220
+ from: string;
221
+ to: string;
222
+ }>;
223
+ /**
224
+ * Deletes a file, a link (never what it leads to) or an empty folder. A folder with things in it
225
+ * is refused with folder_not_empty, unless recursive says to delete it with everything in it.
226
+ */
227
+ delete(path: string, options?: {
228
+ recursive?: boolean;
229
+ }): Promise<void>;
187
230
  }
188
231
  /**
189
232
  * The sandbox's browser, driven from outside it over the Chrome DevTools Protocol: Chrome in
@@ -466,6 +509,8 @@ export declare class Sandbox {
466
509
  get id(): string;
467
510
  get name(): string;
468
511
  get size(): Size;
512
+ /** The size its next start gives it, as last read, or null when none waits. */
513
+ get pendingSize(): Size | null;
469
514
  /** As it was last read: running, stopped, or on its way to one of them. */
470
515
  get status(): SandboxInfo["status"];
471
516
  refresh(): Promise<this>;
@@ -560,9 +605,31 @@ export declare class Sandbox {
560
605
  * for await (const chunk of terminal) process.stdout.write(chunk);
561
606
  * console.log((await terminal.exited).exitCode);
562
607
  *
608
+ * With keep, the shell runs on when the terminal closes, and attach opens it again by its id,
609
+ * with what it printed meanwhile:
610
+ *
611
+ * const first = await sandbox.terminal({ keep: true });
612
+ * first.write("npm run dev\n");
613
+ * await first.whenStarted();
614
+ * const { id } = first.kept!;
615
+ * first.close(); // it runs on
616
+ * const again = await sandbox.terminal({ attach: id });
617
+ *
563
618
  * It is opened with the runtime's WebSocket: in Node 20, pass new Agental({ WebSocket }).
564
619
  */
565
620
  terminal(options?: TerminalOptions): Promise<Terminal>;
621
+ /**
622
+ * The shells kept in it (opened with keep), oldest first: what runs in each one's foreground
623
+ * and where, whether a terminal has it open, and how it ended. A stopped sandbox keeps none.
624
+ * It needs the key action exec.
625
+ */
626
+ terminals(): Promise<KeptTerminal[]>;
627
+ /**
628
+ * Ends a kept shell by its id: what runs in it is sent SIGHUP, and it is no longer listed. A
629
+ * terminal that has it open is sent its exit. A shell it does not keep is an ApiError 404,
630
+ * terminal_not_found; a stopped sandbox, 409 sandbox_not_running.
631
+ */
632
+ closeTerminal(terminalId: string): Promise<void>;
566
633
  /** Runs a command and gives its output as it arrives, then what it exited with. */
567
634
  execStream(command: CommandLine, options?: ExecOptions): AsyncGenerator<ExecEvent, void, void>;
568
635
  /**
@@ -571,6 +638,17 @@ export declare class Sandbox {
571
638
  * info.memoryLost says why when it could not.
572
639
  */
573
640
  stop(options?: StopOptions): Promise<this>;
641
+ /**
642
+ * Gives it a larger size, with more vCPUs, memory and disk, and its files in place. A
643
+ * stopped sandbox takes it at once, and its next start boots it at it. A running one keeps
644
+ * running at its size, and the new one waits as pendingSize for its next start, unless
645
+ * restart: then it is stopped and started again at the new size now. Its own size takes a
646
+ * waiting one away. A smaller size is refused with size_smaller, one its plan does not make
647
+ * with size_not_on_plan. Memory its last stop kept is let go: info.memoryLost says why. A
648
+ * restart is not sent again by itself, and one that leaves a sandbox that ran not running
649
+ * throws AgentalError, with info read as it was answered.
650
+ */
651
+ resize(size: Size, options?: ResizeOptions): Promise<this>;
574
652
  /**
575
653
  * Starts it again, and waits until it is running. Nothing that was running in it is
576
654
  * started for you. An archived sandbox is brought back first, which takes longer. What it
package/dist/sandbox.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { AgentalError, ApiError, ConnectionError, TimeoutError } from "./errors.js";
2
2
  import { sleep, tagSegment } from "./http.js";
3
3
  import { Secrets } from "./template.js";
4
- import { Terminal, terminalPkce, terminalSize } from "./terminal.js";
4
+ import { KEPT_TERMINAL_ID, Terminal, terminalKeep, terminalPkce, terminalSize } from "./terminal.js";
5
5
  /** A create answers when the machine is ready, usually in under a minute. The API says to allow it three. */
6
6
  const CREATE_TIMEOUT_MS = 180_000;
7
7
  /** An archived sandbox is brought back in as long as its disk is large. */
@@ -97,27 +97,62 @@ export async function makeSandbox(http, path, body, key, timeoutMs, burst = {})
97
97
  }
98
98
  });
99
99
  }
100
- /** The files in a sandbox's work folder, /opt/agental. Paths are relative to it. */
100
+ /**
101
+ * The files on a sandbox's machine. A path is relative to the work folder, /opt/agental, or
102
+ * absolute: anywhere on the machine, as root sees it.
103
+ */
101
104
  export class Files {
102
105
  http;
103
106
  path;
104
- constructor(http, path) {
107
+ folders;
108
+ constructor(http, path, folders) {
105
109
  this.http = http;
106
110
  this.path = path;
111
+ this.folders = folders;
107
112
  }
108
113
  /** The text of a file. One that is not UTF-8 is refused: read it with readBytes. */
109
114
  async read(path) {
110
- const { body } = await this.http.json({ method: "GET", path: this.path, query: { path }, replay: true });
111
- return body.text ?? "";
115
+ return (await this.get(path)).text ?? "";
112
116
  }
113
117
  async readBytes(path) {
114
- const { body } = await this.http.json({ method: "GET", path: this.path, query: { path, encoding: "base64" }, replay: true });
115
- return fromBase64(body.base64 ?? "");
118
+ return fromBase64((await this.get(path, { encoding: "base64" })).base64 ?? "");
119
+ }
120
+ /** A file with its size and when it was last changed: modifiedAt is what write takes as ifModifiedAt. */
121
+ async get(path, options = {}) {
122
+ const query = options.encoding ? { path, encoding: options.encoding } : { path };
123
+ return (await this.http.json({ method: "GET", path: this.path, query, replay: true })).body;
124
+ }
125
+ /**
126
+ * Writes a file of up to 10 MB, making the folders it needs. With ifModifiedAt, the modifiedAt
127
+ * the file was read with, it is refused with file_changed if the file was changed or deleted since.
128
+ */
129
+ async write(path, contents, options = {}) {
130
+ const body = {
131
+ path,
132
+ ...(typeof contents === "string" ? { text: contents } : { base64: toBase64(contents) }),
133
+ ...(options.ifModifiedAt === undefined ? {} : { ifModifiedAt: options.ifModifiedAt }),
134
+ };
135
+ // Sent again after a lost answer, a write made on a time would be refused by its own change.
136
+ return (await this.http.json({ method: "PUT", path: this.path, body, replay: options.ifModifiedAt === undefined })).body;
116
137
  }
117
- /** Writes a file of up to 10 MB, making the folders it needs. */
118
- async write(path, contents) {
119
- const body = typeof contents === "string" ? { path, text: contents } : { path, base64: toBase64(contents) };
120
- return (await this.http.json({ method: "PUT", path: this.path, body, replay: true })).body;
138
+ /** What a folder holds, by name: its first 10,000 entries, and truncated if there are more. */
139
+ async list(path) {
140
+ return (await this.http.json({ method: "GET", path: this.folders, query: { path }, replay: true })).body;
141
+ }
142
+ /** Makes a folder, and any missing above it. One there already is no error. */
143
+ async makeFolder(path) {
144
+ return (await this.http.json({ method: "POST", path: this.folders, body: { path }, replay: true })).body;
145
+ }
146
+ /** Moves or renames a file or folder. Something at to already is refused with file_exists, and nothing is replaced. */
147
+ async move(from, to) {
148
+ return (await this.http.json({ method: "POST", path: `${this.path}/move`, body: { from, to } })).body;
149
+ }
150
+ /**
151
+ * Deletes a file, a link (never what it leads to) or an empty folder. A folder with things in it
152
+ * is refused with folder_not_empty, unless recursive says to delete it with everything in it.
153
+ */
154
+ async delete(path, options = {}) {
155
+ await this.http.send({ method: "DELETE", path: this.path, query: { path, ...(options.recursive ? { recursive: "true" } : {}) } });
121
156
  }
122
157
  }
123
158
  /**
@@ -509,7 +544,7 @@ export class Sandbox {
509
544
  this.info = info;
510
545
  this.burstFeeMicros = burstFeeMicros;
511
546
  this.path = `/v1/sandboxes/${encodeURIComponent(info.id)}`;
512
- this.files = new Files(http, `${this.path}/files`);
547
+ this.files = new Files(http, `${this.path}/files`, `${this.path}/folders`);
513
548
  this.commands = new Commands(http, `${this.path}/commands`);
514
549
  this.schedules = new Schedules(http, `${this.path}/schedules`);
515
550
  this.email = new Email(http, `${this.path}/email`);
@@ -527,6 +562,10 @@ export class Sandbox {
527
562
  get size() {
528
563
  return this.info.size;
529
564
  }
565
+ /** The size its next start gives it, as last read, or null when none waits. */
566
+ get pendingSize() {
567
+ return this.info.pendingSize ?? null;
568
+ }
530
569
  /** As it was last read: running, stopped, or on its way to one of them. */
531
570
  get status() {
532
571
  return this.info.status;
@@ -675,15 +714,45 @@ export class Sandbox {
675
714
  * for await (const chunk of terminal) process.stdout.write(chunk);
676
715
  * console.log((await terminal.exited).exitCode);
677
716
  *
717
+ * With keep, the shell runs on when the terminal closes, and attach opens it again by its id,
718
+ * with what it printed meanwhile:
719
+ *
720
+ * const first = await sandbox.terminal({ keep: true });
721
+ * first.write("npm run dev\n");
722
+ * await first.whenStarted();
723
+ * const { id } = first.kept!;
724
+ * first.close(); // it runs on
725
+ * const again = await sandbox.terminal({ attach: id });
726
+ *
678
727
  * It is opened with the runtime's WebSocket: in Node 20, pass new Agental({ WebSocket }).
679
728
  */
680
729
  async terminal(options = {}) {
681
730
  const { cols, rows } = terminalSize(options);
731
+ const keep = terminalKeep(options);
682
732
  const WebSocket = this.http.WebSocket;
683
733
  const { verifier, challenge } = await terminalPkce();
684
- const { ticket, path } = (await this.http.json({ method: "POST", path: `${this.path}/terminal`, body: { cols, rows, challenge } })).body;
734
+ const { ticket, path } = (await this.http.json({ method: "POST", path: `${this.path}/terminal`, body: { cols, rows, challenge, ...keep } })).body;
685
735
  return await Terminal.open(WebSocket, this.http.webSocketUrl(path), ticket, verifier);
686
736
  }
737
+ /**
738
+ * The shells kept in it (opened with keep), oldest first: what runs in each one's foreground
739
+ * and where, whether a terminal has it open, and how it ended. A stopped sandbox keeps none.
740
+ * It needs the key action exec.
741
+ */
742
+ async terminals() {
743
+ return (await this.http.json({ method: "GET", path: `${this.path}/terminals`, replay: true })).body.terminals;
744
+ }
745
+ /**
746
+ * Ends a kept shell by its id: what runs in it is sent SIGHUP, and it is no longer listed. A
747
+ * terminal that has it open is sent its exit. A shell it does not keep is an ApiError 404,
748
+ * terminal_not_found; a stopped sandbox, 409 sandbox_not_running.
749
+ */
750
+ async closeTerminal(terminalId) {
751
+ if (!KEPT_TERMINAL_ID.test(terminalId)) {
752
+ throw new AgentalError(`closeTerminal takes a kept shell's id, as pty_0123456789abcdef, not ${JSON.stringify(String(terminalId).slice(0, 100))}.`);
753
+ }
754
+ await this.http.send({ method: "DELETE", path: `${this.path}/terminals/${terminalId}`, replay: true });
755
+ }
687
756
  /** Runs a command and gives its output as it arrives, then what it exited with. */
688
757
  async *execStream(command, options = {}) {
689
758
  for await (const { event, data } of this.http.events(this.command("/exec/stream", command, options))) {
@@ -732,6 +801,29 @@ export class Sandbox {
732
801
  }
733
802
  return this;
734
803
  }
804
+ /**
805
+ * Gives it a larger size, with more vCPUs, memory and disk, and its files in place. A
806
+ * stopped sandbox takes it at once, and its next start boots it at it. A running one keeps
807
+ * running at its size, and the new one waits as pendingSize for its next start, unless
808
+ * restart: then it is stopped and started again at the new size now. Its own size takes a
809
+ * waiting one away. A smaller size is refused with size_smaller, one its plan does not make
810
+ * with size_not_on_plan. Memory its last stop kept is let go: info.memoryLost says why. A
811
+ * restart is not sent again by itself, and one that leaves a sandbox that ran not running
812
+ * throws AgentalError, with info read as it was answered.
813
+ */
814
+ async resize(size, options = {}) {
815
+ const restart = options.restart === true;
816
+ const wasRunning = this.info.status === "running";
817
+ const body = { size, ...(options.restart === undefined ? {} : { restart: options.restart }) };
818
+ // A restart is not sent again by itself: one sent again after its start failed would be answered with the sandbox stopped.
819
+ const answer = await this.http.json({ method: "POST", path: `${this.path}/resize`, body, headers: burstHeaders(options), replay: !restart });
820
+ this.info = answer.body;
821
+ this.burstFeeMicros = burstFeeOf(answer.headers);
822
+ if (restart && wasRunning && this.info.status !== "running") {
823
+ throw new AgentalError(`Sandbox ${this.id} was stopped to be restarted as a ${this.info.size}, and is ${this.info.status}, not running again.${this.info.error ? ` ${this.info.error}` : ""} start() starts it.`);
824
+ }
825
+ return this;
826
+ }
735
827
  /**
736
828
  * Starts it again, and waits until it is running. Nothing that was running in it is
737
829
  * started for you. An archived sandbox is brought back first, which takes longer. What it
@@ -8,6 +8,8 @@ export declare const TERMINAL_CLOSE: {
8
8
  readonly accessEnded: 4003;
9
9
  /** Nothing was typed in it for 30 minutes. */
10
10
  readonly idle: 4008;
11
+ /** A kept shell was opened again elsewhere (another terminal(), the console, the CLI): it runs on there. */
12
+ readonly elsewhere: 4009;
11
13
  /** It could not be opened, or its sandbox stopped answering. error says why when the API said. */
12
14
  readonly failed: 4011;
13
15
  };
@@ -26,13 +28,23 @@ export interface TerminalOptions {
26
28
  cols?: number;
27
29
  /** Its height in rows, 1 to 1000. Default 24. */
28
30
  rows?: number;
31
+ /**
32
+ * Keep the shell: it runs on when the terminal is closed, with the last 256 KiB of what it
33
+ * printed, until it exits, closeTerminal() ends it, or the sandbox stops. A sandbox whose
34
+ * agent is from before kept shells opens one that is not kept: kept is then null.
35
+ */
36
+ keep?: boolean;
37
+ /** A kept shell's id, as terminals() lists it, to open it again: what it kept comes first. A terminal that had it is closed with 4009. Not taken with keep. */
38
+ attach?: string;
29
39
  }
40
+ /** A kept shell's id. */
41
+ export declare const KEPT_TERMINAL_ID: RegExp;
30
42
  /** How a terminal ended. */
31
43
  export interface TerminalExit {
32
44
  /**
33
45
  * What the shell exited with, when it ended by itself (closeCode 1000). Null when the
34
46
  * terminal was closed before the shell said: by close(), or by the API (closeCode 4003,
35
- * 4008, 4011), or because the connection was lost.
47
+ * 4008, 4009, 4011), or because the connection was lost.
36
48
  */
37
49
  exitCode: number | null;
38
50
  /** The signal that ended the shell, 0 when none did. */
@@ -69,12 +81,18 @@ export declare function terminalSize(options: TerminalOptions): {
69
81
  cols: number;
70
82
  rows: number;
71
83
  };
84
+ /** What a ticket is asked with besides its size: keep, or the kept shell to open again. */
85
+ export declare function terminalKeep(options: TerminalOptions): {
86
+ keep?: true;
87
+ terminal?: string;
88
+ };
72
89
  /**
73
90
  * A login shell in a sandbox, as root in /root, open over a WebSocket. Its output is read by
74
91
  * iterating it, each piece as bytes as the shell wrote them; what is typed is sent with
75
92
  * write(), and a new size with resize(). It ends when the shell does, when close() is called,
76
93
  * or when the API closes it, and then exited says how. Closing it hangs the shell up: what
77
- * runs in it is sent SIGHUP, as when an SSH session ends.
94
+ * runs in it is sent SIGHUP, as when an SSH session ends. A kept one (opened with keep or
95
+ * attach) runs on instead, to be opened again by its id: kept says which it is.
78
96
  *
79
97
  * Output is kept until it is read: a caller that stops reading should close() it.
80
98
  */
@@ -89,6 +107,7 @@ export declare class Terminal implements AsyncIterable<Uint8Array> {
89
107
  private ended;
90
108
  private started;
91
109
  private startedListeners;
110
+ private keptAs;
92
111
  private constructor();
93
112
  /**
94
113
  * Opens a WebSocket to the terminal a ticket is for, and gives the terminal once the API has
@@ -96,6 +115,14 @@ export declare class Terminal implements AsyncIterable<Uint8Array> {
96
115
  * the subprotocols, never in the URL.
97
116
  */
98
117
  static open(WebSocket: WebSocketConstructor, url: string, ticket: string, verifier?: string): Promise<Terminal>;
118
+ /**
119
+ * The kept shell this is, once it has started: its id, to open it again with attach, and its
120
+ * number in the sandbox. Null before then, and for a shell that is not kept.
121
+ */
122
+ get kept(): {
123
+ id: string;
124
+ n: number;
125
+ } | null;
99
126
  /** Whether the shell has started. What is typed before it has is kept, up to 64 KiB, and given to it once it has. */
100
127
  get hasStarted(): boolean;
101
128
  /** Resolves once the shell has started; at once if it has. Never rejects: it also resolves when the terminal ends first. */
@@ -105,7 +132,7 @@ export declare class Terminal implements AsyncIterable<Uint8Array> {
105
132
  /** Gives the terminal a new size, 1 to 1000 columns and rows, as a local terminal's window changes. Throws a ConnectionError once it has ended. */
106
133
  resize(cols: number, rows: number): void;
107
134
  private mustBeOpen;
108
- /** Closes it, which hangs the shell up. exited resolves once it has closed. */
135
+ /** Closes it, which hangs the shell up, unless it is kept: then it runs on. exited resolves once it has closed. */
109
136
  close(): void;
110
137
  [Symbol.asyncIterator](): AsyncGenerator<Uint8Array, void, void>;
111
138
  private received;
package/dist/terminal.js CHANGED
@@ -18,9 +18,13 @@ export const TERMINAL_CLOSE = {
18
18
  accessEnded: 4003,
19
19
  /** Nothing was typed in it for 30 minutes. */
20
20
  idle: 4008,
21
+ /** A kept shell was opened again elsewhere (another terminal(), the console, the CLI): it runs on there. */
22
+ elsewhere: 4009,
21
23
  /** It could not be opened, or its sandbox stopped answering. error says why when the API said. */
22
24
  failed: 4011,
23
25
  };
26
+ /** A kept shell's id. */
27
+ export const KEPT_TERMINAL_ID = /^pty_[0-9a-f]{16}$/;
24
28
  /**
25
29
  * A verifier, kept in memory alone, and its S256 challenge (RFC 7636), which a ticket is asked with: the ticket then
26
30
  * opens the terminal only with the verifier, which no answer carries, from whatever address the WebSocket leaves by.
@@ -51,13 +55,27 @@ function size(value, what) {
51
55
  export function terminalSize(options) {
52
56
  return { cols: size(options.cols ?? 80, "cols"), rows: size(options.rows ?? 24, "rows") };
53
57
  }
58
+ /** What a ticket is asked with besides its size: keep, or the kept shell to open again. */
59
+ export function terminalKeep(options) {
60
+ if (options.attach !== undefined) {
61
+ if (options.keep === true) {
62
+ throw new AgentalError("A terminal is a new one, kept or not, or a kept one opened again: give keep or attach, not both.");
63
+ }
64
+ if (!KEPT_TERMINAL_ID.test(options.attach)) {
65
+ throw new AgentalError(`attach takes a kept shell's id, as pty_0123456789abcdef, not ${JSON.stringify(String(options.attach).slice(0, 100))}.`);
66
+ }
67
+ return { terminal: options.attach };
68
+ }
69
+ return options.keep === true ? { keep: true } : {};
70
+ }
54
71
  const encoder = new TextEncoder();
55
72
  /**
56
73
  * A login shell in a sandbox, as root in /root, open over a WebSocket. Its output is read by
57
74
  * iterating it, each piece as bytes as the shell wrote them; what is typed is sent with
58
75
  * write(), and a new size with resize(). It ends when the shell does, when close() is called,
59
76
  * or when the API closes it, and then exited says how. Closing it hangs the shell up: what
60
- * runs in it is sent SIGHUP, as when an SSH session ends.
77
+ * runs in it is sent SIGHUP, as when an SSH session ends. A kept one (opened with keep or
78
+ * attach) runs on instead, to be opened again by its id: kept says which it is.
61
79
  *
62
80
  * Output is kept until it is read: a caller that stops reading should close() it.
63
81
  */
@@ -72,6 +90,7 @@ export class Terminal {
72
90
  ended = null;
73
91
  started = false;
74
92
  startedListeners = [];
93
+ keptAs = null;
75
94
  constructor(socket) {
76
95
  this.socket = socket;
77
96
  this.exited = new Promise((resolve) => {
@@ -123,6 +142,13 @@ export class Terminal {
123
142
  }
124
143
  return terminal;
125
144
  }
145
+ /**
146
+ * The kept shell this is, once it has started: its id, to open it again with attach, and its
147
+ * number in the sandbox. Null before then, and for a shell that is not kept.
148
+ */
149
+ get kept() {
150
+ return this.keptAs;
151
+ }
126
152
  /** Whether the shell has started. What is typed before it has is kept, up to 64 KiB, and given to it once it has. */
127
153
  get hasStarted() {
128
154
  return this.started;
@@ -153,7 +179,7 @@ export class Terminal {
153
179
  throw new ConnectionError("The terminal has ended.");
154
180
  }
155
181
  }
156
- /** Closes it, which hangs the shell up. exited resolves once it has closed. */
182
+ /** Closes it, which hangs the shell up, unless it is kept: then it runs on. exited resolves once it has closed. */
157
183
  close() {
158
184
  if (!this.ended) {
159
185
  this.socket.close(1000, "closed");
@@ -192,6 +218,11 @@ export class Terminal {
192
218
  return;
193
219
  }
194
220
  if (message["type"] === "started") {
221
+ const id = message["terminal"];
222
+ const n = message["n"];
223
+ if (typeof id === "string" && KEPT_TERMINAL_ID.test(id) && typeof n === "number" && Number.isInteger(n) && n >= 1) {
224
+ this.keptAs = { id, n };
225
+ }
195
226
  this.started = true;
196
227
  for (const listener of this.startedListeners.splice(0)) {
197
228
  listener();
package/dist/types.d.ts CHANGED
@@ -87,6 +87,16 @@ export type BrowserState = Schemas["BrowserState"];
87
87
  export type SshState = Schemas["SshState"];
88
88
  /** A key that may log in to a sandbox as root: its id, fingerprint, type and comment. */
89
89
  export type SshKey = Schemas["SshKey"];
90
+ /** A file read from a sandbox: its path, its size, when it was last changed (null for a sandbox made before that could be read), and its text or base64. */
91
+ export type FileContents = Schemas["FileContents"];
92
+ /** A file written into a sandbox: its path, its size, and when it was last changed. */
93
+ export type FileWritten = Schemas["FileWritten"];
94
+ /** A folder in a sandbox and what it holds, by name. */
95
+ export type Folder = Schemas["Folder"];
96
+ /** One thing in a folder: a file, a folder, a link or something else, with its size and when it was last changed. */
97
+ export type FolderEntry = Schemas["FolderEntry"];
98
+ /** A shell kept in a sandbox: its id and number, what runs in its foreground and where, whether a terminal has it open, the bytes it has printed, and how it ended (null while it runs). */
99
+ export type KeptTerminal = Schemas["SandboxKeptTerminal"];
90
100
  /** Who a key or session belongs to: the account, its role, and whether it is closed. */
91
101
  export type Me = operations["getMe"]["responses"][200]["content"]["application/json"];
92
102
  export type Operation = Schemas["Operation"];
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** This package's version, as package.json says it. A test holds the two to the same. */
2
- export declare const VERSION = "0.9.0";
2
+ export declare const VERSION = "0.10.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** This package's version, as package.json says it. A test holds the two to the same. */
2
- export const VERSION = "0.9.0";
2
+ export const VERSION = "0.10.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agental-sdk",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "TypeScript SDK for agental.io: Linux sandboxes for your agents. The agental command is the package agental.",
5
5
  "license": "MIT",
6
6
  "author": "VERTIXER LTD",