agental-sdk 0.1.0 → 0.2.1

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
@@ -88,6 +88,7 @@ await sandbox.schedules.update(tick.id, { enabled: false }); // paused
88
88
  - When a run finds the sandbox stopped, it starts it, runs, and stops it again when the command ends, keeping its disk: you pay for the minutes it runs. `keepMemory: true` keeps its memory too. `ifStopped: "skip"` runs only while it runs.
89
89
  - A sandbox someone started again, sent a command or moved the stop of meanwhile is left running.
90
90
  - Every 5 minutes at the most: for anything more often, leave the sandbox running and loop inside it. `at` runs it once, at a date and time, as for a check you mean to come back to.
91
+ - With `at`, `deleteAfter: true` deletes the sandbox once the run's command exits 0, whether the run started it or not; the run says so in `deletedSandbox`. A run that fails, times out or does not run leaves it, so that it can be looked at. It takes a key that may delete the sandbox.
91
92
  - After 10 runs one after another fail, a schedule pauses itself and says why in `pausedReason`; resuming it clears that.
92
93
  - While a run still goes, the next is skipped. `overlap: "replace"` stops it instead, `"parallel"` runs both.
93
94
  - A run gets 10 minutes unless `timeoutMs` says, up to six hours. One that could not be made on time is `missed`, and never made up later.
@@ -308,9 +309,12 @@ A sandbox has no point for a moment it was stopped at, and its `reading` is then
308
309
  const billing = await agental.billing();
309
310
  console.log(billing.usedMicros, billing.topUpMicros);
310
311
 
311
- // What is sold: plans with the sizes each makes, top-ups and their bonus, the free month and the hourly prices.
312
+ // What is sold: plans with the sizes each makes, top-ups and their bonus, the free plan's credit and the hourly prices.
312
313
  const prices = await agental.prices();
313
314
 
315
+ // On the free plan, save a card first: nothing is charged, and the account is given $10 of credit once.
316
+ const { url: cardPage } = await agental.checkout({ card: true });
317
+
314
318
  // Start paying $500 for $537 of credits. A person pays at url: nothing is charged before.
315
319
  const { url } = await agental.checkout({ topUp: 500 });
316
320
 
@@ -318,15 +322,17 @@ const { url } = await agental.checkout({ topUp: 500 });
318
322
  await agental.setAutoReload(50);
319
323
  ```
320
324
 
325
+ An account starts on the free plan: nothing a month, and what it runs is paid from credits at the same list prices. It needs a card saved first, charged nothing, and is then given $10 of credit, once an account and once a card; `billing().free` says whether a card is saved (`cardSaved`) and whether the account has paid for anything (`paid`). Until a card is saved, a create throws an `ApiError` 402 `billing_required`; once the credits are used, 402 `out_of_credit`, and a top-up ends it. To go back to the free plan from a paid one, cancel it in the billing portal.
326
+
321
327
  `usedMicros` is the month's usage at list price, spent from the plan's credits first and then from the top-ups, which do not expire. A top-up is any whole number of dollars from $15 to $100,000. From $200 it adds a bonus: 2% at $200, growing evenly on a log scale to 25% at $10,000 and over, so $1,000 adds $1,115. `prices.topUps` lists what each offered amount adds, and `prices.topUpBonus` the curve. `checkout({ plan: "plan100" })` starts a plan the same way, or moves an account that has one at once, with `url` null and `changed` true. A checkout whose answer is lost is not sent again.
322
328
 
323
- `setAutoReload(dollars)` has the card saved at the last purchase charged for a top-up of that much, with tax, when the month's credits and the top-ups run out, and the credits added at once, before any sandbox is stopped: at most three times a day, and not again for a day after a card that would not pay. `setAutoReload(null)` turns it off, and `billing().autoReload` says how it is set. It needs a plan or a top-up bought first, which saves the card: `billing().canAutoReload` says whether it can be set, and the call answers `409 no_card` until then.
329
+ `setAutoReload(dollars)` has the card saved at the last purchase charged for a top-up of that much, with tax, when the month's credits and the top-ups run out, and the credits added at once, before any sandbox is stopped: at most three times a day, and not again for a day after a card that would not pay. `setAutoReload(null)` turns it off, and `billing().autoReload` says how it is set. It needs a card saved first: `billing().canAutoReload` says whether it can be set, and the call answers `409 no_card` until then.
324
330
 
325
- The $20 plan makes tiny and small sandboxes, the $100 plan medium ones too, and the $500 and $2000 plans every size: `prices.tiers` lists the plans, and each plan's `sizes` says which. A create, fork or template start of a size the plan does not make throws an `ApiError` with the status 402 and the code `size_not_on_plan`, whose message names the plan that makes it. A sandbox made before a change of plan still starts at its own size.
331
+ The free plan makes tiny and small sandboxes, the $100 plan medium ones too, and the $500 and $2000 plans every size: `prices.tiers` lists the plans, and each plan's `sizes` says which. A create, fork or template start of a size the plan does not make throws an `ApiError` with the status 402 and the code `size_not_on_plan`, whose message names the plan that makes it. A sandbox made before a change of plan still starts at its own size.
326
332
 
327
333
  ## How many you run, and how fast you start them
328
334
 
329
- 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 $20 plan runs 20 and bursts 20, 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.
335
+ 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.
330
336
 
331
337
  ```ts
