agental-sdk 0.3.1 → 0.6.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
@@ -175,6 +175,21 @@ await sandbox.ssh.off(); // its port is closed
175
175
 
176
176
  `sandbox.ssh.get()` reads it and changes nothing, and `removeKey(id)` takes a key away. SSH stays on through a stop, a start and a move, and `address` is null while the sandbox is not running. The command's `agental ssh <sandbox-id>` does all of it in one go.
177
177
 
178
+ ## Terminal
179
+
180
+ A login shell in the sandbox, as root in `/root`, over a WebSocket: no key and no port, as the console's Terminal tab has it.
181
+
182
+ ```ts
183
+ const terminal = await sandbox.terminal({ cols: 120, rows: 32 });
184
+ terminal.write("cd /opt/agental && ls\n");
185
+ terminal.resize(132, 40); // as your own terminal's window changes
186
+ terminal.write("exit 3\n");
187
+ for await (const chunk of terminal) process.stdout.write(chunk); // Uint8Array, as the shell wrote it
188
+ const { exitCode, closeCode } = await terminal.exited; // 3, 1000
189
+ ```
190
+
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.
192
+
178
193
  ## Desktop
179
194
 
180
195
  ```ts
@@ -333,20 +348,26 @@ The free plan makes tiny and small sandboxes, the $100 plan medium ones too, and
333
348
 
334
349
  ## How many you run, and how fast you start them
335
350
 
336
- Each plan runs so many small sandboxes at once, its running count, and starts so many at once for nothing, its free burst: a tiny counts half, a medium 2 and a large 4. The free plan runs 20 and bursts 20, though only 2 at once until the account has paid for something (`burst().unpaid`, `prices().free.unpaidUnits`), the $100 plan 100 and 100, the $500 plan 600 and 200, the $2000 plan 2000 and 400; `prices().tiers` gives each plan's `runningUnits` and `freeBurstUnits`, and `burstFee` how fees are worked out. Each start adds its memory to a burst meter that halves every 15 minutes. Starting faster than the free burst is never refused for speed: it costs a burst fee, which grows with how far over the meter goes.
351
+ Each plan runs so many small sandboxes at once, its running count, and starts so many at once for nothing, its free burst: a tiny counts half, a medium 2 and a large 4. The free plan runs 20 and bursts 20, though only 2 at once until the account has paid for something (`headroom().now.unpaid`, `prices().free.unpaidUnits`), the $100 plan 100 and 100, the $500 plan 600 and 200, the $2000 plan 2000 and 400; `prices().tiers` gives each plan's `runningUnits` and `freeBurstUnits`, and `burstFee` how fees are worked out. Each start adds its memory to a burst meter that halves every 15 minutes. Starting faster than the free burst is never refused for speed: it costs a burst fee, which grows with how far over the meter goes.
352
+
353
+ `headroom()` says how close the account runs to these limits: `now`, where it stands, and over a range (today, UTC, unless `from` and `to` say otherwise, 90 days at most) what it ran against its running count, each burst (a stretch when the meter was over the free burst, so every start in it paid a fee), what did not start and why, and how fast what started ran.
337
354
 
338
355
  ```ts
339
- const burst = await agental.burst();
340
- console.log(burst.runningUnits, burst.freeBurstUnits); // 100 100
341
- console.log(burst.freeNowMb / 4096); // small sandboxes you may start now for nothing
342
- console.log(burst.spentMicros, burst.budgetMicros); // burst fees this month, and the most you spend on them
356
+ const { now, atRunningCountMs, bursts, refused } = await agental.headroom();
357
+ console.log(now.runningMb / 4096, now.runningUnits); // small sandboxes running, of 100
358
+ console.log(now.freeNowMb / 4096); // small sandboxes you may start now for nothing
359
+ console.log(now.spentMicros, now.budgetMicros); // burst fees this month, and the most you spend on them
360
+ console.log(now.nextStart); // what one sandbox of each size would cost to start now
361
+ console.log(atRunningCountMs / 60_000); // minutes today at the running count
362
+ console.log(bursts[0]?.startedAt, bursts[0]?.endedAt); // the newest burst; endedAt is null while it goes on
363
+ console.log(refused.total, refused.byReason); // what did not start today: running_count, budget, fee_cap, room or other
343
364
 
