@altenginenet/sdk 0.0.0-stage → 0.1.2

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.
@@ -0,0 +1,1951 @@
1
+ import { T as TokenRequest, a as TokenResponse, P as PresenceResponse } from './socket-DqIm8vll.js';
2
+ export { C as ChannelMessage, b as ChannelSocket, c as ChannelSocketOptions, d as PresenceMember, e as PublishMode, S as SocketState, f as SocketToken } from './socket-DqIm8vll.js';
3
+ import { A as AuthClient } from './client-rCIrl668.js';
4
+ export { a as AuthClientOptions, b as AuthConfig, c as AuthField, d as AuthSession, e as AuthTokens, f as AuthUser, M as MfaChallenge, S as SignInResult, g as StoredSession, T as TokenStorage, h as defaultStorage, m as memoryStorage } from './client-rCIrl668.js';
5
+
6
+ /** Side-effect-free constants and path helpers shared by every client.
7
+ *
8
+ * These live apart from `http.ts` on purpose: the browser-safe entry points
9
+ * (`@altenginenet/sdk/auth`, `@altenginenet/sdk/channel`) need the base URLs and path
10
+ * encoders but must NOT pull in the API-key transport, which is a backend
11
+ * credential path that has no business in a browser bundle. */
12
+ /** Production API origin used when no override is given. */
13
+ declare const DEFAULT_BASE_URL = "https://api.altengine.net";
14
+ /** Where `altengine dev` (the local emulator) listens by default. */
15
+ declare const DEV_BASE_URL = "http://127.0.0.1:9191";
16
+
17
+ interface RetryOptions {
18
+ /** Total attempts including the first (default 3). Set 1 to disable retries. */
19
+ maxAttempts?: number;
20
+ /** Base backoff delay in ms (default 250); doubles per attempt with jitter. */
21
+ baseDelayMs?: number;
22
+ /** Backoff ceiling in ms (default 4000). */
23
+ maxDelayMs?: number;
24
+ }
25
+
26
+ /** Supplies a per-request end-user bearer token. `AuthClient` implements this, so
27
+ * `new AltEngine({ auth })` sends the signed-in user's `id_token` (kept fresh)
28
+ * rather than an org API key. */
29
+ interface TokenProvider {
30
+ getToken(): Promise<string | undefined> | string | undefined;
31
+ }
32
+ interface ClientOptions {
33
+ /** API origin override. Resolution order: this option → `dev: true` →
34
+ * `ALTENGINE_URL` env var → `https://api.altengine.net` (production). */
35
+ baseUrl?: string;
36
+ /** Target the local emulator (`altengine dev`) at `http://127.0.0.1:9191`. */
37
+ dev?: boolean;
38
+ /** Org API key (`Authorization: Bearer`). Falls back to the `ALTENGINE_API_KEY`
39
+ * env var; omit only for token-based flows. */
40
+ apiKey?: string;
41
+ /** End-user identity source (an `AuthClient`). When it yields a token, it takes
42
+ * precedence over `apiKey` — an org key is a backend credential and must not be
43
+ * shipped to a browser; the signed-in user's `id_token` is what a client-side
44
+ * app sends, and access rules scope it to that user's own rows. */
45
+ auth?: TokenProvider;
46
+ /** Custom fetch (tests, polyfills). Defaults to `globalThis.fetch`. */
47
+ fetch?: typeof globalThis.fetch;
48
+ /** Per-request timeout in ms (default 30000). */
49
+ timeoutMs?: number;
50
+ /** Default retry policy for retryable failures (429/502/503/504/network). */
51
+ retry?: RetryOptions;
52
+ }
53
+ interface RequestOptions {
54
+ query?: Record<string, string | number | boolean | undefined>;
55
+ body?: unknown;
56
+ headers?: Record<string, string>;
57
+ /** Override the client retry policy; `false` disables retries for this call
58
+ * (used for non-idempotent endpoints: transaction, publish). */
59
+ retry?: RetryOptions | false;
60
+ /** Override the client's request timeout for this call (a long-poll holds the request open
61
+ * for longer than an ordinary call takes). */
62
+ timeoutMs?: number;
63
+ /** Error statuses whose JSON body is still the answer — a task add where every name was
64
+ * already taken is a 409 carrying the per-task results. */
65
+ acceptStatus?: number[];
66
+ }
67
+ /** Minimal JSON-over-fetch transport shared by all service clients. */
68
+ declare class Http {
69
+ readonly baseUrl: string;
70
+ private readonly apiKey?;
71
+ private readonly auth?;
72
+ private readonly fetchImpl;
73
+ private readonly timeoutMs;
74
+ private readonly retry;
75
+ constructor(opts?: ClientOptions);
76
+ url(path: string, query?: RequestOptions["query"]): string;
77
+ request<T>(method: string, path: string, opts?: RequestOptions): Promise<T>;
78
+ /**
79
+ * Fetch a URL that is NOT the altengine API — a presigned upload or download link.
80
+ *
81
+ * CARRIES NO CREDENTIAL OF OURS. A presigned URL's signature is the whole credential, and an
82
+ * org API key sent to object storage is an org API key handed to a third party. The bytes go
83
+ * straight between the caller and storage; nothing is proxied through the API.
84
+ *
85
+ * The client's request timeout does not apply either — a 20 GB upload is not a control-plane
86
+ * call. Bound it with `init.signal`.
87
+ */
88
+ transfer(url: string, init?: RequestInit): Promise<Response>;
89
+ private once;
90
+ }
91
+
92
+ /** Wire types for the datastore data plane. Field names are wire-verbatim
93
+ * (snake_case) — they double as the API reference. */
94
+ type Key = string | number;
95
+ interface DatastoreDocument<T = unknown> {
96
+ key: string;
97
+ data: T;
98
+ created: number;
99
+ updated: number;
100
+ /** Joined documents keyed by the query's `join[].as` names. */
101
+ joins?: Record<string, unknown>;
102
+ }
103
+ interface PutDocument<T = unknown> {
104
+ /** Omit to use the instance's auto-id strategy. Numeric keys are stored as
105
+ * decimal strings (`5` ≡ `"5"`). */
106
+ key?: Key;
107
+ data: T;
108
+ }
109
+ type FilterOp = "=" | "!=" | "<" | "<=" | ">" | ">=" | "in";
110
+ interface Filter {
111
+ /** Dot-path into the document (`a.b.c`, depth ≤ 8) or `__key__` / `__created__`
112
+ * / `__updated__`. */
113
+ field: string;
114
+ op: FilterOp;
115
+ value: unknown;
116
+ }
117
+ interface Order {
118
+ field: string;
119
+ dir?: "asc" | "desc";
120
+ }
121
+ interface Join {
122
+ /** Name the joined document appears under in `joins`. */
123
+ as: string;
124
+ collection: string;
125
+ /** Field on the queried document whose value is the joined document's key. */
126
+ local_field: string;
127
+ }
128
+ interface QueryRequest {
129
+ where?: Filter[];
130
+ order?: Order[];
131
+ /** Default 25, max 500. */
132
+ limit?: number;
133
+ cursor?: string;
134
+ keys_only?: boolean;
135
+ join?: Join[];
136
+ }
137
+ /** Describes an index the instance auto-created to serve a query (present
138
+ * only on the request that triggered the build). */
139
+ interface AutoIndexInfo {
140
+ fields: string[];
141
+ rows_written: number;
142
+ }
143
+ interface QueryResult<T = unknown> {
144
+ documents?: DatastoreDocument<T>[];
145
+ keys?: string[];
146
+ /** Pass back to continue; `null` when exhausted. */
147
+ cursor: string | null;
148
+ /** Present when the instance auto-created an index to serve this query. */
149
+ auto_indexed?: AutoIndexInfo;
150
+ }
151
+ type MetricFn = "count" | "sum" | "avg" | "min" | "max";
152
+ interface Metric {
153
+ fn: MetricFn;
154
+ /** Required for all fns except `count`. */
155
+ field?: string;
156
+ /** Result name; defaults to `fn` or `fn_field`. */
157
+ as?: string;
158
+ }
159
+ interface AggregateRequest {
160
+ where?: Filter[];
161
+ group?: string[];
162
+ metrics: Metric[];
163
+ order?: Order[];
164
+ limit?: number;
165
+ }
166
+ interface AggregateGroup {
167
+ group: Record<string, unknown>;
168
+ metrics: Record<string, number | null>;
169
+ }
170
+ interface AggregateResult {
171
+ groups: AggregateGroup[];
172
+ auto_indexed?: AutoIndexInfo;
173
+ }
174
+ /** One atomic transaction operation. All ops in a transaction apply atomically
175
+ * within a single namespace; a failed `check` aborts with a 409. */
176
+ type TxnOp = {
177
+ op: "put";
178
+ collection: string;
179
+ key?: Key;
180
+ data: unknown;
181
+ } | {
182
+ op: "delete";
183
+ collection: string;
184
+ key: Key;
185
+ } | {
186
+ op: "mutate";
187
+ collection: string;
188
+ key: Key;
189
+ set?: Record<string, unknown>;
190
+ increment?: Record<string, number>;
191
+ remove?: string[];
192
+ upsert?: boolean;
193
+ } | {
194
+ op: "check";
195
+ collection: string;
196
+ key: Key;
197
+ exists: boolean;
198
+ };
199
+ interface TransactionResult {
200
+ /** Per-op resulting key; `null` for delete/check ops. */
201
+ keys: (string | null)[];
202
+ }
203
+ interface IndexSpec {
204
+ id: number;
205
+ collection: string;
206
+ /** `"field"` or `"field:asc"` / `"field:desc"`, max 8. */
207
+ fields: string[];
208
+ unique: boolean;
209
+ }
210
+ interface CreateIndexRequest {
211
+ fields: string[];
212
+ unique?: boolean;
213
+ }
214
+ interface NamespaceInfo {
215
+ namespace: string;
216
+ /** When the namespace was created (unix ms). */
217
+ created_at: number;
218
+ }
219
+ /** One page of an instance's namespaces, newest first. */
220
+ interface NamespacesPage {
221
+ namespaces: NamespaceInfo[];
222
+ has_more: boolean;
223
+ /** Pass back as `cursor` for the next page; null on the last one. */
224
+ cursor?: string | null;
225
+ }
226
+
227
+ interface DatastoreOptions {
228
+ /** Namespace bound to this client (default `""`). */
229
+ namespace?: string;
230
+ }
231
+ /** Client for one datastore instance, bound to a namespace. */
232
+ declare class DatastoreClient {
233
+ readonly instance: string;
234
+ readonly namespace: string;
235
+ /** Namespace administration for the whole instance (not namespace-bound). */
236
+ readonly namespaces: NamespaceAdmin;
237
+ private readonly http;
238
+ private readonly base;
239
+ private readonly nsBase;
240
+ constructor(http: Http, instance: string, opts?: DatastoreOptions);
241
+ /** Same instance, different namespace. */
242
+ withNamespace(namespace: string): DatastoreClient;
243
+ /** Upsert up to 500 documents; returns their keys in order. */
244
+ put<T>(collection: string, documents: PutDocument<T>[]): Promise<{
245
+ keys: string[];
246
+ }>;
247
+ /** Fetch one document (`null` when missing), or — passed an array — up to 500
248
+ * documents in one round trip, order-preserving with `null` placeholders for
249
+ * missing keys (App Engine `db.get` semantics). Both forms ride the batch
250
+ * endpoint — there is no single-document route on the wire. */
251
+ get<T = unknown>(collection: string, key: Key): Promise<DatastoreDocument<T> | null>;
252
+ get<T = unknown>(collection: string, keys: Key[]): Promise<(DatastoreDocument<T> | null)[]>;
253
+ /** Delete up to 500 documents by key; missing keys are no-ops. */
254
+ delete(collection: string, keys: Key[]): Promise<{
255
+ deleted: number;
256
+ }>;
257
+ /** Run one page of an index-served query. */
258
+ query<T = unknown>(collection: string, req?: QueryRequest): Promise<QueryResult<T>>;
259
+ /** Iterate every matching document across pages (cursor handled for you). */
260
+ queryAll<T = unknown>(collection: string, req?: QueryRequest): AsyncGenerator<DatastoreDocument<T>>;
261
+ /** Grouped metrics over an index-served filter. */
262
+ aggregate(collection: string, req: AggregateRequest): Promise<AggregateResult>;
263
+ /** Apply up to 500 operations atomically within this namespace. NOT retried
264
+ * automatically (increments would double-apply); a failed `check` throws a 409. */
265
+ transaction(operations: TxnOp[]): Promise<TransactionResult>;
266
+ readonly indexes: {
267
+ list: (collection: string) => Promise<{
268
+ indexes: IndexSpec[];
269
+ }>;
270
+ create: (collection: string, req: CreateIndexRequest) => Promise<{
271
+ index: IndexSpec;
272
+ }>;
273
+ delete: (collection: string, id: number) => Promise<{
274
+ deleted: boolean;
275
+ }>;
276
+ };
277
+ }
278
+ declare class NamespaceAdmin {
279
+ private readonly http;
280
+ private readonly base;
281
+ constructor(http: Http, base: string);
282
+ /** A page of the instance's namespaces, newest first. When `has_more` is set, pass the
283
+ * returned `cursor` back as `cursor` for the next page. */
284
+ list(opts?: {
285
+ q?: string;
286
+ limit?: number;
287
+ cursor?: string;
288
+ }): Promise<NamespacesPage>;
289
+ /** Delete a namespace and everything in it. Requires a `full` grant. */
290
+ delete(namespace: string): Promise<{
291
+ deleted: boolean;
292
+ }>;
293
+ }
294
+
295
+ /** Wire types for the search data plane (App Engine Search API parity).
296
+ * Field names are wire-verbatim (snake_case). */
297
+ type FieldType = "text" | "html" | "atom" | "number" | "date" | "geo" | "tokenprefix" | "untokenprefix";
298
+ interface GeoPoint {
299
+ lat: number;
300
+ lng: number;
301
+ }
302
+ interface SearchField {
303
+ name: string;
304
+ type: FieldType;
305
+ /** `string` for text/html/atom/tokenprefix/untokenprefix, `number` for number,
306
+ * ISO string or epoch ms for date, `{lat,lng}` for geo. */
307
+ value: unknown;
308
+ language?: string;
309
+ }
310
+ type FacetType = "atom" | "number";
311
+ interface SearchFacet {
312
+ name: string;
313
+ type: FacetType;
314
+ value: string | number;
315
+ }
316
+ interface SearchDocument {
317
+ /** Omit to have the server assign one (returned from `put`). */
318
+ id?: string;
319
+ /** Sort/tiebreak rank; defaults to seconds since 2011-01-01. */
320
+ rank?: number;
321
+ lang?: string;
322
+ fields: SearchField[];
323
+ facets?: SearchFacet[];
324
+ }
325
+ interface SortSpec {
326
+ /** A number, date or atom field name, `"rank"`, or `"_score"`. */
327
+ expr: string;
328
+ desc?: boolean;
329
+ /** Sort value for documents missing the field: a number for a number or date field, a
330
+ * string for an atom field. */
331
+ default?: number | string;
332
+ }
333
+ interface FacetRefinement {
334
+ name: string;
335
+ /** Atom facet value… */
336
+ value?: string;
337
+ /** …or a number range (min inclusive, max exclusive). */
338
+ min?: number;
339
+ max?: number;
340
+ }
341
+ interface SnippetRequest {
342
+ /** Text/html fields to snippet (at most 20): one snippet per listed field that matched.
343
+ * Omitted, each result gets one snippet, from its best-matching text/html field. */
344
+ fields?: string[];
345
+ /** Token count (not chars), clamped 1..64. */
346
+ max_tokens?: number;
347
+ pre_tag?: string;
348
+ post_tag?: string;
349
+ ellipsis?: string;
350
+ }
351
+ interface CollapseRequest {
352
+ /** Atom or number field to collapse (distinct) on. */
353
+ field: string;
354
+ /** Top docs kept per distinct value, clamped 1..10. Incompatible with `sort`. */
355
+ limit?: number;
356
+ }
357
+ interface SearchRequest {
358
+ /** Boolean query language: bare terms, `field:value`, comparisons, AND/OR/NOT,
359
+ * `-term`, grouping, `"phrases"`, `~stem`, `distance(loc, geopoint(lat,lng)) < n`. */
360
+ query: string;
361
+ /** Default 20, max 1000. */
362
+ limit?: number;
363
+ /** Max 1000; prefer `cursor` for deep paging. */
364
+ offset?: number;
365
+ cursor?: string;
366
+ ids_only?: boolean;
367
+ returned_fields?: string[];
368
+ sort?: SortSpec[];
369
+ /** Cap on documents examined for sorting (default 1000, max 10000). */
370
+ sort_limit?: number;
371
+ scorer?: "match" | "rescore";
372
+ /** Auto-discover the top-N facets over matching documents. */
373
+ facet_discover?: number;
374
+ /** Explicit facet names to aggregate. */
375
+ facets?: string[];
376
+ facet_value_limit?: number;
377
+ facet_refinements?: FacetRefinement[];
378
+ /** Matching docs examined for facet counts (max 10000). */
379
+ facet_depth?: number;
380
+ /** Count accuracy cap — `total_hits` is exact up to this (default 20, max 10000). */
381
+ total_hits_accuracy?: number;
382
+ snippet?: SnippetRequest;
383
+ collapse?: CollapseRequest;
384
+ }
385
+ interface SearchHit {
386
+ id: string;
387
+ rank: number;
388
+ score?: number;
389
+ /** Absent when `ids_only`. */
390
+ document?: SearchDocument;
391
+ /** Field name → highlighted HTML. */
392
+ snippet?: Record<string, string>;
393
+ }
394
+ interface FacetValueResult {
395
+ value: string;
396
+ count: number;
397
+ min?: number;
398
+ max?: number;
399
+ }
400
+ interface FacetResult {
401
+ name: string;
402
+ type: FacetType;
403
+ values: FacetValueResult[];
404
+ }
405
+ interface SearchResponse {
406
+ total_hits: number;
407
+ total_hits_exact: boolean;
408
+ returned: number;
409
+ results: SearchHit[];
410
+ /** Present iff more pages exist. */
411
+ cursor?: string;
412
+ facets?: FacetResult[];
413
+ /** Free-form data attached by matching query rules. */
414
+ rule_data?: unknown[];
415
+ }
416
+ interface IndexInfo {
417
+ name: string;
418
+ namespace: string;
419
+ created_at: number;
420
+ }
421
+ interface IndexesPage {
422
+ indexes: IndexInfo[];
423
+ has_more: boolean;
424
+ /** Send back as `cursor` to get the next page. Null on the last one. */
425
+ cursor?: string | null;
426
+ }
427
+ interface ListDocumentsOptions {
428
+ /** Keyset pagination: resume from this document id. */
429
+ start_id?: string;
430
+ /** Include `start_id` itself (default true). */
431
+ include_start?: boolean;
432
+ limit?: number;
433
+ }
434
+ /** The union schema of an index: for every field name, the types it has been
435
+ * indexed with. */
436
+ interface IndexSchema {
437
+ name: string;
438
+ namespace: string;
439
+ fields: Record<string, FieldType[]>;
440
+ }
441
+
442
+ interface SearchOptions {
443
+ /** Namespace for all index operations (default `""`). Rides the request path
444
+ * (`/ns/{ns}/idx/{index}/…`), mirroring datastore. */
445
+ namespace?: string;
446
+ }
447
+ /** Client for one search instance, bound to a namespace. */
448
+ declare class SearchClient {
449
+ readonly instance: string;
450
+ readonly namespace: string;
451
+ private readonly http;
452
+ private readonly base;
453
+ /** Namespace-scoped base: `/v1/search/{instance}/ns/{ns}`. */
454
+ private readonly nsBase;
455
+ constructor(http: Http, instance: string, opts?: SearchOptions);
456
+ /** Same instance, different namespace. */
457
+ withNamespace(namespace: string): SearchClient;
458
+ index(name: string): SearchIndex;
459
+ /** Indexes in this client's namespace. When `has_more` is set, pass the returned `cursor`
460
+ * back as `cursor` for the next page. */
461
+ listIndexes(opts?: {
462
+ q?: string;
463
+ limit?: number;
464
+ cursor?: string;
465
+ }): Promise<IndexesPage>;
466
+ /** Every index in this client's namespace, following the cursor for you.
467
+ *
468
+ * Stops on a cursor that does not advance as well as on a missing one: an SDK outlives the
469
+ * deployment it was written against, and a server that keeps handing back the same cursor
470
+ * would otherwise be followed for ever, billing each round. Same rule as `searchAll`. */
471
+ listAllIndexes(opts?: {
472
+ q?: string;
473
+ limit?: number;
474
+ }): AsyncGenerator<IndexInfo>;
475
+ /** Distinct namespaces with live indexes — alphabetical, `q` substring search,
476
+ * `limit` default 50 (max 100). Instance-wide (not bound to this client's
477
+ * namespace); the default namespace appears as `""`. */
478
+ listNamespaces(opts?: {
479
+ q?: string;
480
+ limit?: number;
481
+ }): Promise<{
482
+ namespaces: string[];
483
+ has_more: boolean;
484
+ }>;
485
+ /** Delete an index and all its documents. Requires a `full` grant. */
486
+ deleteIndex(name: string): Promise<{
487
+ deleted: boolean;
488
+ }>;
489
+ }
490
+ /** Operations on one search index. */
491
+ declare class SearchIndex {
492
+ private readonly http;
493
+ readonly name: string;
494
+ private readonly path;
495
+ constructor(http: Http, nsBase: string, name: string);
496
+ /** Upsert up to 200 documents; returns their ids in order (server-assigned when
497
+ * a document omits `id`). */
498
+ put(documents: SearchDocument[]): Promise<{
499
+ ids: string[];
500
+ }>;
501
+ /** Fetch one document (`null` when missing), or — passed an array — up to 200
502
+ * documents in one round trip, order-preserving with `null` placeholders for
503
+ * missing ids. Both forms ride the batch endpoint. */
504
+ get(id: string): Promise<SearchDocument | null>;
505
+ get(ids: string[]): Promise<(SearchDocument | null)[]>;
506
+ /** Delete up to 200 documents by id; missing ids are no-ops. Requires `full`. */
507
+ delete(ids: string[]): Promise<{
508
+ deleted: number;
509
+ }>;
510
+ /** Run a search request (see `SearchRequest` for the full surface). */
511
+ search(req: SearchRequest): Promise<SearchResponse>;
512
+ /**
513
+ * Iterate every hit across cursor pages.
514
+ *
515
+ * Stops on a cursor that does not advance, as well as on a missing one. Search paging ends at a
516
+ * fixed depth, and a server that kept issuing a cursor past it handed back the SAME page — so
517
+ * "follow the cursor until it is absent", which is what this loop did, fetched that page for
518
+ * ever and billed each round. The server no longer does that; this is the half that does not
519
+ * depend on which version you are talking to, since an SDK outlives the deployment it was
520
+ * written against.
521
+ */
522
+ searchAll(req: SearchRequest): AsyncGenerator<SearchHit>;
523
+ /** One page of documents in id order (keyset pagination via `start_id`). */
524
+ listDocuments(opts: ListDocumentsOptions & {
525
+ ids_only?: false;
526
+ }): Promise<{
527
+ documents: SearchDocument[];
528
+ }>;
529
+ listDocuments(opts: ListDocumentsOptions & {
530
+ ids_only: true;
531
+ }): Promise<{
532
+ ids: string[];
533
+ }>;
534
+ /** Iterate every document in the index (keyset pagination handled for you). */
535
+ listAllDocuments(opts?: {
536
+ limit?: number;
537
+ }): AsyncGenerator<SearchDocument>;
538
+ /** The index's union field schema. */
539
+ schema(): Promise<IndexSchema>;
540
+ }
541
+
542
+ /** Server-side client for one channel instance (API-key auth): mint subscriber
543
+ * tokens, publish over HTTP, and read presence. For the browser/edge WebSocket
544
+ * subscriber, use `ChannelSocket` from `@altenginenet/sdk/channel`. */
545
+ declare class ChannelClient {
546
+ readonly instance: string;
547
+ private readonly http;
548
+ private readonly base;
549
+ constructor(http: Http, instance: string);
550
+ /** Mint a subscriber token (JWT) for the given channels. */
551
+ createToken(req: TokenRequest): Promise<TokenResponse>;
552
+ /** Publish a message (framed ≤32 KiB) to a channel; returns the number of
553
+ * subscribers reached. NOT retried automatically (a retry double-delivers). */
554
+ publish(channel: string, data: unknown): Promise<{
555
+ delivered: number;
556
+ }>;
557
+ /** Presence roster for a channel (requires the instance's presence flag). */
558
+ presence(channel: string): Promise<PresenceResponse>;
559
+ }
560
+
561
+ /** Wire types for the automation data plane — scripts run on your own machines. */
562
+ type RunStatus = "queued" | "running" | "done" | "failed" | "canceled" | "abandoned";
563
+ interface StartRunRequest {
564
+ /** A deployed script's name. Deploy with the CLI: `altengine automation deploy`. */
565
+ script: string;
566
+ /** The run's input, reachable in the script as `job.params`. One deployed script becomes many
567
+ * jobs through it — per dealer, per date, per account. */
568
+ params?: unknown;
569
+ /** Pin the run to one machine. Omit to let any machine matching `labels` take it. */
570
+ agent_id?: string;
571
+ /** Target by label instead of by name — `["site-dallas", "has-quickbooks"]`. */
572
+ labels?: string[];
573
+ /** Override the script's own parallel/exclusive setting for this run. Exclusive (the default
574
+ * for anything touching the desktop) means the run has the machine to itself. */
575
+ parallel?: boolean;
576
+ /** POSTed once the run AND its files have landed, signed with the instance's webhook signing
577
+ * secret — check it with `verifyWebhook`. Mutually exclusive with `on_complete` — a run has
578
+ * one completion target. */
579
+ webhook_url?: string;
580
+ /** A function to call once the run AND its files have landed, as
581
+ * `<functions-instance>/<function>`. Mutually exclusive with `webhook_url`.
582
+ *
583
+ * The function runs with its OWN configured grants, so naming it here grants the function
584
+ * nothing it did not already have. Either field, set on the run, replaces BOTH of the
585
+ * instance's defaults — so "call my function for this run" cannot also fire the fleet's
586
+ * standing webhook. */
587
+ on_complete?: string;
588
+ /** A wall clock, if this job genuinely has a deadline. Usually unset: what bounds a run is the
589
+ * instance's cost ceiling, not a timer. */
590
+ timeout_ms?: number;
591
+ /** Run as a local account the agent created, headless, under that account's own identity
592
+ * rather than the machine's.
593
+ *
594
+ * The account is made by an earlier run calling `user.ensure`, which needs the maintenance
595
+ * lane and a machine installed to allow managed accounts. The agent is the authority on
596
+ * whether a name is one it created and refuses anything else, so this cannot borrow an
597
+ * account somebody else put on the PC. Needs agent 0.0.11 or newer; an older one is refused
598
+ * rather than quietly running with the machine's own identity. */
599
+ run_as?: string;
600
+ }
601
+ interface Run {
602
+ id: string;
603
+ status: RunStatus;
604
+ script: string;
605
+ version: number;
606
+ agent_id: string | null;
607
+ params: unknown;
608
+ labels: string[];
609
+ parallel: boolean;
610
+ timeout_ms: number;
611
+ /** Seconds this run was authorised for, derived from the instance's cost ceiling. */
612
+ max_run_seconds: number;
613
+ parent_run_id: string | null;
614
+ chain_depth: number;
615
+ exit_code: number | null;
616
+ error: string | null;
617
+ /** Present only while `running` AND doing something other than running the script — today
618
+ * `"uploading"`, with `phase_detail` like `"2 files, 3.1 GB"`. This is how a large export
619
+ * still going up is told apart from a script that is stuck. */
620
+ phase?: string | null;
621
+ phase_detail?: string | null;
622
+ cost_usd: number;
623
+ queued_at: number;
624
+ started_at: number | null;
625
+ ended_at: number | null;
626
+ /** Delivery state of this run's completion target. Only one of the two is ever non-null —
627
+ * they are the same three columns, so read whichever is there. */
628
+ webhook: {
629
+ status: string | null;
630
+ attempts: number;
631
+ at: number | null;
632
+ } | null;
633
+ on_complete: {
634
+ target: string;
635
+ status: string | null;
636
+ attempts: number;
637
+ at: number | null;
638
+ } | null;
639
+ }
640
+ interface Artifact {
641
+ id: string;
642
+ run_id: string;
643
+ name: string;
644
+ size_bytes: number;
645
+ content_type: string | null;
646
+ created_at: number;
647
+ expires_at: number;
648
+ /** A presigned download link, minted for THIS response and never stored. It expires on its own
649
+ * in a few minutes, so fetch what you need rather than saving the URL. */
650
+ url?: string;
651
+ url_expires_in?: number;
652
+ }
653
+ interface RunWithArtifacts {
654
+ run: Run;
655
+ artifacts: Artifact[];
656
+ }
657
+ interface LogPage {
658
+ lines: {
659
+ ts: number;
660
+ level: string;
661
+ msg: string;
662
+ }[];
663
+ cursor: string | null;
664
+ /** Where these lines came from. `"agent"` is a live tail of the last few hundred lines from the
665
+ * machine itself; `"artifact"` is the complete log the run uploaded when it finished. A tail
666
+ * that stops is not a script that stopped — this is how you tell. */
667
+ source?: string;
668
+ dropped?: number;
669
+ }
670
+ interface Agent {
671
+ id: string;
672
+ name: string;
673
+ hostname: string | null;
674
+ os: string | null;
675
+ agent_version: string | null;
676
+ labels: string[];
677
+ /** The machine ANSWERED, not that a socket is open. An agent reports in on a timer and one that
678
+ * goes quiet is dropped from the roster inside `heard_within_seconds` — except where `liveness`
679
+ * says otherwise. */
680
+ online: boolean;
681
+ /** When the machine was last heard from, not when it was noticed missing. */
682
+ last_seen: number | null;
683
+ /** A THIRD state, not a shade of offline. Offline is a machine that worked and stopped; this is
684
+ * a credential nobody redeemed, so `hostname`, `os` and `agent_version` are null until it
685
+ * first connects. Do not report one as a machine that has stopped working. */
686
+ never_connected: boolean;
687
+ /** What `online` rests on. Present only while online.
688
+ *
689
+ * `"reporting"` is a checked fact. `"unverified"` is a machine whose agent is too old to report,
690
+ * so a held socket is the whole of the evidence and a PC that was switched off reads as online
691
+ * until its credential expires — show it as online, but not as the same answer. */
692
+ liveness?: "reporting" | "unverified";
693
+ /** The window `"reporting"` is a guarantee over, in seconds. Read it; do not hard-code it. */
694
+ heard_within_seconds?: number;
695
+ enrolled_at: number;
696
+ revoked_at: number | null;
697
+ }
698
+ /** Where a value went, in the machines' own words — see `AutomationClient.send`. */
699
+ interface Delivery {
700
+ /** Runs whose machine CONFIRMED it. Safe to treat as arrived. */
701
+ delivered: number;
702
+ runs: string[];
703
+ /** Nothing was written to these at all, so a retry is safe. */
704
+ unreachable: string[];
705
+ /** Written to an open socket and not acknowledged — neither of its neighbours. Do not send a
706
+ * replacement value: the job may already have this one, and a second one-time code invalidates
707
+ * the first. Let the job's own timeout decide. */
708
+ undetermined: string[];
709
+ }
710
+ interface Script {
711
+ name: string;
712
+ version: number;
713
+ parallel: boolean;
714
+ updated_at: number;
715
+ }
716
+ interface Schedule {
717
+ id: string;
718
+ script: string;
719
+ cron: string;
720
+ timezone: string;
721
+ params: unknown;
722
+ labels: string[];
723
+ agent_id: string | null;
724
+ enabled: boolean;
725
+ catchup_policy: string;
726
+ }
727
+
728
+ /**
729
+ * Server-side client for one automation instance.
730
+ *
731
+ * ORGANIZATION API KEY ONLY. End-user identity tokens are refused by this service, as they are by
732
+ * containers: a run spends time on a machine you own, and access rules bound what a user may
733
+ * READ, not what they may spend. Have a page call a function that decides.
734
+ *
735
+ * Scripts are deployed with the CLI (`altengine automation deploy`), not from here — they are
736
+ * bundled into one flat ES module before upload, and shipping a bundler in this package to do it
737
+ * at runtime would be the wrong trade for every caller who never deploys.
738
+ */
739
+ declare class AutomationClient {
740
+ readonly instance: string;
741
+ private readonly http;
742
+ private readonly base;
743
+ constructor(http: Http, instance: string);
744
+ /**
745
+ * Start a run and return immediately.
746
+ *
747
+ * A `queued` run is NOT a failure — it means no machine matching the request is online yet, and
748
+ * an office PC being asleep is the ordinary case. It will be dispatched when one connects.
749
+ */
750
+ start(req: StartRunRequest): Promise<Run>;
751
+ /** A run and its artifacts, each with a freshly minted download link. */
752
+ get(runId: string): Promise<RunWithArtifacts>;
753
+ list(query?: {
754
+ status?: string;
755
+ script?: string;
756
+ agent_id?: string;
757
+ limit?: number;
758
+ cursor?: string;
759
+ }): Promise<{
760
+ runs: Run[];
761
+ cursor: string | null;
762
+ }>;
763
+ /** Stop a queued or running run. The script unwinds through its own cleanup. */
764
+ cancel(runId: string): Promise<{
765
+ canceled: boolean;
766
+ }>;
767
+ /**
768
+ * A page of the run's log.
769
+ *
770
+ * While the run is going this is a live tail from the machine — the last few hundred lines, not
771
+ * a transcript. Once it finishes it is the complete log the run uploaded, so a finished run is
772
+ * readable even from a machine that has since been switched off. `source` says which answered.
773
+ */
774
+ logs(runId: string, query?: {
775
+ cursor?: string;
776
+ }): Promise<LogPage>;
777
+ /** The run's artifacts, each with a freshly minted download link. */
778
+ artifacts(runId: string): Promise<Artifact[]>;
779
+ /**
780
+ * Poll until a run reaches a terminal status, then return it with its artifacts.
781
+ *
782
+ * THE RUN IS FINISHED WHEN ITS OUTPUT HAS LANDED, not when its script returned — the agent holds
783
+ * the terminal report until every artifact has been stored — so a `done` here always has its
784
+ * files, and the links on them are live.
785
+ *
786
+ * `timeoutMs` bounds the WAIT, not the run: giving up here leaves the run going on the machine.
787
+ * Call `cancel` if that is what you meant. Zero (the default) waits indefinitely, which is
788
+ * usually right for a job that legitimately takes hours.
789
+ */
790
+ wait(runId: string, opts?: {
791
+ timeoutMs?: number;
792
+ signal?: AbortSignal;
793
+ onPoll?: (run: Run) => void;
794
+ }): Promise<RunWithArtifacts>;
795
+ /** Start a run and wait for it. Convenience over `start` + `wait`. */
796
+ run(req: StartRunRequest, opts?: {
797
+ timeoutMs?: number;
798
+ signal?: AbortSignal;
799
+ onPoll?: (run: Run) => void;
800
+ }): Promise<RunWithArtifacts>;
801
+ /** Enrolled machines, with whether each is connected right now. */
802
+ /**
803
+ * One page of enrolled machines, with whether each is connected right now.
804
+ *
805
+ * PAGED, and the cursor matters: a fleet of hundreds is the ordinary shape of this service —
806
+ * an office, a chain of dealerships — and a caller that ignores it is looking at part of one.
807
+ * `q` matches name, hostname or label, which are the three things a machine is known by.
808
+ */
809
+ agents(query?: {
810
+ cursor?: string;
811
+ q?: string;
812
+ limit?: number;
813
+ }): Promise<{
814
+ agents: Agent[];
815
+ cursor: string | null;
816
+ }>;
817
+ /**
818
+ * Every enrolled machine, walking the pages for you.
819
+ *
820
+ * Here because the alternative — a `agents()` that quietly returned the first page — is how a
821
+ * fleet with more machines than a page silently became a smaller fleet. If you are counting
822
+ * machines, or acting on all of them, use this one.
823
+ */
824
+ allAgents(query?: {
825
+ q?: string;
826
+ }): Promise<Agent[]>;
827
+ agent(agentId: string): Promise<Agent>;
828
+ /**
829
+ * One page of deployed scripts and their active versions. Deploy with the CLI.
830
+ *
831
+ * PAGED, like `agents`. Both routes return a cursor and both used to have it dropped here, so a
832
+ * caller past the first page saw part of an answer and was told nothing — which is the exact
833
+ * shape the `agents`/`allAgents` pair below already exists to avoid.
834
+ */
835
+ scripts(query?: {
836
+ cursor?: string;
837
+ limit?: number;
838
+ }): Promise<{
839
+ scripts: Script[];
840
+ cursor: string | null;
841
+ }>;
842
+ /** Every deployed script, walking the pages for you. */
843
+ allScripts(): Promise<Script[]>;
844
+ /** One page of declared schedules. */
845
+ schedules(query?: {
846
+ cursor?: string;
847
+ limit?: number;
848
+ }): Promise<{
849
+ schedules: Schedule[];
850
+ cursor: string | null;
851
+ }>;
852
+ /** Every declared schedule, walking the pages for you. */
853
+ allSchedules(): Promise<Schedule[]>;
854
+ /**
855
+ * Declare a schedule. The cloud owns WHAT should happen; the machine owns WHEN — it fires from
856
+ * its own clock, so a nightly export still runs while your internet is down and only the run's
857
+ * record is late.
858
+ */
859
+ createSchedule(req: Partial<Schedule> & {
860
+ script: string;
861
+ cron: string;
862
+ }): Promise<Schedule>;
863
+ deleteSchedule(scheduleId: string): Promise<void>;
864
+ /**
865
+ * Hand a value to whichever job is waiting for it — `job.waitForData(key)` on the other end.
866
+ *
867
+ * THE CASE THIS IS FOR: a script signs into a portal, the portal sends a one-time code to a
868
+ * mailbox or a phone, and whatever receives that message calls this. Everything else the agent
869
+ * does is outbound; this is the one way to tell a run something.
870
+ *
871
+ * ADDRESSED BY KEY, not by run id, because the thing that will deliver the code — an SMS
872
+ * webhook, an inbound-mail parser — was configured months before tonight's run existed. That
873
+ * puts a duty on the key: the value reaches every job executing on the instance, and only one
874
+ * that asks for that key ever sees it, so `otp.dealer-42` is the shape to write when more than
875
+ * one job can be in flight. `script` and `agentId` narrow it further.
876
+ *
877
+ * Throws when nothing is running. The usual failure is a race you cannot see — the code arrived
878
+ * four seconds after the script gave up — and an integration needs to log that rather than read
879
+ * a silent success.
880
+ *
881
+ * `delivered` counts what the MACHINES confirmed. A run in `undetermined` was written to and did
882
+ * not acknowledge, which is not a failure: do not send a replacement value, because the job may
883
+ * already have this one and a second one-time code invalidates the first.
884
+ */
885
+ send(key: string, value: unknown, opts?: {
886
+ script?: string;
887
+ agentId?: string;
888
+ }): Promise<Delivery>;
889
+ /** The same, to ONE run by id — for when you were given the run id, typically because the
890
+ * script handed out `job.dataUrl(key)` when it triggered whatever produces the value.
891
+ *
892
+ * `delivered: false` with `undetermined: true` is the written-but-unacknowledged case: leave it
893
+ * alone and let the job's own timeout decide. */
894
+ sendToRun(runId: string, key: string, value: unknown): Promise<{
895
+ delivered: boolean;
896
+ undetermined?: true;
897
+ run: string;
898
+ key: string;
899
+ message?: string;
900
+ }>;
901
+ /** The NAMES of the credentials this fleet's scripts read as `env.NAME`. Values are write-only
902
+ * and never returned — a leaked key can replace one but not harvest it. */
903
+ env(): Promise<string[]>;
904
+ /**
905
+ * Replace the credential map. Omitting a name deletes it; `null` for a name KEEPS what is
906
+ * stored, which is the only way to rotate one without re-typing the others you cannot read.
907
+ */
908
+ setEnv(env: Record<string, string | null>): Promise<string[]>;
909
+ }
910
+
911
+ /** Wire types for the blob data plane — files, stored and served. */
912
+ /** One stored object. */
913
+ interface BlobRecord {
914
+ id: string;
915
+ /** Display name. Cosmetic — the id is the lookup key — and it is the segment that appears
916
+ * in a public URL. */
917
+ name: string;
918
+ size: number;
919
+ content_type: string;
920
+ etag: string;
921
+ /** `pending` is a reservation whose bytes have not landed. A read promotes it once they
922
+ * have, so an object you just uploaded reads as `ready`. */
923
+ status: "pending" | "ready";
924
+ public: boolean;
925
+ created: number;
926
+ updated: number;
927
+ meta: Record<string, unknown>;
928
+ /** `blob:<instance>:<object>` — the portable handle to store elsewhere. It is an identifier,
929
+ * not a capability: holding one lets nobody read anything. */
930
+ blobkey: string;
931
+ /** The stable public URL, or null when the object is private. */
932
+ url: string | null;
933
+ }
934
+ interface UploadUrlRequest {
935
+ name?: string;
936
+ /** The exact byte length you will upload. Required, and signed into the URL — sending a
937
+ * different number of bytes is refused by storage. */
938
+ size: number;
939
+ /** Defaults to `application/octet-stream`. Also signed in. */
940
+ content_type?: string;
941
+ /** Omit to take the instance's default. A container job token is refused `true`. */
942
+ public?: boolean;
943
+ meta?: Record<string, unknown>;
944
+ }
945
+ /** A reservation and the URL its bytes go to. */
946
+ interface MintedUpload {
947
+ id: string;
948
+ blobkey: string;
949
+ upload_url: string;
950
+ expires_at: number;
951
+ /** What the PUT must carry, byte for byte. `content-length` is set by the runtime from the
952
+ * body you send. */
953
+ required_headers: Record<string, string>;
954
+ method: "PUT";
955
+ }
956
+ /** The first half of a multipart upload: POST `create_url` and storage answers with XML
957
+ * naming the upload id. */
958
+ interface MultipartBegin {
959
+ id: string;
960
+ blobkey: string;
961
+ key: string;
962
+ part_size: number;
963
+ parts: number;
964
+ create_url: string;
965
+ expires_at: number;
966
+ }
967
+ /** A window of part URLs, plus the two that end the upload either way. */
968
+ interface MultipartUrls {
969
+ part_urls: {
970
+ part_number: number;
971
+ url: string;
972
+ }[];
973
+ complete_url: string;
974
+ /** DELETE here on any failure. Parts of an upload nobody completed still bill. */
975
+ abort_url: string;
976
+ expires_at: number;
977
+ }
978
+ interface BlobDownload {
979
+ blob: BlobRecord;
980
+ /** A signed link, minted for this response and good for a few minutes. Fetch what you need
981
+ * rather than storing the URL. */
982
+ download_url: string;
983
+ expires_at: number;
984
+ }
985
+ interface BlobPage {
986
+ blobs: BlobRecord[];
987
+ cursor: string | null;
988
+ }
989
+ /** A type alias rather than an interface so it satisfies the query-string record. */
990
+ type BlobListQuery = {
991
+ /** Matches the start of the object's name. */
992
+ prefix?: string;
993
+ limit?: number;
994
+ cursor?: string;
995
+ };
996
+ interface UploadOptions {
997
+ /** Defaults to a `Blob`/`File`'s own `type`, then to `application/octet-stream`. */
998
+ contentType?: string;
999
+ /** Omit to take the instance's default. */
1000
+ public?: boolean;
1001
+ meta?: Record<string, unknown>;
1002
+ /** Aborts the transfer, and the multipart upload with it. */
1003
+ signal?: AbortSignal;
1004
+ /** Called after each part of a multipart upload. */
1005
+ onProgress?: (p: {
1006
+ uploaded: number;
1007
+ total: number;
1008
+ }) => void;
1009
+ }
1010
+
1011
+ /**
1012
+ * What one presigned PUT can carry, and therefore where multipart starts.
1013
+ *
1014
+ * Not our number: object storage caps a single upload here, and a presigned URL is exactly one
1015
+ * request. The instance's own size limit is a cost control and a different question.
1016
+ */
1017
+ declare const MAX_SINGLE_PUT_BYTES: number;
1018
+ /**
1019
+ * Client for one blob instance.
1020
+ *
1021
+ * BYTES NEVER TRAVEL THROUGH THE API. Every upload and download here goes to a presigned URL,
1022
+ * so the API sees a reservation and storage sees the file. There is no commit step: the row is
1023
+ * promoted by the side that received the bytes.
1024
+ *
1025
+ * Levels are a ceiling — `read < write < full`. Uploading needs `write`; `delete` needs `full`.
1026
+ *
1027
+ * A CONTAINER JOB'S TOKEN IS NARROWER THAN AN API KEY, and the two refusals it carries are
1028
+ * refusals, not omissions: it may not `list` a store, and it may not publish — `setPublic`, and
1029
+ * `public: true` on an upload. Both come back as 403s naming what was refused. A job is told
1030
+ * its inputs; it does not go looking, and publishing is the one act that outlives the credential
1031
+ * that made it.
1032
+ */
1033
+ declare class BlobClient {
1034
+ readonly instance: string;
1035
+ private readonly http;
1036
+ private readonly base;
1037
+ constructor(http: Http, instance: string);
1038
+ /**
1039
+ * Store a file. Returns the finished object.
1040
+ *
1041
+ * Picks the transfer for you: one presigned PUT, or a multipart upload when a `Blob`/`File` is
1042
+ * larger than storage will take in a single request. `content` may be a string, an
1043
+ * `ArrayBuffer`, a typed array, or a `Blob`/`File` — only a `Blob` can be uploaded in parts,
1044
+ * since parts are sliced from it rather than held in memory.
1045
+ *
1046
+ * `contentType` is worth passing: without one an object is stored as
1047
+ * `application/octet-stream`, which a browser downloads rather than renders. A `File` carries
1048
+ * its own.
1049
+ */
1050
+ put(name: string, content: string | ArrayBuffer | ArrayBufferView | Blob, opts?: UploadOptions): Promise<BlobRecord>;
1051
+ /**
1052
+ * Mint a URL a client PUTs bytes to directly, without handing that client an API key.
1053
+ *
1054
+ * This is how a browser uploads: your backend decides whether this user may, and how big the
1055
+ * file may be, then hands over a URL that can do exactly that one thing for fifteen minutes.
1056
+ * The size is signed in, so it is the real bound on what the holder can make you store.
1057
+ */
1058
+ uploadUrl(req: UploadUrlRequest): Promise<MintedUpload>;
1059
+ /** Reserve an object and sign the call that opens a multipart upload. Use `put` unless you
1060
+ * are driving the transfer yourself. */
1061
+ beginMultipart(req: UploadUrlRequest): Promise<MultipartBegin>;
1062
+ /** Sign a window of part URLs, plus the complete and abort URLs. At most 100 parts per call. */
1063
+ multipartUrls(req: {
1064
+ id: string;
1065
+ upload_id: string;
1066
+ from?: number;
1067
+ count?: number;
1068
+ }): Promise<MultipartUrls>;
1069
+ /** An object's metadata plus a short-lived download URL. */
1070
+ get(id: string): Promise<BlobDownload>;
1071
+ /** An object's bytes, fetched from storage rather than through the API. */
1072
+ bytes(id: string, opts?: {
1073
+ signal?: AbortSignal;
1074
+ }): Promise<Uint8Array>;
1075
+ /**
1076
+ * One page of objects, newest first.
1077
+ *
1078
+ * PAGED, and the cursor matters: a store is small in development and unbounded in a real
1079
+ * account, so a caller that ignores it is looking at part of one.
1080
+ *
1081
+ * Refused for a container job token — a job is told its inputs rather than enumerating the
1082
+ * store it writes to.
1083
+ */
1084
+ list(query?: BlobListQuery): Promise<BlobPage>;
1085
+ /** Every object, walking the pages for you. */
1086
+ listAll(query?: Omit<BlobListQuery, "cursor">): AsyncGenerator<BlobRecord>;
1087
+ /**
1088
+ * Publish or unpublish an object. A public object is served from a stable URL with no
1089
+ * credential at all; unpublishing drops the cached copies too.
1090
+ *
1091
+ * Refused for a container job token: publishing is the one operation whose effect outlives the
1092
+ * credential that made it.
1093
+ */
1094
+ setPublic(id: string, isPublic?: boolean): Promise<BlobRecord>;
1095
+ /** Delete up to 200 objects. Needs `full`; ids that do not exist are not counted. */
1096
+ delete(ids: string[]): Promise<{
1097
+ deleted: number;
1098
+ }>;
1099
+ /**
1100
+ * Cut a large file up, send the parts, and let storage glue them back together — so what the
1101
+ * customer downloads is one ordinary file rather than a split archive they need a tool for.
1102
+ *
1103
+ * Parts go up one at a time: these bytes usually leave an office connection, and a part that
1104
+ * fails is a part re-sent in full. ON ANY FAILURE THE UPLOAD IS ABORTED, because parts of an
1105
+ * upload nobody completed keep billing and no listing shows them.
1106
+ */
1107
+ private putMultipart;
1108
+ /** The finished record. A read, so it needs no grant an upload did not already have —
1109
+ * `write` outranks `read`. */
1110
+ private read;
1111
+ }
1112
+ /**
1113
+ * The blob client for the store a container job was handed, built from the two variables the
1114
+ * platform puts in every job an instance with a `blobStore` launches: `AE_BLOB_URL` (the store's
1115
+ * own endpoint) and `AE_BLOB_TOKEN` (a bearer that expires with the job).
1116
+ *
1117
+ * That token is scoped to one store and one job, at `write`. So it puts and gets; it does not
1118
+ * delete, does not `list` the store, and does not publish. Each of those comes back as a 403
1119
+ * naming what was refused.
1120
+ */
1121
+ declare function blobFromJobEnv(opts?: Omit<ClientOptions, "baseUrl" | "apiKey" | "auth">): BlobClient;
1122
+
1123
+ /** Wire types for the container data plane — a Docker image run as a background job. */
1124
+ type JobStatus = "running" | "done" | "failed" | "canceled";
1125
+ interface LaunchRequest {
1126
+ /** Must be on the instance's allowed-images list. An empty allowlist runs nothing. */
1127
+ image: string;
1128
+ /** `small`, `medium` or `large` — ask `sizes()` what this instance offers. */
1129
+ size?: string;
1130
+ /** Overrides the image's own entrypoint arguments. */
1131
+ cmd?: string[];
1132
+ /** Variables for the job. Names starting `AE_` are reserved. */
1133
+ env?: Record<string, string>;
1134
+ /** The job's deadline. Bounded by the instance's own ceiling, and by what one job may cost. */
1135
+ timeout_ms?: number;
1136
+ }
1137
+ interface Job {
1138
+ id: string;
1139
+ status: JobStatus;
1140
+ image: string;
1141
+ size: string;
1142
+ exit_code: number | null;
1143
+ timeout_ms: number;
1144
+ error: string | null;
1145
+ started_at: number;
1146
+ ended_at: number | null;
1147
+ cost_usd: number;
1148
+ }
1149
+ interface JobPage {
1150
+ jobs: Job[];
1151
+ /** The `started_at` to feed back as `before`. Null when there is nothing older. */
1152
+ cursor: number | null;
1153
+ }
1154
+ /** A type alias rather than an interface so it satisfies the query-string record. */
1155
+ type JobListQuery = {
1156
+ status?: JobStatus;
1157
+ limit?: number;
1158
+ /** Keyset cursor: the `cursor` from the previous page. */
1159
+ before?: number;
1160
+ };
1161
+ interface JobLogLine {
1162
+ timestamp: string;
1163
+ /** The stream the line came from. */
1164
+ level?: string;
1165
+ message: string;
1166
+ }
1167
+ interface JobLogPage {
1168
+ lines: JobLogLine[];
1169
+ cursor: string | number | null;
1170
+ /** Why a page is empty, when it is empty for a reason worth showing — logs that have aged
1171
+ * out, a job that never had a machine, a log service that could not be reached. */
1172
+ note?: string;
1173
+ }
1174
+ interface ContainerSizes {
1175
+ sizes: {
1176
+ name: string;
1177
+ cpus: number;
1178
+ memory_mb: number;
1179
+ }[];
1180
+ /** Nothing outside this list will launch. */
1181
+ allowed_images: string[];
1182
+ max_timeout_ms: number;
1183
+ max_concurrent: number;
1184
+ }
1185
+
1186
+ /**
1187
+ * Server-side client for one container instance — a Docker image run as a background job, for
1188
+ * the work that will not fit in a function.
1189
+ *
1190
+ * ORGANIZATION API KEY ONLY. End-user identity tokens are refused by this service, as they are
1191
+ * by automation: access rules bound what a user may READ, not what they may SPEND. Have a page
1192
+ * call a function that decides.
1193
+ *
1194
+ * A job's OUTPUT does not come back through here. It writes what it produces to blob — name a
1195
+ * `blobStore` on the instance and every job gets `AE_BLOB_URL` and `AE_BLOB_TOKEN` — or it calls
1196
+ * a function when it finishes.
1197
+ */
1198
+ declare class ContainerClient {
1199
+ readonly instance: string;
1200
+ private readonly http;
1201
+ private readonly base;
1202
+ constructor(http: Http, instance: string);
1203
+ /**
1204
+ * Start a job and return as soon as its machine exists.
1205
+ *
1206
+ * There is nothing to await: a job that runs for twenty minutes has nowhere to send twenty
1207
+ * minutes of output. Poll with `wait`, or have the instance call a function when it ends.
1208
+ */
1209
+ run(req: LaunchRequest): Promise<Job>;
1210
+ /** One job: status, exit code, how long it ran, what it cost. */
1211
+ get(jobId: string): Promise<Job>;
1212
+ /**
1213
+ * One page of jobs, newest first.
1214
+ *
1215
+ * PAGED, and the cursor matters. Note the shape: the response's `cursor` is fed back as
1216
+ * `before` — it is the `started_at` of the last job on the page.
1217
+ */
1218
+ list(query?: JobListQuery): Promise<JobPage>;
1219
+ /** Every job matching the query, walking the pages for you. */
1220
+ listAll(query?: Omit<JobListQuery, "before">): AsyncGenerator<Job>;
1221
+ /**
1222
+ * Stop a running job and destroy its machine now. It is billed for the time it ran.
1223
+ *
1224
+ * `canceled: false` means the job had already finished, which is not a failure.
1225
+ */
1226
+ cancel(jobId: string): Promise<{
1227
+ job: Job;
1228
+ canceled: boolean;
1229
+ }>;
1230
+ /**
1231
+ * What the job printed, oldest first.
1232
+ *
1233
+ * BEST EFFORT: an unavailable log service returns an empty page with a `note` rather than
1234
+ * throwing, and a job's own record — exit code, timing, cost — never depends on it. Logs are
1235
+ * kept for about a week after the machine is destroyed.
1236
+ */
1237
+ logs(jobId: string, query?: {
1238
+ cursor?: string | number;
1239
+ }): Promise<JobLogPage>;
1240
+ /** What this instance will accept: the sizes, the image allowlist, and the two ceilings. */
1241
+ sizes(): Promise<ContainerSizes>;
1242
+ /**
1243
+ * Poll until a job reaches a terminal status.
1244
+ *
1245
+ * `timeoutMs` bounds the WAIT, not the job: giving up here leaves the machine running and
1246
+ * billing. Call `cancel` if that is what you meant. Zero (the default) waits indefinitely.
1247
+ */
1248
+ wait(jobId: string, opts?: {
1249
+ timeoutMs?: number;
1250
+ signal?: AbortSignal;
1251
+ onPoll?: (job: Job) => void;
1252
+ }): Promise<Job>;
1253
+ /** Start a job and wait for it. Convenience over `run` + `wait`. */
1254
+ runAndWait(req: LaunchRequest, opts?: {
1255
+ timeoutMs?: number;
1256
+ signal?: AbortSignal;
1257
+ onPoll?: (job: Job) => void;
1258
+ }): Promise<Job>;
1259
+ }
1260
+
1261
+ /** Wire types for the mailbox data plane — email addresses an app or agent owns. Unlike the
1262
+ * older services, this API's fields are camelCase. */
1263
+ /** One mailbox: an address and a display name. */
1264
+ interface MailAddress {
1265
+ address: string;
1266
+ name: string;
1267
+ }
1268
+ /** Why the service stopped this mailbox's sending: too many sends today went to addresses that
1269
+ * previously bounced or marked mail as spam. Only an owner can resume it, in the console. */
1270
+ interface SendPause {
1271
+ at: number;
1272
+ suppressed: number;
1273
+ reason: string;
1274
+ }
1275
+ interface MailboxInfo {
1276
+ name: string;
1277
+ /** The mail domain, or null when none is configured. */
1278
+ domain: string | null;
1279
+ /** The main address (`<slug>@<domain>`), or null when the instance has none. */
1280
+ address: string | null;
1281
+ /** Every other address: `<slug>.<anything>@<domain>`. */
1282
+ pattern: string | null;
1283
+ acceptMode: "any" | "registered";
1284
+ sendMode: "off" | "reply" | "any";
1285
+ retentionDays: number;
1286
+ /** Null unless sending is paused; sends then fail with 403 SEND_PAUSED. */
1287
+ sendPaused: SendPause | null;
1288
+ }
1289
+ /** A message as every list returns it: everything but the bodies. */
1290
+ interface MessageSummary {
1291
+ id: string;
1292
+ direction: "in" | "out";
1293
+ /** The name the message was sent to (received) or from (sent): `inbox` for the main address. */
1294
+ local: string;
1295
+ plusTag: string | null;
1296
+ from: MailAddress;
1297
+ to: MailAddress[];
1298
+ cc: MailAddress[];
1299
+ replyTo: MailAddress[];
1300
+ subject: string;
1301
+ snippet: string;
1302
+ messageId: string | null;
1303
+ inReplyTo: string | null;
1304
+ /** Whether the sender's domain authenticated a received message. Reply mode answers only
1305
+ * senders that did. */
1306
+ verified: boolean;
1307
+ status: string;
1308
+ size: number;
1309
+ attachmentCount: number;
1310
+ receivedAt: number;
1311
+ readAt: number | null;
1312
+ /** When the message and its attachments are deleted. Move it with `keep`. */
1313
+ expiresAt: number;
1314
+ }
1315
+ interface MessageAttachment {
1316
+ idx: number;
1317
+ filename: string | null;
1318
+ contentType: string;
1319
+ size: number;
1320
+ contentId: string | null;
1321
+ disposition: string | null;
1322
+ /** Why the part was not stored (too large, too many), or null. */
1323
+ rejected: string | null;
1324
+ /** Whether `attachment(id, idx)` can hand out a download link for it. */
1325
+ stored: boolean;
1326
+ }
1327
+ /** What one route action did for a received message. */
1328
+ interface MailDelivery {
1329
+ /** `function:<instance>/<fn>`, `channel:<instance>/<channel>`, `channel+text:…` or `webhook:<url>`. */
1330
+ action: string;
1331
+ /** `pending`, `ok:<status>`, or `error:<why>`. */
1332
+ status: string;
1333
+ attempts: number;
1334
+ nextAt: number | null;
1335
+ }
1336
+ /** One full message. */
1337
+ interface MailMessage extends MessageSummary {
1338
+ text: string | null;
1339
+ html: string | null;
1340
+ textTruncated: boolean;
1341
+ htmlTruncated: boolean;
1342
+ references: string | null;
1343
+ authResults: string | null;
1344
+ deliveries: MailDelivery[];
1345
+ /** Whether the raw .eml was kept, so `raw` can link to it. */
1346
+ hasRaw: boolean;
1347
+ attachments: MessageAttachment[];
1348
+ }
1349
+ interface MessagePage {
1350
+ messages: MessageSummary[];
1351
+ /** Newest-first paging: pass back as `cursor`. Null when there is nothing older. */
1352
+ cursor: string | null;
1353
+ }
1354
+ /** A type alias rather than an interface so it satisfies the query-string record. */
1355
+ type MessageListQuery = {
1356
+ /** Only mail for this name (`support`) or full address. */
1357
+ to?: string;
1358
+ direction?: "in" | "out";
1359
+ /** Only received mail not yet marked read. */
1360
+ unread?: boolean;
1361
+ cursor?: string;
1362
+ limit?: number;
1363
+ };
1364
+ interface WaitQuery {
1365
+ /** The point to wait from: `"now"` (mail from this moment on), a message id or a previous
1366
+ * `cursor`, or `"0"` for any message still held. Required — so last week's mail is never
1367
+ * mistaken for the one you are waiting for. */
1368
+ after: string;
1369
+ to?: string;
1370
+ /** How long the server holds the request, at most 30 (the default). */
1371
+ timeoutSeconds?: number;
1372
+ limit?: number;
1373
+ }
1374
+ interface WaitResult {
1375
+ /** Inbound messages newer than `after`, oldest first; empty on timeout. */
1376
+ messages: MessageSummary[];
1377
+ /** Where to wait from next: the last message's id, or `after` unchanged. */
1378
+ cursor: string;
1379
+ }
1380
+ /** A short-lived download link. */
1381
+ interface DownloadLink {
1382
+ url: string;
1383
+ expiresAt: number;
1384
+ }
1385
+ interface AttachmentLink extends DownloadLink {
1386
+ filename: string | null;
1387
+ contentType: string;
1388
+ size: number;
1389
+ }
1390
+ /** File content for an attachment: base64 text, or bytes the SDK base64-encodes for you. */
1391
+ type AttachmentContent = string | Uint8Array | ArrayBuffer | ArrayBufferView | Blob;
1392
+ interface OutgoingAttachment {
1393
+ /** Defaults to `attachment-<n>`. */
1394
+ filename?: string;
1395
+ /** Defaults to `application/octet-stream`. */
1396
+ contentType?: string;
1397
+ /** A string is taken as base64 already; bytes are encoded. */
1398
+ content: AttachmentContent;
1399
+ /** Set to show the part inline, referenced from the HTML as `cid:<contentId>`
1400
+ * (1–100 letters, digits, `.`, `_`, `@` or `-`). */
1401
+ contentId?: string;
1402
+ }
1403
+ interface SendRequest {
1404
+ /** The name to send from: `support` sends as `<slug>.support@<domain>`. Defaults to the
1405
+ * main address. */
1406
+ from?: string;
1407
+ fromName?: string;
1408
+ to: string[] | string;
1409
+ cc?: string[] | string;
1410
+ subject: string;
1411
+ text?: string;
1412
+ html?: string;
1413
+ /** Up to 32. The whole message must stay under 5 MB once encoded — about 3.6 MB of files. */
1414
+ attachments?: OutgoingAttachment[];
1415
+ }
1416
+ /** A reply: `to`, `subject` and `from` default from the message being answered. */
1417
+ type ReplyRequest = Partial<SendRequest>;
1418
+ interface AddressRecord {
1419
+ local: string;
1420
+ label: string | null;
1421
+ meta: Record<string, unknown>;
1422
+ registered: boolean;
1423
+ createdAt: number;
1424
+ disabledAt: number | null;
1425
+ }
1426
+ interface AddressWithFull extends AddressRecord {
1427
+ /** The full address, or null when the instance has none. */
1428
+ address: string | null;
1429
+ }
1430
+ interface AddressPage {
1431
+ addresses: AddressWithFull[];
1432
+ cursor: string | null;
1433
+ }
1434
+ interface CreateAddressRequest {
1435
+ /** Omit to have an unguessable name minted. */
1436
+ local?: string;
1437
+ label?: string;
1438
+ /** At most 4 KB of JSON. */
1439
+ meta?: Record<string, unknown>;
1440
+ }
1441
+
1442
+ /** The longest the server holds a `wait`. */
1443
+ declare const MAX_WAIT_SECONDS = 60;
1444
+ /** Attachment content as the API takes it: a string is already base64; bytes are encoded. */
1445
+ declare function attachmentBase64(content: AttachmentContent): Promise<string>;
1446
+ /**
1447
+ * Server-side client for one mailbox instance — email addresses an app or agent owns.
1448
+ *
1449
+ * ORGANIZATION API KEY ONLY: a mailbox holds third parties' mail and can send as you, so
1450
+ * end-user identity tokens are refused.
1451
+ *
1452
+ * Every name works: `<slug>.<anything>@<domain>` receives mail with no call needed, unless the
1453
+ * instance accepts registered names only. Every message expires after the mailbox's retention;
1454
+ * `keep` moves one message's date.
1455
+ */
1456
+ declare class MailboxClient {
1457
+ readonly instance: string;
1458
+ private readonly http;
1459
+ private readonly base;
1460
+ /** Names that carry a setting: registered, labelled or disabled. */
1461
+ readonly addresses: {
1462
+ /** One page, in name order. */
1463
+ list(query?: {
1464
+ cursor?: string;
1465
+ limit?: number;
1466
+ }): Promise<AddressPage>;
1467
+ /** Register (and optionally label) a name; omit `local` to have an unguessable one minted. */
1468
+ create(req?: CreateAddressRequest): Promise<AddressWithFull>;
1469
+ /** Refuse the name's mail and stop it sending. Its messages stay. */
1470
+ disable(local: string): Promise<AddressRecord>;
1471
+ };
1472
+ constructor(http: Http, instance: string);
1473
+ /** The main address, the pattern of every other one, and the settings a caller needs. */
1474
+ info(): Promise<MailboxInfo>;
1475
+ /** One page of messages, newest first, without bodies. */
1476
+ list(query?: MessageListQuery): Promise<MessagePage>;
1477
+ /**
1478
+ * Wait for the next inbound mail after `after`, holding the request up to `timeoutSeconds`
1479
+ * (at most 60; the server checks every 5 s). Empty on timeout — call again with the returned `cursor` to keep waiting.
1480
+ *
1481
+ * Pass `after: "now"` BEFORE handing an address to whoever will mail it, so older mail is not
1482
+ * mistaken for the new one.
1483
+ */
1484
+ wait(query: WaitQuery): Promise<WaitResult>;
1485
+ /** One message with its bodies and attachment list. */
1486
+ get(id: string): Promise<MailMessage>;
1487
+ /** A short-lived link to the raw .eml. Fails when the mailbox does not keep raw messages. */
1488
+ raw(id: string): Promise<DownloadLink>;
1489
+ /** A short-lived download link for one attachment. The URL is the credential: no key needed. */
1490
+ attachment(id: string, idx: number): Promise<AttachmentLink>;
1491
+ /** Mark a received message read. */
1492
+ markRead(id: string): Promise<{
1493
+ ok: true;
1494
+ }>;
1495
+ /**
1496
+ * Send a new message from a name on this mailbox. Refused when the send mode is `off`, and in
1497
+ * `reply` mode unless every recipient has written to this mailbox in authenticated mail.
1498
+ * Never retried: a retried send is a second email.
1499
+ */
1500
+ send(req: SendRequest): Promise<MessageSummary>;
1501
+ /** Reply to a received message, threaded: to its Reply-To (or From), from the name it was
1502
+ * sent to, with `Re: <subject>` — unless you pass those. Same limits as `send`. */
1503
+ reply(id: string, req?: ReplyRequest): Promise<MessageSummary>;
1504
+ /**
1505
+ * Keep one message until `days` (1–90) from now, overriding the mailbox's retention for it
1506
+ * alone. Extending needs `write`; an earlier date deletes the message sooner, so that needs
1507
+ * `full`.
1508
+ */
1509
+ keep(id: string, days: number): Promise<MessageSummary>;
1510
+ /** Delete a message and its attachments now. Needs `full`. */
1511
+ delete(id: string): Promise<{
1512
+ deleted: number;
1513
+ }>;
1514
+ }
1515
+
1516
+ /** Where a push task is delivered: exactly one of a function, a channel or a webhook. */
1517
+ type TaskTarget = {
1518
+ function: string;
1519
+ } | {
1520
+ channel: string;
1521
+ } | {
1522
+ webhook: string;
1523
+ };
1524
+ type TaskState = "scheduled" | "running" | "leased" | "done" | "failed" | "cancelled";
1525
+ /** Where a task came from. */
1526
+ type TaskSource = "api" | "console" | "mcp" | "function" | "datastore" | "blob" | "mailbox" | "deadletter" | "rerun";
1527
+ interface RetryPolicy {
1528
+ /** Attempts before the task fails, the first included. 1–100, default 10. */
1529
+ maxAttempts: number;
1530
+ /** 1–86400, default 10. */
1531
+ minBackoffSeconds: number;
1532
+ /** 1–604800, default 3600. */
1533
+ maxBackoffSeconds: number;
1534
+ /** How many times the wait doubles before it grows linearly. 0–16, default 8. */
1535
+ maxDoublings: number;
1536
+ /** A task older than this fails without another attempt. 0 (no limit) – 2592000, default 604800. */
1537
+ maxAgeSeconds: number;
1538
+ }
1539
+ interface QueueSettings {
1540
+ /** `push` delivers each task to its target; `pull` holds tasks for workers to lease. */
1541
+ mode: "push" | "pull";
1542
+ /** The default push target; a task's own target overrides it. Null on a pull queue. */
1543
+ target: TaskTarget | null;
1544
+ /** 0.01–100, default 10. */
1545
+ ratePerSecond: number;
1546
+ /** Deliveries in flight at once, 1–50, default 5. */
1547
+ maxConcurrent: number;
1548
+ retry: RetryPolicy;
1549
+ /** Another queue in the same instance that receives a copy of every task that fails. */
1550
+ deadLetterQueue: string | null;
1551
+ paused: boolean;
1552
+ /** Let the target steer its own retries with `Retry-After`, `x-task-retry` and
1553
+ * `x-task-max-attempts`. Default true. */
1554
+ targetControl: boolean;
1555
+ /** How long a push delivery is waited for before the attempt counts as failed and is retried,
1556
+ * 15–840, default 600. The target is not stopped when it passes. */
1557
+ deadlineSeconds: number;
1558
+ }
1559
+ /** What a create or a change sends. Only the fields given change. */
1560
+ type QueueSettingsPatch = Partial<Omit<QueueSettings, "retry">> & {
1561
+ retry?: Partial<RetryPolicy>;
1562
+ };
1563
+ interface QueueInfo {
1564
+ name: string;
1565
+ settings: QueueSettings;
1566
+ createdAt: number;
1567
+ updatedAt: number;
1568
+ deleting: boolean;
1569
+ purging: boolean;
1570
+ /** Tasks per state, each capped at 10,000; `capped` names the states that reached it. */
1571
+ counts: Record<TaskState, number>;
1572
+ capped: TaskState[];
1573
+ }
1574
+ interface TasksInfo {
1575
+ name: string;
1576
+ /** How long a finished task's record — and so its name — is kept. */
1577
+ retentionDays: number;
1578
+ queues: QueueInfo[];
1579
+ }
1580
+ /** One task to add. */
1581
+ interface TaskInput<P = unknown> {
1582
+ /** Any JSON, up to 128 KB. Required: pass null for none. */
1583
+ payload: P;
1584
+ /** Makes the add idempotent: a name already used in the queue is refused while its record is kept. */
1585
+ name?: string;
1586
+ /** Seconds from now. Give this or `runAt`, not both; neither is now. */
1587
+ delay?: number;
1588
+ /** Epoch milliseconds, an ISO 8601 time, or a Date — at most 30 days ahead. */
1589
+ runAt?: number | string | Date;
1590
+ /** Overrides the queue's target (push queues only). */
1591
+ target?: TaskTarget;
1592
+ /** A small object passed to the target beside the payload, up to 4 KB. */
1593
+ params?: Record<string, unknown>;
1594
+ /** This task's retry policy; fields left out take the defaults. */
1595
+ retry?: Partial<RetryPolicy>;
1596
+ /** Overrides the queue's `deadlineSeconds` for this task, 15–840. */
1597
+ deadlineSeconds?: number;
1598
+ }
1599
+ type AddResult = {
1600
+ ok: true;
1601
+ id: string;
1602
+ name: string | null;
1603
+ state: TaskState;
1604
+ runAt: number;
1605
+ } | {
1606
+ ok: false;
1607
+ code: "TASK_EXISTS";
1608
+ message: string;
1609
+ id: string;
1610
+ name: string;
1611
+ };
1612
+ /** A task without its payload, params or result — what a listing returns. */
1613
+ interface TaskSummary {
1614
+ id: string;
1615
+ queue: string;
1616
+ name: string | null;
1617
+ state: TaskState;
1618
+ target: TaskTarget | null;
1619
+ attempts: number;
1620
+ maxAttempts: number;
1621
+ runAt: number;
1622
+ createdAt: number;
1623
+ startedAt: number | null;
1624
+ finishedAt: number | null;
1625
+ leaseUntil: number | null;
1626
+ lastStatus: string | null;
1627
+ lastError: string | null;
1628
+ source: TaskSource;
1629
+ /** Trigger-chain depth: 0 for a task a person or a key added. */
1630
+ depth: number;
1631
+ payloadBytes: number;
1632
+ deadLetterOf: string | null;
1633
+ /** Times the target deferred it (`x-task-retry: defer`); not counted as attempts. */
1634
+ defers: number;
1635
+ /** This task's own deadline in seconds; null means its queue's. */
1636
+ deadlineSeconds: number | null;
1637
+ }
1638
+ interface TaskAttempt {
1639
+ n: number;
1640
+ startedAt: number;
1641
+ endedAt: number | null;
1642
+ status: string | null;
1643
+ error: string | null;
1644
+ }
1645
+ interface TaskRecord<P = unknown> extends TaskSummary {
1646
+ payload: P;
1647
+ params: Record<string, unknown> | null;
1648
+ /** The target's answer, up to 16 KB. */
1649
+ result: string | null;
1650
+ retry: RetryPolicy | null;
1651
+ attemptLog: TaskAttempt[];
1652
+ }
1653
+ /** A leased pull task, and the lease id that acks, extends or releases it. */
1654
+ interface LeasedTask<P = unknown> extends TaskRecord<P> {
1655
+ leaseId: string;
1656
+ }
1657
+ interface TaskPage {
1658
+ tasks: TaskSummary[];
1659
+ cursor: string | null;
1660
+ }
1661
+ interface TaskListQuery {
1662
+ /** Omit for every state, newest first. Waiting work comes soonest first; finished work latest first. */
1663
+ state?: TaskState;
1664
+ cursor?: string;
1665
+ /** 1–200, default 50. */
1666
+ limit?: number;
1667
+ /** Only the task with this name. */
1668
+ name?: string;
1669
+ }
1670
+ interface CancelResult {
1671
+ cancelled: string[];
1672
+ /** Tasks left alone: running or finished (`state`), or not found (`state: null`). */
1673
+ skipped: {
1674
+ id: string;
1675
+ state: TaskState | null;
1676
+ }[];
1677
+ }
1678
+ interface LeaseOptions {
1679
+ /** 1–100, default 1. */
1680
+ count?: number;
1681
+ /** 1–3600, default 300. */
1682
+ leaseSeconds?: number;
1683
+ }
1684
+ interface ReleaseOptions {
1685
+ /** When it may be leased again, in seconds. Default 0. */
1686
+ delaySeconds?: number;
1687
+ /** Recorded on the attempt. */
1688
+ error?: string;
1689
+ }
1690
+ /** What a push target receives about the task it is handed. */
1691
+ interface TaskEnvelope {
1692
+ id: string;
1693
+ queue: string;
1694
+ name: string | null;
1695
+ attempt: number;
1696
+ maxAttempts: number;
1697
+ runAt: number;
1698
+ createdAt: number;
1699
+ source: TaskSource;
1700
+ depth: number;
1701
+ params: Record<string, unknown> | null;
1702
+ deadLetterOf: string | null;
1703
+ /** Epoch ms at which the queue stops waiting for this attempt and counts it as failed. The
1704
+ * target is not stopped then; finish before it, or the work may run again. */
1705
+ deadlineAt: number;
1706
+ }
1707
+ /** The JSON body a function or webhook target receives. Handle it idempotently on `task.id`:
1708
+ * delivery is at least once. */
1709
+ interface TaskDelivery<P = unknown> {
1710
+ task: TaskEnvelope;
1711
+ payload: P;
1712
+ }
1713
+
1714
+ /** Response headers a push target may answer with to steer its own retries (when the queue's
1715
+ * `targetControl` is on, the default). */
1716
+ declare const TASK_RETRY_HEADER = "x-task-retry";
1717
+ declare const TASK_RETRY_AFTER_HEADER = "x-task-retry-after";
1718
+ declare const TASK_MAX_ATTEMPTS_HEADER = "x-task-max-attempts";
1719
+ /**
1720
+ * Server-side client for one tasks instance — queues of work.
1721
+ *
1722
+ * A push queue delivers each task to a function, a channel or a signed webhook and retries it
1723
+ * with backoff until it is accepted; a pull queue holds tasks for workers to `lease` and `ack`.
1724
+ * Delivery is at least once: handle a task idempotently on its id.
1725
+ *
1726
+ * ORGANIZATION API KEY ONLY: a task runs its target with the target's own grants, so end-user
1727
+ * identity tokens are refused.
1728
+ */
1729
+ declare class TasksClient {
1730
+ readonly instance: string;
1731
+ private readonly http;
1732
+ private readonly base;
1733
+ constructor(http: Http, instance: string);
1734
+ /** The instance's retention and its queues. */
1735
+ info(): Promise<TasksInfo>;
1736
+ /** Every queue, with its settings and counts by state. */
1737
+ queues(): Promise<QueueInfo[]>;
1738
+ queue(name: string): Promise<QueueInfo>;
1739
+ /** Create a queue. Settings left out take their defaults. Needs `full`. */
1740
+ createQueue(name: string, settings?: QueueSettingsPatch): Promise<QueueInfo>;
1741
+ /** Change a queue: only the settings given change. Needs `full`. */
1742
+ updateQueue(name: string, settings: QueueSettingsPatch): Promise<QueueInfo>;
1743
+ /** Stop delivering a queue's tasks; nothing is lost. Needs `full`. */
1744
+ pauseQueue(name: string): Promise<QueueInfo>;
1745
+ resumeQueue(name: string): Promise<QueueInfo>;
1746
+ /** Delete every task in a queue, in any state. Needs `full`. */
1747
+ purgeQueue(name: string): Promise<{
1748
+ purged: number;
1749
+ pending: boolean;
1750
+ }>;
1751
+ /** Delete a queue and every task in it. `default` cannot be deleted. Needs `full`. */
1752
+ deleteQueue(name: string): Promise<{
1753
+ deleted: boolean;
1754
+ pending: boolean;
1755
+ }>;
1756
+ /**
1757
+ * Add one task, or up to 100, to a queue. Each result says whether it was added or its name
1758
+ * was already taken — a name already used is a result, not a throw, so a producer that retries
1759
+ * with the same name is idempotent.
1760
+ *
1761
+ * Retried on a transient failure only when every task is named: an unnamed task sent twice is
1762
+ * two tasks.
1763
+ */
1764
+ add<P = unknown>(queue: string, tasks: TaskInput<P> | TaskInput<P>[]): Promise<AddResult[]>;
1765
+ /** One page of a queue's tasks, without payloads. */
1766
+ list(queue: string, query?: TaskListQuery): Promise<TaskPage>;
1767
+ /** Every task in a queue (narrowed by `query`), page by page. */
1768
+ listAll(queue: string, query?: Omit<TaskListQuery, "cursor">): AsyncGenerator<TaskSummary>;
1769
+ /** One task, with its payload, every attempt and the target's answer. */
1770
+ get<P = unknown>(id: string): Promise<TaskRecord<P>>;
1771
+ /** Cancel scheduled or leased tasks (up to 200). A running task cannot be stopped. */
1772
+ cancel(ids: string | string[]): Promise<CancelResult>;
1773
+ /**
1774
+ * Run a task now: a scheduled one is moved up, a failed or cancelled one is retried with its
1775
+ * attempts reset, and a finished one is run again as a NEW task with the same payload.
1776
+ */
1777
+ run<P = unknown>(id: string): Promise<TaskRecord<P>>;
1778
+ /**
1779
+ * Lease up to `count` due tasks from a pull queue. Finish each with `ack`, or give it back with
1780
+ * `release`; a lease that runs out puts the task back with its attempt counted as failed.
1781
+ * Never retried: a retried lease would hold tasks nobody is working on.
1782
+ */
1783
+ lease<P = unknown>(queue: string, opts?: LeaseOptions): Promise<LeasedTask<P>[]>;
1784
+ /** Finish a leased task, with an optional result (a string, or JSON) kept up to 16 KB. */
1785
+ ack<P = unknown>(id: string, leaseId: string, result?: unknown): Promise<TaskRecord<P>>;
1786
+ /** Hold a lease longer: `leaseSeconds` (1–3600, default 300) from now. */
1787
+ extend<P = unknown>(id: string, leaseId: string, leaseSeconds?: number): Promise<TaskRecord<P>>;
1788
+ /** Give a leased task back, to be leased again after `delaySeconds`. The attempt counts as
1789
+ * failed; on the last attempt the task fails instead. */
1790
+ release<P = unknown>(id: string, leaseId: string, opts?: ReleaseOptions): Promise<TaskRecord<P>>;
1791
+ }
1792
+
1793
+ /** Error codes emitted by the altengine API. The union is open (`string`) so new
1794
+ * server codes never break compilation. */
1795
+ type ErrorCode = "NOT_FOUND" | "INVALID_ARGUMENT" | "UNAUTHENTICATED" | "PERMISSION_DENIED" | "RATE_LIMITED" | "QUERY_TOO_COMPLEX" | "INDEX_REQUIRED" | "DOCUMENT_TOO_LARGE" | "INDEX_FULL" | "ALREADY_EXISTS" | "PRECONDITION_FAILED" | "INTERNAL" | (string & {});
1796
+ /** A structured altengine API error: the `{error:{code,message,details?}}` envelope
1797
+ * plus transport context (HTTP status, Retry-After). */
1798
+ declare class AltEngineError extends Error {
1799
+ readonly code: ErrorCode;
1800
+ readonly status: number;
1801
+ readonly details?: unknown;
1802
+ /** Seconds to wait before retrying, from the `Retry-After` header (429s). */
1803
+ readonly retryAfter?: number;
1804
+ constructor(opts: {
1805
+ code: ErrorCode;
1806
+ message: string;
1807
+ status: number;
1808
+ details?: unknown;
1809
+ retryAfter?: number;
1810
+ });
1811
+ /** Whether the request can be safely retried after a backoff. 429 always carries
1812
+ * Retry-After; 502/503/504 are transient. 507 INDEX_FULL is NOT retryable. */
1813
+ get retryable(): boolean;
1814
+ }
1815
+ /** Thrown when the network/fetch layer fails before an HTTP response exists. */
1816
+ declare class AltEngineNetworkError extends Error {
1817
+ readonly cause?: unknown;
1818
+ constructor(message: string, cause?: unknown);
1819
+ }
1820
+
1821
+ /** Field builders — `f.text("title", "Blue Shoes")` reads better than object
1822
+ * literals and pins the right `type` string. */
1823
+ declare const f: {
1824
+ text: (name: string, value: string, language?: string) => SearchField;
1825
+ html: (name: string, value: string, language?: string) => SearchField;
1826
+ atom: (name: string, value: string) => SearchField;
1827
+ number: (name: string, value: number) => SearchField;
1828
+ /** Accepts a Date, ISO string, or epoch milliseconds. */
1829
+ date: (name: string, value: Date | string | number) => SearchField;
1830
+ geo: (name: string, value: GeoPoint) => SearchField;
1831
+ tokenprefix: (name: string, value: string) => SearchField;
1832
+ untokenprefix: (name: string, value: string) => SearchField;
1833
+ };
1834
+ /** Facet builders for document facets. */
1835
+ declare const facet: {
1836
+ atom: (name: string, value: string) => SearchFacet;
1837
+ number: (name: string, value: number) => SearchFacet;
1838
+ };
1839
+
1840
+ /** Verifying an automation completion webhook.
1841
+ *
1842
+ * Every webhook carries two headers:
1843
+ *
1844
+ * - `x-altengine-timestamp` — when it was sent, in milliseconds since the epoch.
1845
+ * - `x-altengine-signature` — `v1=<hex>`, an HMAC-SHA256 of `<timestamp>.<raw body>` keyed with
1846
+ * the instance's whole webhook signing secret, `whsec_` prefix included.
1847
+ *
1848
+ * Uses Web Crypto, so it runs the same on Node 20+, in a browser, and in any edge runtime. */
1849
+ declare const WEBHOOK_SIGNATURE_HEADER = "x-altengine-signature";
1850
+ declare const WEBHOOK_TIMESTAMP_HEADER = "x-altengine-timestamp";
1851
+ /** How far the timestamp may be from now, either way, by default: five minutes. */
1852
+ declare const DEFAULT_WEBHOOK_TOLERANCE_MS: number;
1853
+ interface VerifyWebhookOptions {
1854
+ /** The instance's webhook signing secret, `whsec_…`, as the console or MCP shows it. */
1855
+ secret: string;
1856
+ /** The body exactly as received — NOT a re-serialised parse, which signs different bytes. */
1857
+ body: string | Uint8Array | ArrayBuffer;
1858
+ /** The `x-altengine-signature` header. */
1859
+ signature: string | null | undefined;
1860
+ /** The `x-altengine-timestamp` header. */
1861
+ timestamp: string | number | null | undefined;
1862
+ /** Reject a timestamp further than this from now, either way. Default five minutes. */
1863
+ toleranceMs?: number;
1864
+ /** The current time in ms. For tests; defaults to `Date.now()`. */
1865
+ now?: number;
1866
+ }
1867
+ /**
1868
+ * True when the webhook was signed with `secret` and its timestamp is within `toleranceMs` of now.
1869
+ *
1870
+ * ```ts
1871
+ * import { verifyWebhook } from "@altenginenet/sdk";
1872
+ *
1873
+ * const ok = await verifyWebhook({
1874
+ * secret: process.env.ALTENGINE_WEBHOOK_SECRET!,
1875
+ * body: await request.text(),
1876
+ * signature: request.headers.get("x-altengine-signature"),
1877
+ * timestamp: request.headers.get("x-altengine-timestamp"),
1878
+ * });
1879
+ * if (!ok) return new Response("bad signature", { status: 401 });
1880
+ * ```
1881
+ *
1882
+ * Each delivery attempt is signed afresh, so a retry carries a new timestamp: deduplicate on
1883
+ * `run.id`, not on the signature.
1884
+ */
1885
+ declare function verifyWebhook(opts: VerifyWebhookOptions): Promise<boolean>;
1886
+
1887
+ /** @altenginenet/sdk — official JavaScript/TypeScript SDK for altengine
1888
+ * (https://www.altengine.net).
1889
+ *
1890
+ * ```ts
1891
+ * import { AltEngine, f } from "@altenginenet/sdk";
1892
+ *
1893
+ * const ae = new AltEngine({ apiKey: "ae_..." }); // production api.altengine.net
1894
+ * // const ae = new AltEngine({ dev: true, apiKey: "dev" }); // local `altengine dev`
1895
+ *
1896
+ * const db = ae.datastore("myapp");
1897
+ * const { keys } = await db.put("todos", [{ data: { title: "ship SDK" } }]);
1898
+ *
1899
+ * const idx = ae.search("myapp").index("products");
1900
+ * await idx.put([{ fields: [f.text("title", "Blue Shoes"), f.number("price", 59)] }]);
1901
+ *
1902
+ * const ch = ae.channel("myapp");
1903
+ * const { token, ws_endpoint, protocols } = await ch.createToken({ channels: ["room:1"] });
1904
+ * ```
1905
+ *
1906
+ * For the browser WebSocket subscriber, import from `@altenginenet/sdk/channel`.
1907
+ * For client-side sign-in with no backend of your own, see `@altenginenet/sdk/auth`:
1908
+ *
1909
+ * ```ts
1910
+ * import { AuthClient } from "@altenginenet/sdk/auth";
1911
+ *
1912
+ * const auth = new AuthClient({ instance: "myapp-auth" });
1913
+ * await auth.signIn("alice@example.com", "hunter2");
1914
+ * const ae = new AltEngine({ auth }); // requests now carry the user's token
1915
+ * ```
1916
+ */
1917
+
1918
+ declare class AltEngine {
1919
+ private readonly http;
1920
+ constructor(opts?: ClientOptions);
1921
+ /** Client for a datastore instance (namespace-bound; default `""`). */
1922
+ datastore(instance: string, opts?: DatastoreOptions): DatastoreClient;
1923
+ /** Client for a search instance (namespace-bound; default `""`). */
1924
+ search(instance: string, opts?: SearchOptions): SearchClient;
1925
+ /** Server-side client for a channel instance (tokens, publish, presence). */
1926
+ channel(instance: string): ChannelClient;
1927
+ /** Server-side client for an automation instance — start runs on your own machines, read
1928
+ * what they produced, and declare schedules. Organization API key only: a run spends time on
1929
+ * hardware you own, so end-user identity tokens are refused as they are for containers. */
1930
+ automation(instance: string): AutomationClient;
1931
+ /** Client for a blob instance — files, stored and served. Upload bytes go straight to
1932
+ * storage on a presigned URL and never travel through the API. */
1933
+ blob(instance: string): BlobClient;
1934
+ /** Server-side client for a container instance — a Docker image run as a background job.
1935
+ * Organization API key only: end-user identity tokens are refused, as they are for
1936
+ * automation, because access rules bound what a user may read, not what they may spend. */
1937
+ container(instance: string): ContainerClient;
1938
+ /** Server-side client for a mailbox instance — email addresses an app or agent owns: read
1939
+ * what arrives, wait for the next message, send and reply. Organization API key only. */
1940
+ mailbox(instance: string): MailboxClient;
1941
+ /** Server-side client for a tasks instance — queues of work delivered to a function, a channel
1942
+ * or a signed webhook with retries, or leased by workers. Organization API key only. */
1943
+ tasks(instance: string): TasksClient;
1944
+ /** Client for an auth instance — end-user sign-up/sign-in and identity tokens.
1945
+ * Shares this client's API origin but never its API key (auth endpoints are
1946
+ * public; the end user's own credentials are the trust boundary). For browser
1947
+ * apps, import `AuthClient` from `@altenginenet/sdk/auth` directly instead. */
1948
+ auth(instance: string): AuthClient;
1949
+ }
1950
+
1951
+ export { type AddResult, type AddressPage, type AddressRecord, type AddressWithFull, type Agent, type AggregateGroup, type AggregateRequest, type AggregateResult, AltEngine, AltEngineError, AltEngineNetworkError, type Artifact, type AttachmentContent, type AttachmentLink, AuthClient, type AutoIndexInfo, AutomationClient, BlobClient, type BlobDownload, type BlobListQuery, type BlobPage, type BlobRecord, type CancelResult, ChannelClient, type ClientOptions, type CollapseRequest, ContainerClient, type ContainerSizes, type CreateAddressRequest, type CreateIndexRequest, DEFAULT_BASE_URL, DEFAULT_WEBHOOK_TOLERANCE_MS, DEV_BASE_URL, DatastoreClient, type DatastoreDocument, type DatastoreOptions, type Delivery, type DownloadLink, type ErrorCode, type FacetRefinement, type FacetResult, type FacetType, type FacetValueResult, type FieldType, type Filter, type FilterOp, type GeoPoint, type IndexInfo, type IndexSchema, type IndexSpec, type IndexesPage, type Job, type JobListQuery, type JobLogLine, type JobLogPage, type JobPage, type JobStatus, type Join, type Key, type LaunchRequest, type LeaseOptions, type LeasedTask, type ListDocumentsOptions, type LogPage, MAX_SINGLE_PUT_BYTES, MAX_WAIT_SECONDS, type MailAddress, type MailDelivery, type MailMessage, MailboxClient, type MailboxInfo, type MessageAttachment, type MessageListQuery, type MessagePage, type MessageSummary, type Metric, type MetricFn, type MintedUpload, type MultipartBegin, type MultipartUrls, NamespaceAdmin, type NamespaceInfo, type NamespacesPage, type Order, type OutgoingAttachment, PresenceResponse, type PutDocument, type QueryRequest, type QueryResult, type QueueInfo, type QueueSettings, type QueueSettingsPatch, type ReleaseOptions, type ReplyRequest, type RequestOptions, type RetryOptions, type RetryPolicy, type Run, type RunStatus, type RunWithArtifacts, type Schedule, type Script, SearchClient, type SearchDocument, type SearchFacet, type SearchField, type SearchHit, SearchIndex, type SearchOptions, type SearchRequest, type SearchResponse, type SendPause, type SendRequest, type SnippetRequest, type SortSpec, type StartRunRequest, TASK_MAX_ATTEMPTS_HEADER, TASK_RETRY_AFTER_HEADER, TASK_RETRY_HEADER, type TaskAttempt, type TaskDelivery, type TaskEnvelope, type TaskInput, type TaskListQuery, type TaskPage, type TaskRecord, type TaskSource, type TaskState, type TaskSummary, type TaskTarget, TasksClient, type TasksInfo, type TokenProvider, TokenRequest, TokenResponse, type TransactionResult, type TxnOp, type UploadOptions, type UploadUrlRequest, type VerifyWebhookOptions, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_TIMESTAMP_HEADER, type WaitQuery, type WaitResult, attachmentBase64, blobFromJobEnv, f, facet, verifyWebhook };