332
338
  const burst = await agental.burst();
@@ -355,9 +361,8 @@ Where `enforced` is true, a start is refused with an `ApiError` of status 429 an
355
361
  - `running_limit_reached`: the account already runs its plan's running count. Stop something first.
356
362
  - `burst_fee_too_high`: the start would cost more than `maxBurstFeeMicros`.
357
363
  - `burst_budget_reached`: the fee would take this month's burst fees past the budget.
358
- - `burst_in_free_month`: the start would cost a fee, which the free month does not pay.
359
364
 
360
- With `maxBurstWaitMs`, a start refused with one of the last three waits `retryAfterSeconds`, if that is no longer than allowed, and is tried once more. It is off by default, and never waits for `running_limit_reached`. Burst fees come out of the plan's credits, then the top-ups, and `billing().burstMicros` is this month's.
365
+ With `maxBurstWaitMs`, a start refused with one of the last two waits `retryAfterSeconds`, if that is no longer than allowed, and is tried once more. It is off by default, and never waits for `running_limit_reached`. Burst fees come out of the plan's credits, then the top-ups, and `billing().burstMicros` is this month's.
361
366
 
362
367
  ## Send it to your own collector
363
368
 
package/dist/client.d.ts CHANGED
@@ -1,7 +1,114 @@
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, Size, Snapshot, Team, TeamRole, Telemetry, TelemetryTest, RunsOnRepository, RunsOnRepositories, Usage, Webhook } from "./types.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 } from "./types.js";
5
+ /** What a list of sandboxes is narrowed to. Each field left out narrows nothing; a list of values is any of them. */
6
+ export interface SandboxFilter {
7
+ /** Tags every sandbox has. */
8
+ tag?: string | readonly string[];
9
+ /** Tags no sandbox has. */
10
+ notTag?: string | readonly string[];
11
+ /** creating, running, stopped, error, restoring or migrating. */
12
+ status?: string | readonly string[];
13
+ /** true for only archived sandboxes, false for none. */
14
+ archived?: boolean;
15
+ size?: string | readonly string[];
16
+ region?: string | readonly string[];
17
+ templateId?: string | readonly string[];
18
+ /** Who made them, as createdBy says it. */
19
+ createdBy?: string | readonly string[];
20
+ createdAfter?: string | Date;
21
+ createdBefore?: string | Date;
22
+ stoppedBefore?: string | Date;
23
+ /** Their autoStopAt is before this. */
24
+ stopsBefore?: string | Date;
25
+ /** never: they have no autoStopAt. */
26
+ stops?: "never";
27
+ memoryKept?: boolean;
28
+ /** open, blocked or allowlist. */
29
+ outbound?: string | readonly string[];
30
+ /** What they are doing: low-cpu, disk-full, memory-full or not-read. Any of them. */
31
+ activity?: string | readonly string[];
32
+ /** None of these. */
33
+ notActivity?: string | readonly string[];
34
+ /** Each key at this value; "*" for any value, the key being set. */
35
+ metadata?: Record<string, string>;
36
+ /** No key at this value; "*" for the key not being set. */
37
+ notMetadata?: Record<string, string>;
38
+ /** Text found in the name or the id, case ignored. */
39
+ text?: string;
40
+ }
41
+ /** How a page of sandboxes is sorted. Only created and -created keep a walk through the pages exact while sandboxes change. */
42
+ export type SandboxSort = "created" | "-created" | "name" | "-name" | "status" | "-status" | "stopped" | "-stopped" | "cost" | "-cost" | "-cpu" | "-memory" | "-disk";
43
+ /** A page of sandboxes, and what to pass as cursor for the next one: null when this is the last. */
44
+ export interface SandboxPage {
45
+ sandboxes: Sandbox[];
46
+ nextCursor: string | null;
47
+ }
48
+ /** What a job does to each sandbox, and how. */
49
+ export type SandboxJobAction = "stop" | "start" | "archive" | "snapshot" | "auto-stop" | "labels" | "delete";
50
+ export interface SandboxJobOptions {
51
+ /** For stop: keep their memory too. */
52
+ keepMemory?: boolean;
53
+ /** For snapshot: its name. */
54
+ name?: string;
55
+ /** For auto-stop: when to stop, or null to take the time limit away. */
56
+ at?: string | Date | null;
57
+ /** For auto-stop: seconds from now, fixed to a time when the job is made. */
58
+ inSeconds?: number;
59
+ /** For labels: own tags to add and take away, own metadata to set (null takes a key away). */
60
+ addTags?: string[];
61
+ removeTags?: string[];
62
+ metadata?: Record<string, string | null>;
63
+ }
64
+ /**
65
+ * Jobs that act on many sandboxes at once. A preview fixes the sandboxes a filter finds; a job
66
+ * acts on exactly those, checking each again just before, and on no other.
67
+ */
68
+ declare class SandboxJobs {
69
+ private readonly http;
70
+ constructor(http: Http);
71
+ /** The sandboxes a job would act on, fixed, with how many, the first of them, and the money before and after. Nothing is done. */
72
+ preview(action: SandboxJobAction, select: {
73
+ filter: SandboxFilter;
74
+ } | {
75
+ ids: readonly string[];
76
+ }, options?: SandboxJobOptions): Promise<SandboxJobPreview>;
77
+ /**
78
+ * Makes a job from a preview, or from sandbox IDs named outright. Sent again with the same
79
+ * idempotencyKey, the same job is answered.
80
+ */
81
+ create(from: {
82
+ previewId: string;
83
+ confirm?: number;
84
+ } | {
85
+ action: SandboxJobAction;
86
+ ids: readonly string[];
87
+ options?: SandboxJobOptions;
88
+ confirm?: number;
89
+ }, options?: {
90
+ idempotencyKey?: string;
91
+ }): Promise<SandboxJob>;
92
+ get(id: string): Promise<SandboxJob>;
93
+ /** The organization's last 50 jobs, the newest first. */
94
+ list(): Promise<SandboxJob[]>;
95
+ /** A page of a job's items, in order, each with its state, why, and what it made or follows. */
96
+ items(id: string, options?: {
97
+ state?: string;
98
+ limit?: number;
99
+ cursor?: string;
100
+ }): Promise<{
101
+ items: SandboxJobItem[];
102
+ nextCursor: string | null;
103
+ }>;
104
+ /** No item that has not begun begins; those under way are followed to their end. */
105
+ cancel(id: string): Promise<SandboxJob>;
106
+ /** Reads the job until it has ended, telling onProgress each time, and answers it ended. */
107
+ wait(id: string, options?: {
108
+ onProgress?: (job: SandboxJob) => void;
109
+ signal?: AbortSignal;
110
+ }): Promise<SandboxJob>;
111
+ }
5
112
  declare class Sandboxes {
6
113
  private readonly http;
7
114
  constructor(http: Http);
@@ -14,14 +121,32 @@ declare class Sandboxes {
14
121
  /** One of your sandboxes, by its id. */
15
122
  get(id: string): Promise<Sandbox>;
16
123
  /**
17
- * Your sandboxes, stopped ones included. Given a tag, or several, only those with every
18
- * one of them; given metadata, only those with each key at that value. A template's
19
- * tags and metadata count.
124
+ * Every sandbox of yours that matches the filter, stopped ones included, oldest first. With
125
+ * no filter, every sandbox. It reads a page of 200 at a time and follows them to the end.
126
+ * Tags and metadata are judged as the sandbox shows them: its template's count, and its own
127
+ * value for a key wins over its template's.
20
128
  */
21
- list(filter?: {
22
- tag?: string | string[];
23
- metadata?: Record<string, string>;
24
- }): Promise<Sandbox[]>;
129
+ list(filter?: SandboxFilter): Promise<Sandbox[]>;
130
+ /**
131
+ * One page of the sandboxes that match the filter: up to limit of them, and nextCursor to pass
132
+ * as cursor, with the same sort, for the page after it. Sorted by anything but created, a
133
+ * sandbox that changes while the pages are read can be missed or met twice.
134
+ */
135
+ page(filter?: SandboxFilter, options?: {
136
+ sort?: SandboxSort;
137
+ limit?: number;
138
+ cursor?: string;
139
+ }): Promise<SandboxPage>;
140
+ /**
141
+ * How many sandboxes the filter finds and what they cost: an hour as each is charged now, and
142
+ * since midnight UTC today; what the running among them would cost stopped; and, for each field
143
+ * in facets (status, size, region, templateId, tag, outbound, metadataKeys, metadata.<key>), the
144
+ * count and hourly cost of each value. Money is in millionths of a US dollar. Spent is for the
145
+ * sandboxes found, not the account: the account's whole month is on billing.
146
+ */
147
+ summary(filter?: SandboxFilter, options?: {
148
+ facets?: readonly string[];
149
+ }): Promise<SandboxSummary>;
25
150
  /**
26
151
  * The mail of one sandbox, by the sandbox's id, without reading the sandbox. It asks
27
152
  * nothing by itself. It is the way in for a key made with only email.read and
@@ -131,6 +256,8 @@ export declare class Agental {
131
256
  readonly apiKeys: ApiKeys;
132
257
  /** The organizations the key's person is in, and the members and invites of a team. */
133
258
  readonly organizations: Organizations;
259
+ /** Jobs that act on many sandboxes at once: a preview fixes the set, a job acts on exactly it. */
260
+ readonly jobs: SandboxJobs;
134
261
  private readonly http;
135
262
  constructor(options?: AgentalOptions);
136
263
  /** The regions sandboxes can be made in now, the default first, with the sizes each has room for. */
@@ -146,35 +273,41 @@ export declare class Agental {
146
273
  /** What applies to every account here: how many sandboxes, how long one runs, whether ports get public addresses. */
147
274
  policy(): Promise<Policy>;
148
275
  /**
149
- * What is sold: the list price an hour of each size, the monthly plans, the top-ups offered
150
- * with what each adds, the range a top-up may be and its bonus, and the free month. It needs
151
- * no key.
276
+ * What is sold: the list price an hour of each size, the plans, the free one first, the
277
+ * top-ups offered with what each adds, the range a top-up may be and its bonus, and the free
278
+ * plan's credit and what it runs at once before the account has paid. It needs no key.
152
279
  */
153
280
  prices(): Promise<Prices>;
154
281
  /**
155
- * Where the account stands: its plan, in its free month or not, what it has used this month at list price,
156
- * what is left of its top-ups, and whether it may run a sandbox. Amounts are millionths of a US dollar.
282
+ * Where the account stands: its plan, the free one included, what it has used this month at list price,
283
+ * what is left of its credits, and whether it may run a sandbox. On the free plan, `free` says whether a
284
+ * card is saved and whether the account has paid for anything. Amounts are millionths of a US dollar.
157
285
  */
158
286
  billing(): Promise<Billing>;
159
287
  /**
160
- * Starts a purchase and gives the address of the payment page, for a person to open: a
161
- * plan, or a top-up of credits that do not expire, any whole number of US dollars
162
- * from 15 to 100,000. From $200 a top-up adds a bonus, 2% there and growing to 25% at
163
- * $10,000: $500 adds $537. prices() says what each adds.
164
- * An account that already has a plan and asks for another is moved to it at once: url is
165
- * null and changed is true. Nothing is charged until the person pays.
288
+ * Starts a purchase, or a card saved, and gives the address of the page, for a person to
289
+ * open: a plan; a top-up of credits that do not expire, any whole number of US dollars from
290
+ * 15 to 100,000; or `{ card: true }`, which saves a card for the free plan and charges
291
+ * nothing. Once the card is saved, the account is given the free plan's credit, once, and may
292
+ * run sandboxes; an account with a card saved already is refused with 409 card_saved.
293
+ * From $200 a top-up adds a bonus, 2% there and growing to 25% at $10,000: $500 adds $537.
294
+ * prices() says what each adds. An account that already has a plan and asks for another is
295
+ * moved to it at once: url is null and changed is true. Nothing is charged until the person
296
+ * pays. To go back to the free plan, cancel the plan in the billing portal.
166
297
  */
167
298
  checkout(purchase: {
168
- plan: "plan20" | "plan100" | "plan500" | "plan2000";
299
+ plan: "plan100" | "plan500" | "plan2000";
169
300
  } | {
170
301
  topUp: number;
302
+ } | {
303
+ card: true;
171
304
  }): Promise<Checkout>;
172
305
  /**
173
306
  * Sets the auto-reload, or turns it off with null: when the month's credits and the top-ups run
174
307
  * out, the card saved at the last purchase is charged for a top-up of this many US dollars, with
175
308
  * tax, and its credits are added at once, before any sandbox is stopped. At most three times a
176
- * day, and not again for a day after a card that would not pay. It needs a plan or a top-up
177
- * bought first, which saves the card: billing().canAutoReload says whether it can be set.
309
+ * day, and not again for a day after a card that would not pay. It needs a card saved
310
+ * first, by checkout(): billing().canAutoReload says whether it can be set.
178
311
  */
179
312
  setAutoReload(dollars: number | null): Promise<AutoReload>;
180
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. */
@@ -188,8 +321,9 @@ export declare class Agental {
188
321
  *
189
322
  * Where `enforced` is true, a create, fork or start past the running count throws an
190
323
  * `ApiError` 429 `running_limit_reached`; one faster than the free burst costs a burst fee,
191
- * and is refused with `burst_budget_reached` past the monthly budget or
192
- * `burst_in_free_month` in the free month. Amounts are millionths of a US dollar.
324
+ * 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.
193
327
  */
194
328
  burst(quote?: {
195
329
  size: Size;
package/dist/client.js CHANGED
@@ -1,6 +1,112 @@
1
- import { Http } from "./http.js";
1
+ import { Http, sleep } from "./http.js";
2
2
  import { CREATE_TIMEOUT_MS, Email, iso, made, makeSandbox, Sandbox } from "./sandbox.js";
3
3
  import { Templates } from "./template.js";
4
+ /** A filter as GET /v1/sandboxes and /v1/sandbox-summary take it. */
5
+ function filterQuery(filter) {
6
+ const query = {};
7
+ const many = (name, value) => {
8
+ if (value !== undefined) {
9
+ query[name] = typeof value === "string" ? value : [...value];
10
+ }
11
+ };
12
+ const time = (value) => (value instanceof Date ? value.toISOString() : value);
13
+ many("tag", filter.tag);
14
+ many("notTag", filter.notTag);
15
+ many("status", filter.status);
16
+ many("size", filter.size);
17
+ many("region", filter.region);
18
+ many("templateId", filter.templateId);
19
+ many("createdBy", filter.createdBy);
20
+ many("outbound", filter.outbound);
21
+ many("activity", filter.activity);
22
+ many("notActivity", filter.notActivity);
23
+ many("createdAfter", time(filter.createdAfter));
24
+ many("createdBefore", time(filter.createdBefore));
25
+ many("stoppedBefore", time(filter.stoppedBefore));
26
+ many("stopsBefore", time(filter.stopsBefore));
27
+ many("stops", filter.stops);
28
+ many("q", filter.text);
29
+ if (filter.archived !== undefined) {
30
+ query["archived"] = String(filter.archived);
31
+ }
32
+ if (filter.memoryKept !== undefined) {
33
+ query["memoryKept"] = String(filter.memoryKept);
34
+ }
35
+ for (const [key, value] of Object.entries(filter.metadata ?? {})) {
36
+ query[`metadata[${key}]`] = value;
37
+ }
38
+ for (const [key, value] of Object.entries(filter.notMetadata ?? {})) {
39
+ query[`notMetadata[${key}]`] = value;
40
+ }
41
+ return query;
42
+ }
43
+ /**
44
+ * Jobs that act on many sandboxes at once. A preview fixes the sandboxes a filter finds; a job
45
+ * acts on exactly those, checking each again just before, and on no other.
46
+ */
47
+ class SandboxJobs {
48
+ http;
49
+ constructor(http) {
50
+ this.http = http;
51
+ }
52
+ /** The sandboxes a job would act on, fixed, with how many, the first of them, and the money before and after. Nothing is done. */
53
+ async preview(action, select, options = {}) {
54
+ const body = {
55
+ action,
56
+ options: jobOptions(options),
57
+ select: "ids" in select ? { ids: [...select.ids] } : { filter: filterQuery(select.filter) },
58
+ };
59
+ return (await this.http.json({ method: "POST", path: "/v1/sandbox-jobs/preview", body })).body;
60
+ }
61
+ /**
62
+ * Makes a job from a preview, or from sandbox IDs named outright. Sent again with the same
63
+ * idempotencyKey, the same job is answered.
64
+ */
65
+ async create(from, options = {}) {
66
+ // A delete is made with confirm: the count its preview showed.
67
+ const confirm = from.confirm === undefined ? {} : { confirm: from.confirm };
68
+ const body = "previewId" in from ? { previewId: from.previewId, ...confirm } : { action: from.action, ids: [...from.ids], options: jobOptions(from.options ?? {}), ...confirm };
69
+ const key = options.idempotencyKey ?? `sdk-${crypto.randomUUID().replaceAll("-", "").slice(0, 12)}`;
70
+ return (await this.http.json({ method: "POST", path: "/v1/sandbox-jobs", body, headers: { "Idempotency-Key": key }, replay: true })).body;
71
+ }
72
+ async get(id) {
73
+ return (await this.http.json({ method: "GET", path: `/v1/sandbox-jobs/${encodeURIComponent(id)}`, replay: true })).body;
74
+ }
75
+ /** The organization's last 50 jobs, the newest first. */
76
+ async list() {
77
+ return (await this.http.json({ method: "GET", path: "/v1/sandbox-jobs", replay: true })).body.jobs;
78
+ }
79
+ /** A page of a job's items, in order, each with its state, why, and what it made or follows. */
80
+ async items(id, options = {}) {
81
+ const query = {};
82
+ if (options.state)
83
+ query["state"] = options.state;
84
+ if (options.limit !== undefined)
85
+ query["limit"] = String(options.limit);
86
+ if (options.cursor)
87
+ query["cursor"] = options.cursor;
88
+ return (await this.http.json({ method: "GET", path: `/v1/sandbox-jobs/${encodeURIComponent(id)}/items`, query, replay: true })).body;
89
+ }
90
+ /** No item that has not begun begins; those under way are followed to their end. */
91
+ async cancel(id) {
92
+ return (await this.http.json({ method: "POST", path: `/v1/sandbox-jobs/${encodeURIComponent(id)}/cancel`, replay: true })).body;
93
+ }
94
+ /** Reads the job until it has ended, telling onProgress each time, and answers it ended. */
95
+ async wait(id, options = {}) {
96
+ for (;;) {
97
+ const job = await this.get(id);
98
+ options.onProgress?.(job);
99
+ if (job.state !== "running") {
100
+ return job;
101
+ }
102
+ await sleep(this.http.pollIntervalMs, options.signal);
103
+ }
104
+ }
105
+ }
106
+ function jobOptions(options) {
107
+ const { at, ...rest } = options;
108
+ return { ...rest, ...(at === undefined ? {} : { at: at instanceof Date ? at.toISOString() : at }) };
109
+ }
4
110
  class Sandboxes {
5
111
  http;
6
112
  constructor(http) {
@@ -33,20 +139,54 @@ class Sandboxes {
33
139
  return new Sandbox(this.http, body);
34
140
  }
35
141
  /**
36
- * Your sandboxes, stopped ones included. Given a tag, or several, only those with every
37
- * one of them; given metadata, only those with each key at that value. A template's
38
- * tags and metadata count.
142
+ * Every sandbox of yours that matches the filter, stopped ones included, oldest first. With
143
+ * no filter, every sandbox. It reads a page of 200 at a time and follows them to the end.
144
+ * Tags and metadata are judged as the sandbox shows them: its template's count, and its own
145
+ * value for a key wins over its template's.
39
146
  */
40
147
  async list(filter = {}) {
41
- const query = {};
42
- if (filter.tag !== undefined) {
43
- query["tag"] = filter.tag;
44
- }
45
- for (const [key, value] of Object.entries(filter.metadata ?? {})) {
46
- query[`metadata[${key}]`] = value;
47
- }
148
+ const found = [];
149
+ let cursor = null;
150
+ do {
151
+ const page = await this.page(filter, { limit: 200, ...(cursor === null ? {} : { cursor }) });
152
+ found.push(...page.sandboxes);
153
+ cursor = page.nextCursor;
154
+ } while (cursor !== null);
155
+ return found;
156
+ }
157
+ /**
158
+ * One page of the sandboxes that match the filter: up to limit of them, and nextCursor to pass
159
+ * as cursor, with the same sort, for the page after it. Sorted by anything but created, a
160
+ * sandbox that changes while the pages are read can be missed or met twice.
161
+ */
162
+ async page(filter = {}, options = {}) {
163
+ const query = filterQuery(filter);
164
+ const many = (name, value) => {
165
+ if (value !== undefined) {
166
+ query[name] = value;
167
+ }
168
+ };
169
+ many("sort", options.sort);
170
+ many("limit", options.limit === undefined ? undefined : String(options.limit));
171
+ many("cursor", options.cursor);
48
172
  const { body } = await this.http.json({ method: "GET", path: "/v1/sandboxes", query, replay: true });
49
- return body.sandboxes.map((info) => new Sandbox(this.http, info));
173
+ // An API from before pages answers every sandbox at once, and no nextCursor.
174
+ return { sandboxes: body.sandboxes.map((info) => new Sandbox(this.http, info)), nextCursor: body.nextCursor ?? null };
175
+ }
176
+ /**
177
+ * How many sandboxes the filter finds and what they cost: an hour as each is charged now, and
178
+ * since midnight UTC today; what the running among them would cost stopped; and, for each field
179
+ * in facets (status, size, region, templateId, tag, outbound, metadataKeys, metadata.<key>), the
180
+ * count and hourly cost of each value. Money is in millionths of a US dollar. Spent is for the
181
+ * sandboxes found, not the account: the account's whole month is on billing.
182
+ */
183
+ async summary(filter = {}, options = {}) {
184
+ const query = filterQuery(filter);
185
+ if (options.facets !== undefined && options.facets.length > 0) {
186
+ query["facets"] = options.facets.join(",");
187
+ }
188
+ const { body } = await this.http.json({ method: "GET", path: "/v1/sandbox-summary", query, replay: true });
189
+ return body;
50
190
  }
51
191
  /**
52
192
  * The mail of one sandbox, by the sandbox's id, without reading the sandbox. It asks
@@ -209,6 +349,8 @@ export class Agental {
209
349
  apiKeys;
210
350
  /** The organizations the key's person is in, and the members and invites of a team. */
211
351
  organizations;
352
+ /** Jobs that act on many sandboxes at once: a preview fixes the set, a job acts on exactly it. */
353
+ jobs;
212
354
  http;
213
355
  constructor(options = {}) {
214
356
  this.http = new Http(options);
@@ -217,6 +359,7 @@ export class Agental {
217
359
  this.templates = new Templates(this.http);
218
360
  this.apiKeys = new ApiKeys(this.http);
219
361
  this.organizations = new Organizations(this.http);
362
+ this.jobs = new SandboxJobs(this.http);
220
363
  }
221
364
  /** The regions sandboxes can be made in now, the default first, with the sizes each has room for. */
222
365
  async regions() {
@@ -243,27 +386,31 @@ export class Agental {
243
386
  return (await this.http.json({ method: "GET", path: "/v1/policy", replay: true })).body;
244
387
  }
245
388
  /**
246
- * What is sold: the list price an hour of each size, the monthly plans, the top-ups offered
247
- * with what each adds, the range a top-up may be and its bonus, and the free month. It needs
248
- * no key.
389
+ * What is sold: the list price an hour of each size, the plans, the free one first, the
390
+ * top-ups offered with what each adds, the range a top-up may be and its bonus, and the free
391
+ * plan's credit and what it runs at once before the account has paid. It needs no key.
249
392
  */
250
393
  async prices() {
251
394
  return (await this.http.json({ method: "GET", path: "/v1/billing/plans", replay: true })).body;
252
395
  }
253
396
  /**
254
- * Where the account stands: its plan, in its free month or not, what it has used this month at list price,
255
- * what is left of its top-ups, and whether it may run a sandbox. Amounts are millionths of a US dollar.
397
+ * Where the account stands: its plan, the free one included, what it has used this month at list price,
398
+ * what is left of its credits, and whether it may run a sandbox. On the free plan, `free` says whether a
399
+ * card is saved and whether the account has paid for anything. Amounts are millionths of a US dollar.
256
400
  */
257
401
  async billing() {
258
402
  return (await this.http.json({ method: "GET", path: "/v1/billing", replay: true })).body;
259
403
  }
260
404
  /**
261
- * Starts a purchase and gives the address of the payment page, for a person to open: a
262
- * plan, or a top-up of credits that do not expire, any whole number of US dollars
263
- * from 15 to 100,000. From $200 a top-up adds a bonus, 2% there and growing to 25% at
264
- * $10,000: $500 adds $537. prices() says what each adds.
265
- * An account that already has a plan and asks for another is moved to it at once: url is
266
- * null and changed is true. Nothing is charged until the person pays.
405
+ * Starts a purchase, or a card saved, and gives the address of the page, for a person to
406
+ * open: a plan; a top-up of credits that do not expire, any whole number of US dollars from
407
+ * 15 to 100,000; or `{ card: true }`, which saves a card for the free plan and charges
408
+ * nothing. Once the card is saved, the account is given the free plan's credit, once, and may
409
+ * run sandboxes; an account with a card saved already is refused with 409 card_saved.
410
+ * From $200 a top-up adds a bonus, 2% there and growing to 25% at $10,000: $500 adds $537.
411
+ * prices() says what each adds. An account that already has a plan and asks for another is
412
+ * moved to it at once: url is null and changed is true. Nothing is charged until the person
413
+ * pays. To go back to the free plan, cancel the plan in the billing portal.
267
414
  */
268
415
  async checkout(purchase) {
269
416
  return (await this.http.json({ method: "POST", path: "/v1/billing/checkout", body: purchase })).body;
@@ -272,8 +419,8 @@ export class Agental {
272
419
  * Sets the auto-reload, or turns it off with null: when the month's credits and the top-ups run
273
420
  * out, the card saved at the last purchase is charged for a top-up of this many US dollars, with
274
421
  * tax, and its credits are added at once, before any sandbox is stopped. At most three times a
275
- * day, and not again for a day after a card that would not pay. It needs a plan or a top-up
276
- * bought first, which saves the card: billing().canAutoReload says whether it can be set.
422
+ * day, and not again for a day after a card that would not pay. It needs a card saved
423
+ * first, by checkout(): billing().canAutoReload says whether it can be set.
277
424
  */
278
425
  async setAutoReload(dollars) {
279
426
  return (await this.http.json({ method: "PUT", path: "/v1/billing/auto-reload", body: { dollars } })).body;
@@ -291,8 +438,9 @@ export class Agental {
291
438
  *
292
439
  * Where `enforced` is true, a create, fork or start past the running count throws an
293
440
  * `ApiError` 429 `running_limit_reached`; one faster than the free burst costs a burst fee,
294
- * and is refused with `burst_budget_reached` past the monthly budget or
295
- * `burst_in_free_month` in the free month. Amounts are millionths of a US dollar.
441
+ * and is refused with `burst_budget_reached` past the monthly budget.
442
+ * On the free plan, until the account has paid for something (`unpaid`), the running count
443
+ * is `free.unpaidUnits` of prices(). Amounts are millionths of a US dollar.
296
444
  */
297
445
  async burst(quote) {
298
446
  const query = { size: quote?.size, count: quote?.count?.toString() };
package/dist/errors.d.ts CHANGED
@@ -41,10 +41,9 @@ export declare class ApiError extends AgentalError {
41
41
  * Why a create, fork or start was refused with the status 429. running_limit_reached: the
42
42
  * account already runs as many sandboxes as its plan's runningUnits allows. burst_fee_too_high:
43
43
  * the start would cost more in burst fees than maxBurstFeeMicros allows. burst_budget_reached:
44
- * the fee would take this month's burst fees past the account's budget. burst_in_free_month:
45
- * the start would cost a fee, which the free month does not pay.
44
+ * the fee would take this month's burst fees past the account's budget.
46
45
  */
47
- export type BurstRefusalCode = "running_limit_reached" | "burst_fee_too_high" | "burst_budget_reached" | "burst_in_free_month";
46
+ export type BurstRefusalCode = "running_limit_reached" | "burst_fee_too_high" | "burst_budget_reached";
48
47
  /**
49
48
  * Something in front of the API answered, not the API: a 502, a 504, a 52x, or any error
50
49
  * with no code in it. The API was not reached or did not answer in time, so the request
package/dist/http.js CHANGED
@@ -9,7 +9,7 @@ function environment(name) {
9
9
  return value?.trim() || undefined;
10
10
  }
11
11
  /**
12
- * What every request says it is, where the runtime lets it: agental-typescript/0.1.0. A
12
+ * What every request says it is, where the runtime lets it: agental-typescript/0.2.0. A
13
13
  * browser sends its own User-Agent, and asked for another it would ask the API first whether
14
14
  * it may, so in a browser none is set.
15
15
  */
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { Agental } from "./client.js";
1
+ export { Agental, type SandboxFilter, type SandboxJobAction, type SandboxJobOptions, type SandboxPage, type SandboxSort } from "./client.js";
2
2
  export { AgentalError, ApiError, ConnectionError, ProxyError, TimeoutError } from "./errors.js";
3
3
  export type { BurstRefusalCode } from "./errors.js";
4
4
  export type { AgentalOptions } from "./http.js";
@@ -6,5 +6,5 @@ export { Browser, Commands, Desktop, Email, Files, Sandbox, Schedules, Ssh } fro
6
6
  export { Secrets, Template, Templates } from "./template.js";
7
7
  export type { TemplateChanges } from "./template.js";
8
8
  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, EmailMessage, EmailMessageList, EmailMessageSummary, ExecResult, HiddenVariable, HostRoute, Invite, Me, Member, Organization, MetricsAtMoment, MetricsReading, NetworkRule, Operation, PlainVariable, Plan, Policy, Prices, RunningOverTime, SandboxAutoStop, SandboxEmail, SandboxInfo, 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, TemplateRepo, TemplateSandbox, TemplateStart, TemplateSsh, Usage, Webhook, WebhookDelivery, } from "./types.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, 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";
10
10
  export { verifyWebhook } from "./webhooks.js";