344
- // What starting 30 medium ones now would cost, and in how many seconds it would cost nothing.
345
- const { quote } = await agental.burst({ size: "medium", count: 30 });
346
- console.log(quote?.feeMicros, quote?.freeInSeconds);
365
+ // The last week, read every hour.
366
+ const week = await agental.headroom({ from: new Date(Date.now() - 7 * 86_400_000), step: "hour" });
367
+ console.log(week.series.map((point) => point.peakRunningMb / 4096));
347
368
 
348
369
  // Spend at most $10 a month on burst fees; 0 refuses every start that would cost one, null puts back the default ($50).
349
- await agental.setBurstBudget(10_000_000);
370
+ await agental.setHeadroomBudget(10_000_000);
350
371
  ```
351
372
 
352
373
  A create, fork or start takes `maxBurstFeeMicros`, the most it may pay, and the sandbox's `burstFeeMicros` says what it paid:
@@ -357,7 +378,7 @@ console.log(sandbox.burstFeeMicros); // 0 within the free burst
357
378
  await sandbox.start({ maxBurstFeeMicros: 0, maxBurstWaitMs: 300_000 }); // free, waiting up to 5 minutes for it to be
358
379
  ```
359
380
 
360
- Where `enforced` is true, a start is refused with an `ApiError` of status 429 and one of these codes. `feeMicros` says what it would have cost and `retryAfterSeconds` when it would cost nothing, or null when waiting would not help:
381
+ Where `now.enforced` is true, a start is refused with an `ApiError` of status 429 and one of these codes. `feeMicros` says what it would have cost and `retryAfterSeconds` when it would cost nothing, or null when waiting would not help; `refusedLastHour` how many creates and starts were refused with the same code in the last hour, this one with them, and `headroomUrl` the console's page that shows them all:
361
382
 
362
383
  - `running_limit_reached`: the account already runs its plan's running count. Stop something first.
363
384
  - `burst_fee_too_high`: the start would cost more than `maxBurstFeeMicros`.
@@ -493,7 +514,7 @@ await agental.rotateWebhookSecret(hook.id); // a new signingSecret; the old one
493
514
  await agental.deleteWebhook(hook.id);
