agental-sdk 0.1.0 → 0.2.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
@@ -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,110 @@
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
+ /** Each key at this value; "*" for any value, the key being set. */
31
+ metadata?: Record<string, string>;
32
+ /** No key at this value; "*" for the key not being set. */
33
+ notMetadata?: Record<string, string>;
34
+ /** Text found in the name or the id, case ignored. */
35
+ text?: string;
36
+ }
37
+ /** How a page of sandboxes is sorted. Only created and -created keep a walk through the pages exact while sandboxes change. */
38
+ export type SandboxSort = "created" | "-created" | "name" | "-name" | "status" | "-status" | "stopped" | "-stopped" | "cost" | "-cost";
39
+ /** A page of sandboxes, and what to pass as cursor for the next one: null when this is the last. */
40
+ export interface SandboxPage {
41
+ sandboxes: Sandbox[];
42
+ nextCursor: string | null;
43
+ }
44
+ /** What a job does to each sandbox, and how. */
45
+ export type SandboxJobAction = "stop" | "start" | "archive" | "snapshot" | "auto-stop" | "labels" | "delete";
46
+ export interface SandboxJobOptions {
47
+ /** For stop: keep their memory too. */
48
+ keepMemory?: boolean;
49
+ /** For snapshot: its name. */
50
+ name?: string;
51
+ /** For auto-stop: when to stop, or null to take the time limit away. */
52
+ at?: string | Date | null;
53
+ /** For auto-stop: seconds from now, fixed to a time when the job is made. */
54
+ inSeconds?: number;
55
+ /** For labels: own tags to add and take away, own metadata to set (null takes a key away). */
56
+ addTags?: string[];
57
+ removeTags?: string[];
58
+ metadata?: Record<string, string | null>;
59
+ }
60
+ /**
61
+ * Jobs that act on many sandboxes at once. A preview fixes the sandboxes a filter finds; a job
62
+ * acts on exactly those, checking each again just before, and on no other.
63
+ */
64
+ declare class SandboxJobs {
65
+ private readonly http;
66
+ constructor(http: Http);
67
+ /** The sandboxes a job would act on, fixed, with how many, the first of them, and the money before and after. Nothing is done. */
68
+ preview(action: SandboxJobAction, select: {
69
+ filter: SandboxFilter;
70
+ } | {
71
+ ids: readonly string[];
72
+ }, options?: SandboxJobOptions): Promise<SandboxJobPreview>;
73
+ /**
74
+ * Makes a job from a preview, or from sandbox IDs named outright. Sent again with the same
75
+ * idempotencyKey, the same job is answered.
76
+ */
77
+ create(from: {
78
+ previewId: string;
79
+ confirm?: number;
80
+ } | {
81
+ action: SandboxJobAction;
82
+ ids: readonly string[];
83
+ options?: SandboxJobOptions;
84
+ confirm?: number;
85
+ }, options?: {
86
+ idempotencyKey?: string;
87
+ }): Promise<SandboxJob>;
88
+ get(id: string): Promise<SandboxJob>;
89
+ /** The organization's last 50 jobs, the newest first. */
90
+ list(): Promise<SandboxJob[]>;
91
+ /** A page of a job's items, in order, each with its state, why, and what it made or follows. */
92
+ items(id: string, options?: {
93
+ state?: string;
94
+ limit?: number;
95
+ cursor?: string;
96
+ }): Promise<{
97
+ items: SandboxJobItem[];
98
+ nextCursor: string | null;
99
+ }>;
100
+ /** No item that has not begun begins; those under way are followed to their end. */
101
+ cancel(id: string): Promise<SandboxJob>;
102
+ /** Reads the job until it has ended, telling onProgress each time, and answers it ended. */
103
+ wait(id: string, options?: {
104
+ onProgress?: (job: SandboxJob) => void;
105
+ signal?: AbortSignal;
106
+ }): Promise<SandboxJob>;
107
+ }
5
108
  declare class Sandboxes {
6
109
  private readonly http;
7
110
  constructor(http: Http);
@@ -14,14 +117,32 @@ declare class Sandboxes {
14
117
  /** One of your sandboxes, by its id. */
15
118
  get(id: string): Promise<Sandbox>;
16
119
  /**
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.
120
+ * Every sandbox of yours that matches the filter, stopped ones included, oldest first. With
121
+ * no filter, every sandbox. It reads a page of 200 at a time and follows them to the end.
122
+ * Tags and metadata are judged as the sandbox shows them: its template's count, and its own
123
+ * value for a key wins over its template's.
20
124
  */
21
- list(filter?: {
22
- tag?: string | string[];
23
- metadata?: Record<string, string>;
24
- }): Promise<Sandbox[]>;
125
+ list(filter?: SandboxFilter): Promise<Sandbox[]>;
126
+ /**
127
+ * One page of the sandboxes that match the filter: up to limit of them, and nextCursor to pass
128
+ * as cursor, with the same sort, for the page after it. Sorted by anything but created, a
129
+ * sandbox that changes while the pages are read can be missed or met twice.
130
+ */
131
+ page(filter?: SandboxFilter, options?: {
132
+ sort?: SandboxSort;
133
+ limit?: number;
134
+ cursor?: string;
135
+ }): Promise<SandboxPage>;
136
+ /**
137
+ * How many sandboxes the filter finds and what they cost: an hour as each is charged now, and
138
+ * since midnight UTC today; what the running among them would cost stopped; and, for each field
139
+ * in facets (status, size, region, templateId, tag, outbound, metadataKeys, metadata.<key>), the
140
+ * count and hourly cost of each value. Money is in millionths of a US dollar. Spent is for the
141
+ * sandboxes found, not the account: the account's whole month is on billing.
142
+ */
143
+ summary(filter?: SandboxFilter, options?: {
144
+ facets?: readonly string[];
145
+ }): Promise<SandboxSummary>;
25
146
  /**
26
147
  * The mail of one sandbox, by the sandbox's id, without reading the sandbox. It asks
27
148
  * nothing by itself. It is the way in for a key made with only email.read and
@@ -131,6 +252,8 @@ export declare class Agental {
131
252
  readonly apiKeys: ApiKeys;
132
253
  /** The organizations the key's person is in, and the members and invites of a team. */
133
254
  readonly organizations: Organizations;
255
+ /** Jobs that act on many sandboxes at once: a preview fixes the set, a job acts on exactly it. */
256
+ readonly jobs: SandboxJobs;
134
257
  private readonly http;
135
258
  constructor(options?: AgentalOptions);
136
259
  /** The regions sandboxes can be made in now, the default first, with the sizes each has room for. */
@@ -146,35 +269,41 @@ export declare class Agental {
146
269
  /** What applies to every account here: how many sandboxes, how long one runs, whether ports get public addresses. */
147
270
  policy(): Promise<Policy>;
148
271
  /**
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.
272
+ * What is sold: the list price an hour of each size, the plans, the free one first, the
273
+ * top-ups offered with what each adds, the range a top-up may be and its bonus, and the free
274
+ * plan's credit and what it runs at once before the account has paid. It needs no key.
152
275
  */
153
276
  prices(): Promise<Prices>;
154
277
  /**
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.
278
+ * Where the account stands: its plan, the free one included, what it has used this month at list price,
279
+ * what is left of its credits, and whether it may run a sandbox. On the free plan, `free` says whether a
280
+ * card is saved and whether the account has paid for anything. Amounts are millionths of a US dollar.
157
281
  */
158
282
  billing(): Promise<Billing>;
159
283
  /**
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.
284
+ * Starts a purchase, or a card saved, and gives the address of the page, for a person to
285
+ * open: a plan; a top-up of credits that do not expire, any whole number of US dollars from
286
+ * 15 to 100,000; or `{ card: true }`, which saves a card for the free plan and charges
287
+ * nothing. Once the card is saved, the account is given the free plan's credit, once, and may
288
+ * run sandboxes; an account with a card saved already is refused with 409 card_saved.
289
+ * From $200 a top-up adds a bonus, 2% there and growing to 25% at $10,000: $500 adds $537.
290
+ * prices() says what each adds. An account that already has a plan and asks for another is
291
+ * moved to it at once: url is null and changed is true. Nothing is charged until the person
292
+ * pays. To go back to the free plan, cancel the plan in the billing portal.
166
293
  */
167
294
  checkout(purchase: {
168
- plan: "plan20" | "plan100" | "plan500" | "plan2000";
295
+ plan: "plan100" | "plan500" | "plan2000";
169
296
  } | {
170
297
  topUp: number;
298
+ } | {
299
+ card: true;
171
300
  }): Promise<Checkout>;
172
301
  /**
173
302
  * Sets the auto-reload, or turns it off with null: when the month's credits and the top-ups run
174
303
  * out, the card saved at the last purchase is charged for a top-up of this many US dollars, with
175
304
  * 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.
305
+ * day, and not again for a day after a card that would not pay. It needs a card saved
306
+ * first, by checkout(): billing().canAutoReload says whether it can be set.
178
307
  */
179
308
  setAutoReload(dollars: number | null): Promise<AutoReload>;
180
309
  /** 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 +317,9 @@ export declare class Agental {
188
317
  *
189
318
  * Where `enforced` is true, a create, fork or start past the running count throws an
190
319
  * `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.
320
+ * and is refused with `burst_budget_reached` past the monthly budget.
321
+ * On the free plan, until the account has paid for something (`unpaid`), the running count
322
+ * is `free.unpaidUnits` of prices(). Amounts are millionths of a US dollar.
193
323
  */
194
324
  burst(quote?: {
195
325
  size: Size;
package/dist/client.js CHANGED
@@ -1,6 +1,110 @@
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("createdAfter", time(filter.createdAfter));
22
+ many("createdBefore", time(filter.createdBefore));
23
+ many("stoppedBefore", time(filter.stoppedBefore));
24
+ many("stopsBefore", time(filter.stopsBefore));
25
+ many("stops", filter.stops);
26
+ many("q", filter.text);
27
+ if (filter.archived !== undefined) {
28
+ query["archived"] = String(filter.archived);
29
+ }
30
+ if (filter.memoryKept !== undefined) {
31
+ query["memoryKept"] = String(filter.memoryKept);
32
+ }
33
+ for (const [key, value] of Object.entries(filter.metadata ?? {})) {
34
+ query[`metadata[${key}]`] = value;
35
+ }
36
+ for (const [key, value] of Object.entries(filter.notMetadata ?? {})) {
37
+ query[`notMetadata[${key}]`] = value;
38
+ }
39
+ return query;
40
+ }
41
+ /**
42
+ * Jobs that act on many sandboxes at once. A preview fixes the sandboxes a filter finds; a job
43
+ * acts on exactly those, checking each again just before, and on no other.
44
+ */
45
+ class SandboxJobs {
46
+ http;
47
+ constructor(http) {
48
+ this.http = http;
49
+ }
50
+ /** The sandboxes a job would act on, fixed, with how many, the first of them, and the money before and after. Nothing is done. */
51
+ async preview(action, select, options = {}) {
52
+ const body = {
53
+ action,
54
+ options: jobOptions(options),
55
+ select: "ids" in select ? { ids: [...select.ids] } : { filter: filterQuery(select.filter) },
56
+ };
57
+ return (await this.http.json({ method: "POST", path: "/v1/sandbox-jobs/preview", body })).body;
58
+ }
59
+ /**
60
+ * Makes a job from a preview, or from sandbox IDs named outright. Sent again with the same
61
+ * idempotencyKey, the same job is answered.
62
+ */
63
+ async create(from, options = {}) {
64
+ // A delete is made with confirm: the count its preview showed.
65
+ const confirm = from.confirm === undefined ? {} : { confirm: from.confirm };
66
+ const body = "previewId" in from ? { previewId: from.previewId, ...confirm } : { action: from.action, ids: [...from.ids], options: jobOptions(from.options ?? {}), ...confirm };
67
+ const key = options.idempotencyKey ?? `sdk-${crypto.randomUUID().replaceAll("-", "").slice(0, 12)}`;
68
+ return (await this.http.json({ method: "POST", path: "/v1/sandbox-jobs", body, headers: { "Idempotency-Key": key }, replay: true })).body;
69
+ }
70
+ async get(id) {
71
+ return (await this.http.json({ method: "GET", path: `/v1/sandbox-jobs/${encodeURIComponent(id)}`, replay: true })).body;
72
+ }
73
+ /** The organization's last 50 jobs, the newest first. */
74
+ async list() {
75
+ return (await this.http.json({ method: "GET", path: "/v1/sandbox-jobs", replay: true })).body.jobs;
76
+ }
77
+ /** A page of a job's items, in order, each with its state, why, and what it made or follows. */
78
+ async items(id, options = {}) {
79
+ const query = {};
80
+ if (options.state)
81
+ query["state"] = options.state;
82
+ if (options.limit !== undefined)
83
+ query["limit"] = String(options.limit);
84
+ if (options.cursor)
85
+ query["cursor"] = options.cursor;
86
+ return (await this.http.json({ method: "GET", path: `/v1/sandbox-jobs/${encodeURIComponent(id)}/items`, query, replay: true })).body;
87
+ }
88
+ /** No item that has not begun begins; those under way are followed to their end. */
89
+ async cancel(id) {
90
+ return (await this.http.json({ method: "POST", path: `/v1/sandbox-jobs/${encodeURIComponent(id)}/cancel`, replay: true })).body;
91
+ }
92
+ /** Reads the job until it has ended, telling onProgress each time, and answers it ended. */
93
+ async wait(id, options = {}) {
94
+ for (;;) {
95
+ const job = await this.get(id);
96
+ options.onProgress?.(job);
97
+ if (job.state !== "running") {
98
+ return job;
99
+ }
100
+ await sleep(this.http.pollIntervalMs, options.signal);
101
+ }
102
+ }
103
+ }
104
+ function jobOptions(options) {
105
+ const { at, ...rest } = options;
106
+ return { ...rest, ...(at === undefined ? {} : { at: at instanceof Date ? at.toISOString() : at }) };
107
+ }
4
108
  class Sandboxes {
5
109
  http;
6
110
  constructor(http) {
@@ -33,20 +137,54 @@ class Sandboxes {
33
137
  return new Sandbox(this.http, body);
34
138
  }
35
139
  /**
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.
140
+ * Every sandbox of yours that matches the filter, stopped ones included, oldest first. With
141
+ * no filter, every sandbox. It reads a page of 200 at a time and follows them to the end.
142
+ * Tags and metadata are judged as the sandbox shows them: its template's count, and its own
143
+ * value for a key wins over its template's.
39
144
  */
40
145
  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
- }
146
+ const found = [];
147
+ let cursor = null;
148
+ do {
149
+ const page = await this.page(filter, { limit: 200, ...(cursor === null ? {} : { cursor }) });
150
+ found.push(...page.sandboxes);
151
+ cursor = page.nextCursor;
152
+ } while (cursor !== null);
153
+ return found;
154
+ }
155
+ /**
156
+ * One page of the sandboxes that match the filter: up to limit of them, and nextCursor to pass
157
+ * as cursor, with the same sort, for the page after it. Sorted by anything but created, a
158
+ * sandbox that changes while the pages are read can be missed or met twice.
159
+ */
160
+ async page(filter = {}, options = {}) {
161
+ const query = filterQuery(filter);
162
+ const many = (name, value) => {
163
+ if (value !== undefined) {
164
+ query[name] = value;
165
+ }
166
+ };
167
+ many("sort", options.sort);
168
+ many("limit", options.limit === undefined ? undefined : String(options.limit));
169
+ many("cursor", options.cursor);
48
170
  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));
171
+ // An API from before pages answers every sandbox at once, and no nextCursor.
172
+ return { sandboxes: body.sandboxes.map((info) => new Sandbox(this.http, info)), nextCursor: body.nextCursor ?? null };
173
+ }
174
+ /**
175
+ * How many sandboxes the filter finds and what they cost: an hour as each is charged now, and
176
+ * since midnight UTC today; what the running among them would cost stopped; and, for each field
177
+ * in facets (status, size, region, templateId, tag, outbound, metadataKeys, metadata.<key>), the
178
+ * count and hourly cost of each value. Money is in millionths of a US dollar. Spent is for the
179
+ * sandboxes found, not the account: the account's whole month is on billing.
180
+ */
181
+ async summary(filter = {}, options = {}) {
182
+ const query = filterQuery(filter);
183
+ if (options.facets !== undefined && options.facets.length > 0) {
184
+ query["facets"] = options.facets.join(",");
185
+ }
186
+ const { body } = await this.http.json({ method: "GET", path: "/v1/sandbox-summary", query, replay: true });
187
+ return body;
50
188
  }
51
189
  /**
52
190
  * The mail of one sandbox, by the sandbox's id, without reading the sandbox. It asks
@@ -209,6 +347,8 @@ export class Agental {
209
347
  apiKeys;
210
348
  /** The organizations the key's person is in, and the members and invites of a team. */
211
349
  organizations;
350
+ /** Jobs that act on many sandboxes at once: a preview fixes the set, a job acts on exactly it. */
351
+ jobs;
212
352
  http;
213
353
  constructor(options = {}) {
214
354
  this.http = new Http(options);
@@ -217,6 +357,7 @@ export class Agental {
217
357
  this.templates = new Templates(this.http);
218
358
  this.apiKeys = new ApiKeys(this.http);
219
359
  this.organizations = new Organizations(this.http);
360
+ this.jobs = new SandboxJobs(this.http);
220
361
  }
221
362
  /** The regions sandboxes can be made in now, the default first, with the sizes each has room for. */
222
363
  async regions() {
@@ -243,27 +384,31 @@ export class Agental {
243
384
  return (await this.http.json({ method: "GET", path: "/v1/policy", replay: true })).body;
244
385
  }
245
386
  /**
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.
387
+ * What is sold: the list price an hour of each size, the plans, the free one first, the
388
+ * top-ups offered with what each adds, the range a top-up may be and its bonus, and the free
389
+ * plan's credit and what it runs at once before the account has paid. It needs no key.
249
390
  */
250
391
  async prices() {
251
392
  return (await this.http.json({ method: "GET", path: "/v1/billing/plans", replay: true })).body;
252
393
  }
253
394
  /**
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.
395
+ * Where the account stands: its plan, the free one included, what it has used this month at list price,
396
+ * what is left of its credits, and whether it may run a sandbox. On the free plan, `free` says whether a
397
+ * card is saved and whether the account has paid for anything. Amounts are millionths of a US dollar.
256
398
  */
257
399
  async billing() {
258
400
  return (await this.http.json({ method: "GET", path: "/v1/billing", replay: true })).body;
259
401
  }
260
402
  /**
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.
403
+ * Starts a purchase, or a card saved, and gives the address of the page, for a person to
404
+ * open: a plan; a top-up of credits that do not expire, any whole number of US dollars from
405
+ * 15 to 100,000; or `{ card: true }`, which saves a card for the free plan and charges
406
+ * nothing. Once the card is saved, the account is given the free plan's credit, once, and may
407
+ * run sandboxes; an account with a card saved already is refused with 409 card_saved.
408
+ * From $200 a top-up adds a bonus, 2% there and growing to 25% at $10,000: $500 adds $537.
409
+ * prices() says what each adds. An account that already has a plan and asks for another is
410
+ * moved to it at once: url is null and changed is true. Nothing is charged until the person
411
+ * pays. To go back to the free plan, cancel the plan in the billing portal.
267
412
  */
268
413
  async checkout(purchase) {
269
414
  return (await this.http.json({ method: "POST", path: "/v1/billing/checkout", body: purchase })).body;
@@ -272,8 +417,8 @@ export class Agental {
272
417
  * Sets the auto-reload, or turns it off with null: when the month's credits and the top-ups run
273
418
  * out, the card saved at the last purchase is charged for a top-up of this many US dollars, with
274
419
  * 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.
420
+ * day, and not again for a day after a card that would not pay. It needs a card saved
421
+ * first, by checkout(): billing().canAutoReload says whether it can be set.
277
422
  */
278
423
  async setAutoReload(dollars) {
279
424
  return (await this.http.json({ method: "PUT", path: "/v1/billing/auto-reload", body: { dollars } })).body;
@@ -291,8 +436,9 @@ export class Agental {
291
436
  *
292
437
  * Where `enforced` is true, a create, fork or start past the running count throws an
293
438
  * `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.
439
+ * and is refused with `burst_budget_reached` past the monthly budget.
440
+ * On the free plan, until the account has paid for something (`unpaid`), the running count
441
+ * is `free.unpaidUnits` of prices(). Amounts are millionths of a US dollar.
296
442
  */
297
443
  async burst(quote) {
298
444
  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";