494
515
  ```
495
516
 
496
- `events` takes the kinds of event, such as `sandbox.started`, `sandbox.stopped` and `sandbox.error`. `sandbox.auto_stop_set` is a running sandbox's stop moved: its `data` has `autoStopAt`, `previousAutoStopAt`, and `by`, `account` or `sandbox`.
517
+ `events` takes the kinds of event, such as `sandbox.started`, `sandbox.stopped` and `sandbox.error`. `sandbox.auto_stop_set` is a running sandbox's stop moved: its `data` has `autoStopAt`, `previousAutoStopAt`, and `by`, `account` or `sandbox`. A group by its name and `.*`, such as `headroom.*` or `sandbox.*`, takes every kind of the group and any added to it later; a `*` anywhere else is refused. The `headroom.*` events are your organization's, about no sandbox: `headroom.burst_started` and `headroom.burst_ended` (a stretch over the free burst, with what it cost), `headroom.refused` (starts refused, at most one a minute for each reason), `headroom.running_count_reached`, `headroom.budget_threshold` (burst fees past 80% of the month's budget) and `headroom.budget_reached` (the budget refused a start). Money is in micros of a dollar, memory in MB.
497
518
 
498
519
  Check each post your server receives:
499
520
 
package/dist/client.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Http, type AgentalOptions } from "./http.js";
2
2
  import { Email, Sandbox, type CreateOptions } from "./sandbox.js";
3
3
  import { Templates } from "./template.js";
4
- import type { AccountEmail, AccountExport, ApiKey, ApiKeyUsage, Billing, Burst, Catalog, HostRoute, Invite, Me, Member, Organization, Region, AutoReload, Checkout, DataRetention, CreateApiKey, CreatedApiKey, MetricsAtMoment, Policy, Prices, RunningOverTime, SandboxSummary, SandboxJob, SandboxJobItem, SandboxJobPreview, Size, Snapshot, Team, TeamRole, Telemetry, TelemetryTest, RunsOnRepository, RunsOnRepositories, Usage, Webhook, EgressAccount } from "./types.js";
4
+ import type { AccountEmail, AccountExport, ApiKey, ApiKeyUsage, Billing, Headroom, HeadroomNow, HeadroomRange, Catalog, HostRoute, Invite, Me, Member, Organization, Region, AutoReload, Checkout, DataRetention, CreateApiKey, CreatedApiKey, MetricsAtMoment, Policy, Prices, RunningOverTime, SandboxSummary, SandboxJob, SandboxJobItem, SandboxJobPreview, Snapshot, Team, TeamRole, Telemetry, TelemetryTest, ClaudeConnection, ClaudeSession, RunsOnRepository, RunsOnRepositories, Usage, Webhook, EgressAccount } from "./types.js";
5
5
  /** What a list of sandboxes is narrowed to. Each field left out narrows nothing; a list of values is any of them. */
6
6
  export interface SandboxFilter {
7
7
  /** Tags every sandbox has. */
@@ -313,28 +313,27 @@ export declare class Agental {
313
313
  /** The account's mail: the handle every address of its sandboxes carries, what its plan allows, and what it has had of that today. */
314
314
  email(): Promise<AccountEmail>;
315
315
  /**
316
- * Where your account stands against its plan: how many small sandboxes it runs and may run
317
- * at once (runningUnits; a tiny counts half, a medium 2, a large 4), what its burst meter
318
- * reads against the free burst, what it has spent on burst fees this month against its
319
- * budget, and what one sandbox of each size would cost to start now. With a size, and a
320
- * count, quote says what starting that many now would cost.
316
+ * How close your account runs to its plan's limits. `now` is where it stands: how many small
317
+ * sandboxes it runs and may run at once (runningUnits; a tiny counts half, a medium 2, a
318
+ * large 4), what its burst meter reads against the free burst, what it has spent on burst
319
+ * fees this month against its budget, and what one sandbox of each size would cost to start
320
+ * now. Over the range, today (UTC) unless from and to say otherwise: what it ran against its
321
+ * running count (series, atRunningCountMs), each burst, what did not start and why
322
+ * (refused), and how fast what started ran (speed). A range covers 90 days at most.
321
323
  *
322
- * Where `enforced` is true, a create, fork or start past the running count throws an
324
+ * Where `now.enforced` is true, a create, fork or start past the running count throws an
323
325
  * `ApiError` 429 `running_limit_reached`; one faster than the free burst costs a burst fee,
324
326
  * and is refused with `burst_budget_reached` past the monthly budget.
325
- * On the free plan, until the account has paid for something (`unpaid`), the running count
326
- * is `free.unpaidUnits` of prices(). Amounts are millionths of a US dollar.
327
+ * On the free plan, until the account has paid for something (`now.unpaid`), the running
328
+ * count is `free.unpaidUnits` of prices(). Amounts are millionths of a US dollar.
327
329
  */
328
- burst(quote?: {
329
- size: Size;
330
- count?: number;
331
- }): Promise<Burst>;
330
+ headroom(range?: HeadroomRange): Promise<Headroom>;
332
331
  /**
333
332
  * Sets the most the account spends on burst fees in a month, in millionths of a US dollar:
334
333
  * 0 refuses every start that would cost one. null gives it the default again,
335
- * defaultBudgetMicros. It answers with the account's burst as it stands now.
334
+ * defaultBudgetMicros. It answers with where the account stands now, as headroom().now.
336
335
  */
337
- setBurstBudget(budgetMicros: number | null): Promise<Burst>;
336
+ setHeadroomBudget(budgetMicros: number | null): Promise<HeadroomNow>;
338
337
  /**
339
338
  * Whether the account may send sandboxes out through residential addresses, and what it
340
339
  * still needs: plan (Fleet or larger), card (one saved), use_case (setEgressUseCase()).
@@ -407,6 +406,40 @@ export declare class Agental {
407
406
  testTelemetry(): Promise<TelemetryTest>;
408
407
  /** Removes your collector, with its headers, and nothing more is sent to it. When none is set it throws an ApiError with the status 404. */
409
408
  deleteTelemetry(): Promise<void>;
409
+ /**
410
+ * The Claude Managed Agents self-hosted environments connected to your account. Each
411
+ * session of one runs its tool calls in a sandbox of your own. Their keys and signing
412
+ * secrets are never shown. Only where policy() says managedAgents.
413
+ */
414
+ listClaudeConnections(): Promise<ClaudeConnection[]>;
415
+ /**
416
+ * Connects a self-hosted environment from the Claude Console: its id, its environment key,
417
+ * and, for a turn to start at once, its webhook's signing secret. The key and secret are
418
+ * kept sealed and never shown again, and the key never goes into a sandbox. Each session
419
+ * gets a sandbox on templateId (the account's default when left out), stopped between turns
420
+ * and deleted once it has slept keepDays (7). Set the answer's webhookUrl as the
421
+ * environment's webhook for session.status_run_started in the Claude Console.
422
+ */
423
+ connectClaude(connection: {
424
+ environmentId: string;
425
+ environmentKey: string;
426
+ webhookSecret?: string;
427
+ templateId?: string | null;
428
+ keepDays?: number;
429
+ }): Promise<ClaudeConnection>;
430
+ /** One connected environment. */
431
+ getClaudeConnection(id: string): Promise<ClaudeConnection>;
432
+ /** The sessions of a connected environment that have run here, the latest active first: each one's sandbox, whether it runs or sleeps, when a sleeping one's sandbox is deleted, and why its last turn was not served. */
433
+ listClaudeSessions(id: string): Promise<ClaudeSession[]>;
434
+ /** Changes a connection: a new key or signing secret (null forgets it), another template (null for the default), or keepDays. What is left out stays as it was. */
435
+ updateClaudeConnection(id: string, change: {
436
+ environmentKey?: string;
437
+ webhookSecret?: string | null;
438
+ templateId?: string | null;
439
+ keepDays?: number;
440
+ }): Promise<ClaudeConnection>;
441
+ /** Disconnects an environment: its key and signing secret are forgotten, and no more of its work is claimed. Its sessions' sandboxes are left as they are. */
442
+ disconnectClaude(id: string): Promise<void>;
410
443
  /**
411
444
  * GitHub Actions jobs on sandboxes: each repository's pool, how many sandboxes of each size it
412
445
  * keeps and the template they are made on. available is false where jobs do not run on
@@ -441,8 +474,10 @@ export declare class Agental {
441
474
  listWebhooks(): Promise<Webhook[]>;
442
475
  /**
443
476
  * Adds a webhook. url is posted each event it takes, and has to be on the public internet.
444
- * events names the kinds it takes, such as sandbox.stopped, or "*" for every one and any
445
- * added later, which is what it takes when events is left out. The answer holds
477
+ * events names the kinds it takes, such as sandbox.stopped or headroom.burst_ended, a group
478
+ * of them by its name and .*, such as "headroom.*", which takes the group's kinds added later
479
+ * too, or "*" for every one and any added later, which is what it takes when events is left
480
+ * out. A * anywhere else is refused. The answer holds
446
481
  * signingSecret, the one time it is given: each post's X-Agental-Signature is checked
447
482
  * against it with verifyWebhook. It is sent once, so a lost answer is not sent again.
448
483
  */
package/dist/client.js CHANGED
@@ -431,29 +431,32 @@ export class Agental {
431
431
  return (await this.http.json({ method: "GET", path: "/v1/email", replay: true })).body;
432
432
  }
433
433
  /**
434
- * Where your account stands against its plan: how many small sandboxes it runs and may run
435
- * at once (runningUnits; a tiny counts half, a medium 2, a large 4), what its burst meter
436
- * reads against the free burst, what it has spent on burst fees this month against its
437
- * budget, and what one sandbox of each size would cost to start now. With a size, and a
438
- * count, quote says what starting that many now would cost.
434
+ * How close your account runs to its plan's limits. `now` is where it stands: how many small
435
+ * sandboxes it runs and may run at once (runningUnits; a tiny counts half, a medium 2, a
436
+ * large 4), what its burst meter reads against the free burst, what it has spent on burst
437
+ * fees this month against its budget, and what one sandbox of each size would cost to start
438
+ * now. Over the range, today (UTC) unless from and to say otherwise: what it ran against its
439
+ * running count (series, atRunningCountMs), each burst, what did not start and why
440
+ * (refused), and how fast what started ran (speed). A range covers 90 days at most.
439
441
  *
440
- * Where `enforced` is true, a create, fork or start past the running count throws an
442
+ * Where `now.enforced` is true, a create, fork or start past the running count throws an
441
443
  * `ApiError` 429 `running_limit_reached`; one faster than the free burst costs a burst fee,
442
444
  * and is refused with `burst_budget_reached` past the monthly budget.
443
- * On the free plan, until the account has paid for something (`unpaid`), the running count
444
- * is `free.unpaidUnits` of prices(). Amounts are millionths of a US dollar.
445
+ * On the free plan, until the account has paid for something (`now.unpaid`), the running
446
+ * count is `free.unpaidUnits` of prices(). Amounts are millionths of a US dollar.
445
447
  */
446
- async burst(quote) {
447
- const query = { size: quote?.size, count: quote?.count?.toString() };
448
- return (await this.http.json({ method: "GET", path: "/v1/burst", query, replay: true })).body;
448
+ async headroom(range = {}) {
449
+ const iso = (at) => (at instanceof Date ? at.toISOString() : at);
450
+ const query = { from: iso(range.from), to: iso(range.to), step: range.step };
451
+ return (await this.http.json({ method: "GET", path: "/v1/headroom", query, replay: true })).body;
449
452
  }
450
453
  /**
451
454
  * Sets the most the account spends on burst fees in a month, in millionths of a US dollar:
452
455
  * 0 refuses every start that would cost one. null gives it the default again,
453
- * defaultBudgetMicros. It answers with the account's burst as it stands now.
456
+ * defaultBudgetMicros. It answers with where the account stands now, as headroom().now.
454
457
  */
455
- async setBurstBudget(budgetMicros) {
456
- return (await this.http.json({ method: "PUT", path: "/v1/burst/budget", body: { budgetMicros }, replay: true })).body;
458
+ async setHeadroomBudget(budgetMicros) {
459
+ return (await this.http.json({ method: "PUT", path: "/v1/headroom/budget", body: { budgetMicros }, replay: true })).body;
457
460
  }
458
461
  /**
459
462
  * Whether the account may send sandboxes out through residential addresses, and what it
@@ -538,6 +541,41 @@ export class Agental {
538
541
  async deleteTelemetry() {
539
542
  await this.http.send({ method: "DELETE", path: "/v1/telemetry" });
540
543
  }
544
+ /**
545
+ * The Claude Managed Agents self-hosted environments connected to your account. Each
546
+ * session of one runs its tool calls in a sandbox of your own. Their keys and signing
547
+ * secrets are never shown. Only where policy() says managedAgents.
548
+ */
549
+ async listClaudeConnections() {
550
+ return (await this.http.json({ method: "GET", path: "/v1/claude/connections", replay: true })).body.data;
551
+ }
552
+ /**
553
+ * Connects a self-hosted environment from the Claude Console: its id, its environment key,
554
+ * and, for a turn to start at once, its webhook's signing secret. The key and secret are
555
+ * kept sealed and never shown again, and the key never goes into a sandbox. Each session
556
+ * gets a sandbox on templateId (the account's default when left out), stopped between turns
557
+ * and deleted once it has slept keepDays (7). Set the answer's webhookUrl as the
558
+ * environment's webhook for session.status_run_started in the Claude Console.
559
+ */
560
+ async connectClaude(connection) {
561
+ return (await this.http.json({ method: "POST", path: "/v1/claude/connections", body: connection })).body.connection;
562
+ }
563
+ /** One connected environment. */
564
+ async getClaudeConnection(id) {
565
+ return (await this.http.json({ method: "GET", path: `/v1/claude/connections/${encodeURIComponent(id)}`, replay: true })).body.connection;
566
+ }
567
+ /** The sessions of a connected environment that have run here, the latest active first: each one's sandbox, whether it runs or sleeps, when a sleeping one's sandbox is deleted, and why its last turn was not served. */
568
+ async listClaudeSessions(id) {
569
+ return (await this.http.json({ method: "GET", path: `/v1/claude/connections/${encodeURIComponent(id)}/sessions`, replay: true })).body.data;
570
+ }
571
+ /** Changes a connection: a new key or signing secret (null forgets it), another template (null for the default), or keepDays. What is left out stays as it was. */
572
+ async updateClaudeConnection(id, change) {
573
+ return (await this.http.json({ method: "PATCH", path: `/v1/claude/connections/${encodeURIComponent(id)}`, body: change, replay: true })).body.connection;
574
+ }
575
+ /** Disconnects an environment: its key and signing secret are forgotten, and no more of its work is claimed. Its sessions' sandboxes are left as they are. */
576
+ async disconnectClaude(id) {
577
+ await this.http.send({ method: "DELETE", path: `/v1/claude/connections/${encodeURIComponent(id)}` });
578
+ }
541
579
  /**
542
580
  * GitHub Actions jobs on sandboxes: each repository's pool, how many sandboxes of each size it
543
581
  * keeps and the template they are made on. available is false where jobs do not run on
@@ -581,8 +619,10 @@ export class Agental {
581
619
  }
582
620
  /**
583
621
  * Adds a webhook. url is posted each event it takes, and has to be on the public internet.
584
- * events names the kinds it takes, such as sandbox.stopped, or "*" for every one and any
585
- * added later, which is what it takes when events is left out. The answer holds
622
+ * events names the kinds it takes, such as sandbox.stopped or headroom.burst_ended, a group
623
+ * of them by its name and .*, such as "headroom.*", which takes the group's kinds added later
624
+ * too, or "*" for every one and any added later, which is what it takes when events is left
625
+ * out. A * anywhere else is refused. The answer holds
586
626
  * signingSecret, the one time it is given: each post's X-Agental-Signature is checked
587
627
  * against it with verifyWebhook. It is sent once, so a lost answer is not sent again.
588
628
  */
package/dist/errors.d.ts CHANGED
@@ -21,21 +21,33 @@ export declare class ApiError extends AgentalError {
21
21
  * size now, to send it again to with a new key. Empty when none has, and undefined on
22
22
  * any other error.
23
23
  */
24
- regionsWithRoom?: string[] | undefined, burst?: {
24
+ regionsWithRoom?: string[] | undefined, refusal?: {
25
25
  feeMicros?: number;
26
26
  retryAfterSeconds?: number | null;
27
+ refusedLastHour?: number;
28
+ headroomUrl?: string;
27
29
  });
28
30
  /**
29
- * On a start refused with 429 for its burst (see `BurstRefusalCode`): the burst fee it
31
+ * On a start refused with 429 or 409 for its burst (see `BurstRefusalCode`): the burst fee it
30
32
  * would have cost, in millionths of a US dollar. Undefined on any other error.
31
33
  */
32
34
  readonly feeMicros?: number;
33
35
  /**
34
- * On a start refused with 429 for its burst: seconds until the same start would cost no
36
+ * On a start refused with 429 or 409 for its burst: seconds until the same start would cost no
35
37
  * burst fee. Null where waiting would not help: on running_limit_reached, or for a start
36
38
  * larger than the plan's whole free burst. Undefined on any other error.
37
39
  */
38
40
  readonly retryAfterSeconds?: number | null;
41
+ /**
42
+ * On a create or start refused with 429 or 409: how many of the account's creates and starts were
43
+ * refused with the same code in the last hour, this one with them. Undefined on any other error.
44
+ */
45
+ readonly refusedLastHour?: number;
46
+ /**
47
+ * On a create or start refused with 429 or 409: the console's page where the account sees every
48
+ * refusal, as headroom() reads them. Undefined on any other error.
49
+ */
50
+ readonly headroomUrl?: string;
39
51
  }
40
52
  /**
41
53
  * Why a create, fork or start was refused with the status 429. running_limit_reached: the
package/dist/errors.js CHANGED
@@ -19,29 +19,45 @@ export class ApiError extends AgentalError {
19
19
  * size now, to send it again to with a new key. Empty when none has, and undefined on
20
20
  * any other error.
21
21
  */
22
- regionsWithRoom, burst) {
22
+ regionsWithRoom, refusal) {
23
23
  super(message);
24
24
  this.status = status;
25
25
  this.code = code;
26
26
  this.regionsWithRoom = regionsWithRoom;
27
- if (burst?.feeMicros !== undefined) {
28
- this.feeMicros = burst.feeMicros;
27
+ if (refusal?.feeMicros !== undefined) {
28
+ this.feeMicros = refusal.feeMicros;
29
29
  }
30
- if (burst?.retryAfterSeconds !== undefined) {
31
- this.retryAfterSeconds = burst.retryAfterSeconds;
30
+ if (refusal?.retryAfterSeconds !== undefined) {
31
+ this.retryAfterSeconds = refusal.retryAfterSeconds;
32
+ }
33
+ if (refusal?.refusedLastHour !== undefined) {
34
+ this.refusedLastHour = refusal.refusedLastHour;
35
+ }
36
+ if (refusal?.headroomUrl !== undefined) {
37
+ this.headroomUrl = refusal.headroomUrl;
32
38
  }
33
39
  }
34
40
  /**
35
- * On a start refused with 429 for its burst (see `BurstRefusalCode`): the burst fee it
41
+ * On a start refused with 429 or 409 for its burst (see `BurstRefusalCode`): the burst fee it
36
42
  * would have cost, in millionths of a US dollar. Undefined on any other error.
37
43
  */
38
44
  feeMicros;
39
45
  /**
40
- * On a start refused with 429 for its burst: seconds until the same start would cost no
46
+ * On a start refused with 429 or 409 for its burst: seconds until the same start would cost no
41
47
  * burst fee. Null where waiting would not help: on running_limit_reached, or for a start
42
48
  * larger than the plan's whole free burst. Undefined on any other error.
43
49
  */
44
50
  retryAfterSeconds;
51
+ /**
52
+ * On a create or start refused with 429 or 409: how many of the account's creates and starts were
53
+ * refused with the same code in the last hour, this one with them. Undefined on any other error.
54
+ */
55
+ refusedLastHour;
56
+ /**
57
+ * On a create or start refused with 429 or 409: the console's page where the account sees every
58
+ * refusal, as headroom() reads them. Undefined on any other error.
59
+ */
60
+ headroomUrl;
45
61
  }
46
62
  /**
47
63
  * Something in front of the API answered, not the API: a 502, a 504, a 52x, or any error
package/dist/http.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { WebSocketConstructor } from "./terminal.js";
1
2
  export declare const DEFAULT_BASE_URL = "https://agental.io";
2
3
  export interface AgentalOptions {
3
4
  /**
@@ -15,6 +16,11 @@ export interface AgentalOptions {
15
16
  retryDelayMs?: number;
16
17
  /** How often something that is waited for is looked at, in milliseconds. Default 2000. */
17
18
  pollIntervalMs?: number;
19
+ /**
20
+ * What a sandbox's terminal is opened with. Left out, it is the runtime's own WebSocket: in
21
+ * Node 22 and later, browsers, Deno and Bun. In Node 20, pass WebSocket from the ws package.
22
+ */
23
+ WebSocket?: WebSocketConstructor;
18
24
  }
19
25
  export interface Call {
20
26
  method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
@@ -42,7 +48,16 @@ export declare class Http {
42
48
  private readonly fetch;
43
49
  private readonly maxRetries;
44
50
  private readonly retryDelayMs;
51
+ private readonly webSocket;
45
52
  constructor(options?: AgentalOptions);
53
+ /** The WebSocket a terminal is opened with: the one given, else the runtime's own. */
54
+ get WebSocket(): WebSocketConstructor;
55
+ /**
56
+ * The ws: or wss: URL of a path on the API's own address, as a terminal's WebSocket is opened
57
+ * on it. Only a path is taken, so that no answer can send the WebSocket, and the ticket in
58
+ * it, to another host.
59
+ */
60
+ webSocketUrl(path: string): string;
46
61
  /** The answer to a request that worked. One that did not is thrown, after it was sent again if that was safe. */
47
62
  send(call: Call): Promise<Response>;
48
63
  /** The JSON a request was answered with, and the status and headers it came with. */
package/dist/http.js CHANGED
@@ -64,6 +64,7 @@ export class Http {
64
64
  fetch;
65
65
  maxRetries;
66
66
  retryDelayMs;
67
+ webSocket;
67
68
  constructor(options = {}) {
68
69
  let apiKey = options.apiKey ?? environment("AGENTAL_API_KEY");
69
70
  let baseUrl = options.baseUrl ?? environment("AGENTAL_API_URL");
@@ -84,6 +85,30 @@ export class Http {
84
85
  this.maxRetries = options.maxRetries ?? 3;
85
86
  this.retryDelayMs = options.retryDelayMs ?? 1000;
86
87
  this.pollIntervalMs = options.pollIntervalMs ?? 2000;
88
+ this.webSocket = options.WebSocket;
89
+ }
90
+ /** The WebSocket a terminal is opened with: the one given, else the runtime's own. */
91
+ get WebSocket() {
92
+ const found = this.webSocket ?? globalThis.WebSocket;
93
+ if (!found) {
94
+ throw new AgentalError("This runtime has no WebSocket, which a terminal is opened with. Use Node 22 or later, or pass new Agental({ WebSocket }) with WebSocket from the ws package.");
95
+ }
96
+ return found;
97
+ }
98
+ /**
99
+ * The ws: or wss: URL of a path on the API's own address, as a terminal's WebSocket is opened
100
+ * on it. Only a path is taken, so that no answer can send the WebSocket, and the ticket in
101
+ * it, to another host.
102
+ */
103
+ webSocketUrl(path) {
104
+ if (!path.startsWith("/") || path.startsWith("//") || /[\\\s]/.test(path)) {
105
+ throw new AgentalError(`The API gave the terminal a path that is not one on its own address: ${JSON.stringify(path.slice(0, 200))}.`);
106
+ }
107
+ const url = new URL(this.baseUrl);
108
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
109
+ throw new AgentalError(`A terminal is opened on an http: or https: API, not ${url.protocol}.`);
110
+ }
111
+ return `${url.origin.replace(/^http/, "ws")}${url.pathname.replace(/\/+$/, "")}${path}`;
87
112
  }
88
113
  /** The answer to a request that worked. One that did not is thrown, after it was sent again if that was safe. */
89
114
  async send(call) {
@@ -221,14 +246,16 @@ async function errorOf(response) {
221
246
  const body = parsed(await response.text().catch(() => ""));
222
247
  const error = body && typeof body === "object" ? body.error : null;
223
248
  if (error && typeof error === "object") {
224
- const { code, message, regionsWithRoom, feeMicros, retryAfterSeconds } = error;
249
+ const { code, message, regionsWithRoom, feeMicros, retryAfterSeconds, refusedLastHour, headroomUrl } = error;
225
250
  if (typeof code === "string" && typeof message === "string") {
226
251
  const regions = Array.isArray(regionsWithRoom) ? regionsWithRoom.filter((one) => typeof one === "string") : undefined;
227
- const burst = {
252
+ const refusal = {
228
253
  ...(typeof feeMicros === "number" ? { feeMicros } : {}),
229
254
  ...(typeof retryAfterSeconds === "number" || retryAfterSeconds === null ? { retryAfterSeconds } : {}),
255
+ ...(typeof refusedLastHour === "number" ? { refusedLastHour } : {}),
256
+ ...(typeof headroomUrl === "string" ? { headroomUrl } : {}),
230
257
  };
231
- return new ApiError(response.status, code, message, regions, burst);
258
+ return new ApiError(response.status, code, message, regions, refusal);
232
259
  }
233
260
  }
234
261
  return new ProxyError(response.status);
package/dist/index.d.ts CHANGED
@@ -4,7 +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";
8
+ export type { TerminalExit, TerminalOptions, WebSocketConstructor, WebSocketLike } from "./terminal.js";
7
9
  export type { TemplateChanges } from "./template.js";
8
10
  export type { BurstOptions, CommandLine, CreateOptions, DesktopButton, ExecEvent, ExecOptions, SandboxChanges, ScreenshotOptions, SendEmailOptions, StartOptions, StopOptions, WaitOptions } from "./sandbox.js";
9
- export type { AccountEmail, ApiKey, ApiKeyAction, ApiKeyPreset, ApiKeyUsage, Billing, BrowserState, Burst, BurstFee, BurstQuote, Catalog, Region, AutoReload, 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, RunsOnRepository, RunsOnRepositories, TemplateApplied, TemplateInfo, TemplateNetwork, TemplateSandbox, TemplateStart, TemplateSsh, Usage, Webhook, WebhookDelivery, } from "./types.js";
11
+ export type { AccountEmail, ApiKey, ApiKeyAction, ApiKeyPreset, ApiKeyUsage, Billing, BrowserState, BurstFee, BurstQuote, Headroom, HeadroomNow, HeadroomRange, HeadroomStep, Catalog, Region, AutoReload, 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
12
  export { verifyWebhook } from "./webhooks.js";
package/dist/index.js CHANGED
@@ -2,4 +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
6
  export { verifyWebhook } from "./webhooks.js";