@flowmails/flowmails-sdk 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -11,6 +11,233 @@ interface SendAttachment {
11
11
  content: string | Uint8Array;
12
12
  mimeType?: string;
13
13
  }
14
+ /**
15
+ * One event in the durable log — what arrived, where, and from whom.
16
+ *
17
+ * The event carries **routing facts plus the subject line**, never a
18
+ * body: that is the platform's core promise (`docs/agent-platform.md`
19
+ * §4.2), and the body is opt-in through {@link MessageDetail}. The
20
+ * `messageId` is the SMTP `Message-ID` — the key every content read
21
+ * takes.
22
+ */
23
+ interface AgentEvent {
24
+ /** The cursor value. Treat it as opaque; pass it back as `after`. */
25
+ id: string;
26
+ /** The SMTP `Message-ID`. Pass this to `messages.get()`. */
27
+ messageId: string;
28
+ /** `inbound.received` — the only event type the platform emits. */
29
+ event: string;
30
+ /** The mailbox the message landed in, e.g. `billing@yourapp.com`. */
31
+ recipient: string;
32
+ /** The sender, when the receive worker could determine it. */
33
+ sender: string | null;
34
+ /** The subject line — the one content field on the event. */
35
+ subject: string | null;
36
+ /** ISO-8601 timestamp of when the platform recorded the event. */
37
+ createdAt: string;
38
+ }
39
+ /** Options for {@link AgentEvents.list}. */
40
+ interface ListEventsOptions {
41
+ /**
42
+ * Cursor: return events **after** this event id. Pass the
43
+ * `nextCursor` of the previous page. Treat it as opaque — it is an
44
+ * event id, not a timestamp, because two events can land in the
45
+ * same millisecond and a cursor that can skip a row loses mail.
46
+ */
47
+ after?: string;
48
+ /** Page size. The platform caps it; ask for what you will drain. */
49
+ limit?: number;
50
+ /** Exact recipient address filter. */
51
+ recipient?: string;
52
+ /** Exact sender address filter. */
53
+ sender?: string;
54
+ /** Case-insensitive **substring** of the subject. */
55
+ subject?: string;
56
+ }
57
+ /** One page of the event log. */
58
+ interface ListEventsResult {
59
+ events: AgentEvent[];
60
+ /**
61
+ * The cursor to pass as `after` on the next call. Present whenever
62
+ * the page was not empty; absent when the log is drained.
63
+ */
64
+ nextCursor?: string;
65
+ }
66
+ /** Options for {@link AgentWaits.create}. */
67
+ interface CreateWaitOptions {
68
+ /** The mailbox to watch, e.g. `billing@yourapp.com`. */
69
+ address: string;
70
+ /** Only resolve for mail from this sender. */
71
+ sender?: string;
72
+ /** Only resolve for a subject containing this substring. */
73
+ subject?: string;
74
+ /**
75
+ * How long to keep the wait open, in milliseconds. Defaults to 15
76
+ * minutes; the platform caps it at 24 hours.
77
+ */
78
+ timeoutMs?: number;
79
+ }
80
+ /** A durable wait, as the platform reports it. */
81
+ interface WaitStatus {
82
+ waitId: string;
83
+ /** `pending` → `resolved` (a message landed) or `expired`. */
84
+ status: "pending" | "resolved" | "expired";
85
+ address: string;
86
+ sender: string | null;
87
+ subject: string | null;
88
+ /** The SMTP `Message-ID` that resolved the wait, when it resolved. */
89
+ resolvedMessageId: string | null;
90
+ /** ISO-8601 deadline. A wait past it reads as `expired`. */
91
+ expiresAt: string | number;
92
+ }
93
+ /**
94
+ * A newly-opened wait.
95
+ *
96
+ * Returned **immediately** — the platform writes a row and answers,
97
+ * it never suspends the request. A verification mail arrives minutes
98
+ * to hours later and an edge request dies long before that, so the
99
+ * wait is durable state the agent polls with {@link AgentWaits.get}.
100
+ */
101
+ interface CreateWaitResult extends WaitStatus {
102
+ /** A hint for the poll loop: check again in a few seconds. */
103
+ pollAfterMs: number;
104
+ }
105
+ /** The full content of one message. Fetched, never pushed. */
106
+ interface MessageDetail {
107
+ /** The worker's numeric row id. */
108
+ id: number | string;
109
+ /** The SMTP `Message-ID` the event carried. */
110
+ messageId: string;
111
+ from: string;
112
+ fromName: string | null;
113
+ to: string;
114
+ toName: string | null;
115
+ subject: string | null;
116
+ /** Plain-text body. Ideal for regexing a verification code out. */
117
+ text: string | null;
118
+ /** Rendered HTML body, when the message had one. */
119
+ html: string | null;
120
+ receivedAt: string | null;
121
+ attachments: Array<{
122
+ filename: string | null;
123
+ mimeType: string | null;
124
+ size: number | null;
125
+ url: string | null;
126
+ }>;
127
+ }
128
+ /** One address (mailbox) the platform accepts mail for. */
129
+ interface AgentAddress {
130
+ address: string;
131
+ localPart: string;
132
+ }
133
+ /**
134
+ * One domain on the account.
135
+ *
136
+ * `routingMode` decides whether a new address needs anything to
137
+ * happen: on `catchall` every local part already delivers, on
138
+ * `rules` only the listed ones do.
139
+ */
140
+ interface AgentDomain {
141
+ id: string;
142
+ name: string;
143
+ routingMode: "catchall" | "rules";
144
+ localParts: string[];
145
+ /** False when the per-account receive worker is not deployed yet. */
146
+ ready: boolean;
147
+ }
148
+ /** Result of {@link AgentAddresses.create}. */
149
+ interface CreateAddressResult {
150
+ address: string;
151
+ localPart: string;
152
+ domainId: string;
153
+ domain: string;
154
+ /** False when the address already existed — the call is idempotent. */
155
+ created: boolean;
156
+ routingMode?: "catchall" | "rules";
157
+ }
158
+ /**
159
+ * One message of a conversation chain.
160
+ *
161
+ * It extends {@link MessageDetail} because the thread route uses the
162
+ * **same projection** the single-message read uses — the same
163
+ * fields, the same shape. The only addition is the truncation flag.
164
+ */
165
+ interface ThreadMessage extends MessageDetail {
166
+ /**
167
+ * `1` when the receive worker shortened the body.
168
+ *
169
+ * The worker returns a bounded window of the chain and truncates
170
+ * the bodies of the non-current members — a long thread must not
171
+ * become a way to pull a whole mailbox. `total` / `hasMoreOlder` /
172
+ * `hasMoreNewer` say whether the chain extends past the window.
173
+ */
174
+ bodyTruncated: 0 | 1;
175
+ }
176
+ /**
177
+ * A conversation chain — `docs/agent-platform.md` §10.8 AP-27.
178
+ */
179
+ interface ThreadDetail {
180
+ /** The conversation **root's** SMTP `Message-ID`. */
181
+ threadId: string;
182
+ /** The platform domain id the chain was read from. */
183
+ domainId: string;
184
+ /** The domain name the chain was read from. */
185
+ domain: string;
186
+ /** The full chain length — not just the returned window. */
187
+ total: number;
188
+ /** The chain extends past the window, older side. */
189
+ hasMoreOlder: boolean;
190
+ /** The chain extends past the window, newer side. */
191
+ hasMoreNewer: boolean;
192
+ /** The chain, oldest first. */
193
+ messages: ThreadMessage[];
194
+ }
195
+ /**
196
+ * One search hit.
197
+ *
198
+ * Addressing, the subject and a short preview — never the body. The
199
+ * body is fetched per message, through {@link AgentMessages.get},
200
+ * when the agent decides a message matters.
201
+ */
202
+ interface SearchMessageHit {
203
+ /** The worker's row id. Accepted by {@link AgentMessages.get}. */
204
+ id: number | null;
205
+ /** The SMTP `Message-ID`, when the sender supplied one. */
206
+ messageId: string;
207
+ from: string | null;
208
+ fromName: string | null;
209
+ to: string | null;
210
+ toName: string | null;
211
+ subject: string | null;
212
+ receivedAt: string | null;
213
+ /** A short plain-text preview of the body. */
214
+ preview: string | null;
215
+ }
216
+ /**
217
+ * The arguments of a mailbox search.
218
+ *
219
+ * `domainId` is required on the call (not in this shape) because the
220
+ * receive worker's search path is domain-scoped: one domain, one
221
+ * round-trip, one stable ordering. `GET /api/agent/domains` is the
222
+ * call that answers it.
223
+ */
224
+ interface SearchMessagesOptions {
225
+ /** The query. At least two characters — the platform refuses less. */
226
+ q: string;
227
+ /** The page size. */
228
+ limit?: number;
229
+ /** Which field to match. Defaults to `body` (subject + from + to + text). */
230
+ field?: "subject" | "from" | "to" | "body";
231
+ /** Which mailbox direction. Defaults to `receive`. */
232
+ type?: "receive" | "send";
233
+ }
234
+ /** The result of a mailbox search. */
235
+ interface SearchMessagesResult {
236
+ messages: SearchMessageHit[];
237
+ /** How many rows match the filter, ignoring `limit`. */
238
+ total: number;
239
+ domainId: string;
240
+ }
14
241
  /**
15
242
  * Composed send payload.
16
243
  *
@@ -30,6 +257,21 @@ interface SendOptions {
30
257
  to: string | string[];
31
258
  /** Optional reply-to override. */
32
259
  replyTo?: string;
260
+ /**
261
+ * Reply in thread: the SMTP `Message-ID` (or numeric id) of the
262
+ * message being answered.
263
+ *
264
+ * When set, the SDK backend resolves the parent row and derives
265
+ * the `In-Reply-To` / `References` headers and the thread anchor,
266
+ * so the recipient's mail client threads your message with the
267
+ * original conversation — and the dashboard shows it in the same
268
+ * thread. The caller supplies the **parent**, never the headers:
269
+ * deriving `References` by hand is how threads fork.
270
+ *
271
+ * A parent with no `Message-ID` header is rejected: there is
272
+ * nothing to point `In-Reply-To` at.
273
+ */
274
+ replyToMessageId?: string;
33
275
  /** Subject line — required, non-empty. */
34
276
  subject: string;
35
277
  /** Plain-text body. Required iff `html` is also missing. */
@@ -40,32 +282,203 @@ interface SendOptions {
40
282
  html?: string;
41
283
  /** Attachments. */
42
284
  attachments?: SendAttachment[];
285
+ /**
286
+ * Idempotency key — the same key under the same account and the
287
+ * same request returns the **original** result and does not send
288
+ * twice.
289
+ *
290
+ * Give every send a key you can rebuild after a timeout (a UUID
291
+ * per logical mail, not per attempt) and a retry becomes free: the
292
+ * backend replays the first answer instead of delivering a second
293
+ * message.
294
+ *
295
+ * The key is scoped to the **account**, not globally — two accounts
296
+ * may use the same string. Reusing one key for a *different* payload
297
+ * is a client bug and is refused with `idempotency_key_conflict`
298
+ * (409) rather than answered with the first result.
299
+ */
300
+ idempotencyKey?: string;
43
301
  }
44
302
  /**
45
- * Result of a successful send. Matches the marketing-copy promise
46
- * in `apps/web/app/routes/home.tsx`:
303
+ * Result of a successful send.
304
+ *
305
+ * `id` is the platform's row id; `messageId` is the SMTP `Message-ID`
306
+ * the relay assigned, which is the key every read path takes — pass
307
+ * it to {@link AgentMessages.get} to read a reply, or to
308
+ * {@link AgentMessages.status} to poll delivery.
309
+ *
310
+ * ## A send that failed
311
+ *
312
+ * The backend answers `201` for a send the relay **refused** — the
313
+ * message row exists, the mail does not. That used to be invisible:
314
+ * the answer was `{ id, status: "failed", messageId: "" }` with
315
+ * nothing else, so an agent could not tell a refused send from a
316
+ * lost one (the 2026-10-31 audit, P0-1).
317
+ *
318
+ * Two fields now say what happened:
319
+ *
320
+ * - `error` — the typed slug (`"send_failed"`), or `null` when the
321
+ * send did not fail. **It is never `null` on a failed send**, so
322
+ * "failed with no reason" is not a state the wire can be in.
323
+ * - `sendFeedback` — the relay's own reason, when it gave one
324
+ * (`null` when it did not).
47
325
  *
48
- * { "id": "msg_8421", "status": "queued" }
326
+ * Both are optional because the SDK also talks to older backends that
327
+ * did not send them; on those, `status` is the only signal.
49
328
  */
50
329
  interface SendResult {
51
330
  /** Numeric email row id (stringified for JSON safety). */
52
331
  id: string;
53
- /** Always `"queued"` for now; the SDK backend doesn't surface
54
- * the SMTP `delivered` / `bounced` lifecycle — that comes via
55
- * webhooks in a future milestone. */
56
- status: "queued";
332
+ /** The row's lifecycle state at send time. */
333
+ status: string;
334
+ /**
335
+ * The SMTP `Message-ID` the relay assigned (the receive worker's
336
+ * `resendEmailId`). Empty when the send failed before the relay
337
+ * accepted it.
338
+ */
339
+ messageId?: string;
340
+ /**
341
+ * The relay's reason for the failure, when the relay gave one —
342
+ * `null` when it did not, and `null` on a send that succeeded.
343
+ */
344
+ sendFeedback?: string | null;
345
+ /**
346
+ * The typed failure slug (`"send_failed"`), or `null` when the
347
+ * send did not fail.
348
+ *
349
+ * A failed send always carries one: `status: "failed"` with
350
+ * `error: null` is not a state the backend can answer.
351
+ */
352
+ error?: string | null;
353
+ }
354
+ /**
355
+ * The outbound half of a domain — what the platform last recorded
356
+ * about whether it can send.
357
+ *
358
+ * Read from `fm.me().sending`, the connection check's answer to
359
+ * "may this key's domain send?". It is the same verdict the
360
+ * dashboard shows, read from the same document, so the two cannot
361
+ * disagree.
362
+ */
363
+ interface AccountSendingState {
364
+ /**
365
+ * True only when the domain can send right now.
366
+ *
367
+ * Read it **with** `state`: `canSend: false` with
368
+ * `state: "unknown"` means "we have not looked", while
369
+ * `canSend: false` with `state: "not_onboarded"` means the domain
370
+ * is not on Cloudflare Email Sending and no send will succeed.
371
+ */
372
+ canSend: boolean;
373
+ /**
374
+ * The outbound verdict, in the platform's vocabulary: `ready`,
375
+ * `not_onboarded`, `disabled`, `unconfigured`, `unlocked`,
376
+ * `misconfigured`, `no_credential`, `unknown` or `error`.
377
+ */
378
+ state: string;
379
+ /** The detail the platform recorded with the verdict. */
380
+ detail: string | null;
381
+ /**
382
+ * When the sending half was last probed, in epoch milliseconds —
383
+ * `null` when it never was. The platform probes on demand, so an
384
+ * old stamp means the answer may be out of date.
385
+ */
386
+ checkedAt: number | null;
387
+ }
388
+ /**
389
+ * What the credential behind the client is allowed to do, and which
390
+ * account it belongs to.
391
+ *
392
+ * This is the **connection check** (`docs/agent-platform.md` §10.8
393
+ * AP-05): it answers "is my key live, which account is it, which
394
+ * domain may it send from, and what may it do?" without sending a
395
+ * single message — the only two ways to get that answer before it
396
+ * existed were to send real mail or to fail.
397
+ */
398
+ interface AccountInfo {
399
+ /** The account the credential belongs to. */
400
+ userId: string;
401
+ /**
402
+ * The domain the credential is bound to — the constraint on
403
+ * sending. `null` when the credential carries no binding.
404
+ */
405
+ domain: string | null;
406
+ /** The per-account receive worker the credential sends through. */
407
+ workerHost: string | null;
408
+ /**
409
+ * Which credential type answered: `"sdk_key"` (the dashboard's
410
+ * domain-bound API key) or `"agent_credential"` (a scoped
411
+ * credential issued for one set of capabilities).
412
+ */
413
+ credentialType: string;
414
+ /** The scopes this credential holds. */
415
+ scopes: string[];
416
+ /**
417
+ * The outbound half — **may this domain actually send?**
418
+ *
419
+ * `null` when the answer is not knowable: the credential carries no
420
+ * bound domain, the platform could not be read, or the domain has
421
+ * no row. `null` means "we do not know", which is different from
422
+ * "this domain cannot send" — read it with `state` before acting
423
+ * on it.
424
+ */
425
+ sending: AccountSendingState | null;
426
+ }
427
+ /**
428
+ * The account's receive worker, and the version of it.
429
+ *
430
+ * The receive worker lives in the customer's own Cloudflare account
431
+ * and does the actual receiving and sending; it is versioned, and an
432
+ * older one silently does less than the platform expects (no route
433
+ * tables before `1.4.0`, no Message-ID lookup before `1.5.1`, no event
434
+ * reporting before `1.6.0`). An agent that cannot see the version
435
+ * cannot tell why its events are empty.
436
+ */
437
+ interface WorkerVersionInfo {
438
+ /**
439
+ * The version the platform last deployed for this account — `null`
440
+ * when it has no record (a worker deployed outside the platform
441
+ * leaves it stale, so read {@link lastDeployAt} with it).
442
+ */
443
+ version: string | null;
444
+ /** The worker host this account's mail flows through. */
445
+ workerHost: string | null;
446
+ /** Whether the worker finished its own bootstrap (schema migrations). */
447
+ bootstrapped: boolean;
448
+ /** When the platform last deployed this worker (ISO-8601), or `null`. */
449
+ lastDeployAt: string | null;
450
+ /** The last deploy error, when one happened, or `null`. */
451
+ lastDeployError: string | null;
57
452
  }
58
453
  interface FlowmailsOptions {
59
454
  /** `fm_<32+hex>` API key issued in `apps/web/app/routes/dashboard/settings/api-keys.tsx`. */
60
455
  apiKey: string;
61
456
  /** Override the SDK backend base URL. Defaults to `https://sdk.flowmails.net`. */
62
457
  baseURL?: string;
458
+ /**
459
+ * The **platform** origin, used by the listen half of the surface
460
+ * (`fm.events`, `fm.messages`, `fm.waits`, `fm.addresses`). The
461
+ * send path goes to {@link baseURL} (the SDK backend); the event
462
+ * log, the durable wait and the message read live on the platform
463
+ * worker, which is a different deployment.
464
+ *
465
+ * Defaults to `https://flowmails.net`. Set it for a self-hosted or
466
+ * staging deployment — the same API key authenticates both.
467
+ */
468
+ platformURL?: string;
63
469
  /** Inject a `fetch` implementation (Workers environments, test harnesses). */
64
470
  fetch?: typeof globalThis.fetch;
65
471
  /**
66
- * Number of automatic retries on transient failures (5xx, 408,
67
- * 429). Defaults to 2. Set to 0 to disable. The retry budget is
68
- * bounded; doesn't apply to 4xx validation / auth failures.
472
+ * Number of automatic retries on transient failures (5xx, 408, and
473
+ * a 429 that asks for another attempt). Defaults to 2. Set to 0 to
474
+ * disable. The retry budget is bounded; doesn't apply to 4xx
475
+ * validation / auth failures.
476
+ *
477
+ * A **quota** refusal (429 `rate_limit_exceeded`) is deliberately
478
+ * NOT retried: the window is an hour, a retry inside it cannot
479
+ * succeed, and it would only burn another slot. The error carries
480
+ * `limit` / `remaining` / `resetAt` so the caller can wait for the
481
+ * window instead of guessing.
69
482
  */
70
483
  maxRetries?: number;
71
484
  /**
@@ -79,26 +492,270 @@ interface FlowmailsOptions {
79
492
  declare class Flowmails {
80
493
  private readonly apiKey;
81
494
  private readonly baseURL;
495
+ private readonly platformURL;
82
496
  private readonly fetchFn;
83
497
  private readonly maxRetries;
84
498
  private readonly requestId?;
85
499
  constructor(opts: FlowmailsOptions);
86
500
  /**
87
- * Send mail through the SDK backend. The only v0.1 endpoint.
501
+ * Send mail through the SDK backend.
502
+ *
503
+ * Pass `replyToMessageId` to answer a message in thread — the SDK
504
+ * backend resolves the parent and derives the `In-Reply-To` /
505
+ * `References` headers and the thread anchor, so the recipient's
506
+ * client threads it with the original conversation.
88
507
  *
89
- * Returns `{ id, status: "queued" }` on success; throws one of
508
+ * Returns `{ id, status, messageId }` on success; throws one of
90
509
  * `AuthenticationError` / `ValidationError` / `RateLimitError` /
91
510
  * `UpstreamError` on failure (all subclasses of `FlowmailsError`).
511
+ *
512
+ * **A send the relay refused is not a throw.** The backend answers
513
+ * `201` with `status: "failed"`, and the result carries the
514
+ * reason: `error` is the typed slug and `sendFeedback` is the
515
+ * relay's own words. Check `result.error` before treating a `201`
516
+ * as "sent".
92
517
  */
93
518
  send(opts: SendOptions): Promise<SendResult>;
94
519
  /**
95
- * Private: low-level request helper with retry+backoff+error
96
- * mapping. SDK callers must use the typed `send()` method
97
- * instead — this exists so future public methods can share the
98
- * same retry budget / error class mapping without re-implementing.
520
+ * The connection check — who the credential is.
521
+ *
522
+ * `flowmails test` (the CLI's documented first command) and every
523
+ * "is my setup right?" question end here. It verifies the key,
524
+ * names the account, names the bound domain and reports the
525
+ * scopes — and it sends nothing, so running it can never mail
526
+ * somebody by accident.
527
+ *
528
+ * It also answers the question the 2026-10-31 audit (P0-1) found
529
+ * missing: **may this domain actually send?** — `info.sending`
530
+ * carries the platform's own verdict, read from the same document
531
+ * the dashboard reads.
532
+ *
533
+ * ```ts
534
+ * const me = await fm.me();
535
+ * if (me.sending && !me.sending.canSend) {
536
+ * // me.sending.state says why: "not_onboarded", "unknown", …
537
+ * }
538
+ * ```
539
+ *
540
+ * @throws {AuthenticationError} when the key is missing, malformed
541
+ * or revoked.
542
+ */
543
+ me(): Promise<AccountInfo>;
544
+ /**
545
+ * The account's receive worker, and the version of it.
546
+ *
547
+ * The receive worker does the actual receiving and sending, and it
548
+ * is versioned: `1.4.0` brought the route tables, `1.5.1` the
549
+ * Message-ID lookup, `1.6.0` the event reporting that fills the
550
+ * log this SDK reads. An agent whose worker is older than the
551
+ * platform expects sees an empty event log and has no way to tell
552
+ * "no mail yet" from "my worker cannot report".
553
+ *
554
+ * ```ts
555
+ * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });
556
+ * const worker = await fm.workerVersion();
557
+ * if (!worker.version || worker.version < "1.6.0") { … }
558
+ * ```
559
+ *
560
+ * @throws {AuthenticationError} when the key is missing, malformed
561
+ * or revoked.
562
+ */
563
+ workerVersion(): Promise<WorkerVersionInfo>;
564
+ /**
565
+ * The event log — the listen half of the surface, read with a
566
+ * cursor.
567
+ *
568
+ * ```ts
569
+ * const fm = new Flowmails({ apiKey: process.env.FLOWMAILS_API_KEY! });
570
+ * let after: string | undefined;
571
+ * for (;;) {
572
+ * const page = await fm.events.list({ after, subject: "invoice" });
573
+ * for (const event of page.events) { … }
574
+ * after = page.nextCursor ?? after;
575
+ * }
576
+ * ```
577
+ */
578
+ readonly events: AgentEvents;
579
+ /**
580
+ * Read one message by its SMTP `Message-ID` — the id the event
581
+ * carried.
582
+ *
583
+ * The event log deliberately hands over routing facts and a
584
+ * subject and never a body (§4.2), so the content is an explicit
585
+ * ask. This is that ask.
586
+ */
587
+ readonly messages: AgentMessages;
588
+ /**
589
+ * The conversation a message belongs to.
590
+ *
591
+ * The core listen/reply loop can store the message ids itself;
592
+ * this is for the agent that wants the platform to reconstruct the
593
+ * chain. The chain is read from the **conversation root's** SMTP
594
+ * `Message-ID`, which is exactly what `email.threadId` holds.
595
+ */
596
+ readonly threads: AgentThreads;
597
+ /**
598
+ * The durable wait — the one thing an agent cannot build for
599
+ * itself.
600
+ *
601
+ * A suspended HTTP request dies on the edge long before a
602
+ * verification mail arrives (minutes to hours later), so the wait
603
+ * is a row on the platform and the agent polls it. `create()`
604
+ * answers **immediately**; it does not block.
605
+ */
606
+ readonly waits: AgentWaits;
607
+ /**
608
+ * The addresses (mailboxes) the key's account owns, and the one
609
+ * narrow write the agent surface has: create a single one.
610
+ */
611
+ readonly addresses: AgentAddresses;
612
+ /**
613
+ * Private: the one request path, with retry + backoff + error
614
+ * mapping shared by every public method.
615
+ *
616
+ * `origin` is explicit because the surface spans two deployments:
617
+ * the SDK backend (`baseURL`) for sending, the platform
618
+ * (`platformURL`) for reading and waiting. `method` is explicit
619
+ * because the listen endpoints are GETs — the v0.1 helper was
620
+ * POST-only, which is why reading used to mean hand-rolling HTTP.
99
621
  */
100
622
  private request;
101
623
  }
624
+ /**
625
+ * The event log namespace — see {@link Flowmails.events}.
626
+ */
627
+ interface AgentEvents {
628
+ /**
629
+ * One page of the log, oldest first, after `opts.after`.
630
+ *
631
+ * The cursor is an **event id**, never a timestamp: two events can
632
+ * land in the same millisecond, and a cursor that can skip a row
633
+ * loses mail. An unknown cursor is a `ValidationError`, never an
634
+ * empty page — "no new events" would silently stop the agent
635
+ * seeing mail.
636
+ */
637
+ list(opts?: ListEventsOptions): Promise<ListEventsResult>;
638
+ }
639
+ /**
640
+ * The message-read namespace — see {@link Flowmails.messages}.
641
+ */
642
+ interface AgentMessages {
643
+ /** Fetch the full content of one message by SMTP `Message-ID`. */
644
+ get(messageId: string, opts?: {
645
+ domainId?: string;
646
+ }): Promise<MessageDetail>;
647
+ /** Poll a sent message's delivery state by row id or `Message-ID`. */
648
+ status(id: string): Promise<SendStatus>;
649
+ /**
650
+ * `search_emails`: look **back** through the mailbox.
651
+ *
652
+ * The event log is the primary listen path — a cursor over what
653
+ * just arrived. Search is the history path: "what did that
654
+ * supplier mail me last quarter?" is not an event-log question,
655
+ * and the event log carries no body.
656
+ *
657
+ * A result carries addressing, the subject and a short **preview**;
658
+ * the body is fetched per message with {@link AgentMessages.get},
659
+ * so a search is never a way to pull the whole mailbox through a
660
+ * query parameter.
661
+ */
662
+ search(domainId: string, opts: SearchMessagesOptions): Promise<SearchMessagesResult>;
663
+ }
664
+ /**
665
+ * The conversation namespace — see {@link Flowmails.threads}.
666
+ */
667
+ interface AgentThreads {
668
+ /**
669
+ * Read the conversation a message belongs to.
670
+ *
671
+ * `threadId` is the conversation **root's** SMTP `Message-ID` —
672
+ * the value `email.threadId` holds, never an intermediate parent's.
673
+ * An agent that holds an intermediate message id still gets the
674
+ * whole chain: the platform resolves it to its row and reads the
675
+ * chain from that row's own anchor.
676
+ */
677
+ get(threadId: string, opts?: {
678
+ domainId?: string;
679
+ }): Promise<ThreadDetail>;
680
+ }
681
+ /**
682
+ * The durable-wait namespace — see {@link Flowmails.waits}.
683
+ */
684
+ interface AgentWaits {
685
+ /** Open a wait. Answers immediately; poll {@link AgentWaits.get}. */
686
+ create(opts: CreateWaitOptions): Promise<CreateWaitResult>;
687
+ /** Read a wait. A wait past its deadline reads as `expired`. */
688
+ get(waitId: string): Promise<WaitStatus>;
689
+ }
690
+ /**
691
+ * The address namespace — see {@link Flowmails.addresses}.
692
+ */
693
+ interface AgentAddresses {
694
+ /** `list_domains`: every domain on the key's account. */
695
+ listDomains(): Promise<AgentDomain[]>;
696
+ /** `list_addresses`: one domain's local parts and routing mode. */
697
+ list(domainId: string): Promise<{
698
+ domainId: string;
699
+ domain: string;
700
+ routingMode: "catchall" | "rules";
701
+ localParts: string[];
702
+ addresses: string[];
703
+ /** True when every local part already delivers (catch-all mode). */
704
+ acceptsAnyLocalPart: boolean;
705
+ }>;
706
+ /**
707
+ * `create_address`: add **one** local part.
708
+ *
709
+ * Idempotent — creating an address that already exists answers
710
+ * with `created: false` rather than an error. It never changes the
711
+ * routing mode, never removes a part and never clears the table:
712
+ * mode changes and route-table editing stay dashboard-only.
713
+ */
714
+ create(domainId: string, localPart: string): Promise<CreateAddressResult>;
715
+ }
716
+ /**
717
+ * A sent message's delivery state.
718
+ *
719
+ * `status` is the receive worker's lifecycle literal, so an agent can
720
+ * distinguish "the relay took it" from "the recipient's server
721
+ * accepted it" from "it bounced" — the v0.1 SDK collapsed all of them
722
+ * into `"queued"` and dropped the relay's `Message-ID` with them.
723
+ */
724
+ interface SendStatus {
725
+ /** The worker's row id. */
726
+ id: string;
727
+ /**
728
+ * `sent` (the relay accepted it) or `failed` (the relay rejected it)
729
+ * — those are the two the receive worker writes for an outbound
730
+ * message today.
731
+ *
732
+ * The vocabulary also holds `delivered` / `bounced` / `complained` /
733
+ * `delayed`, and the backend maps them if they appear, but the
734
+ * worker has no DSN or bounce ingestion and never writes them. **A
735
+ * bounce is not observable today.**
736
+ */
737
+ status: string;
738
+ /** The SMTP `Message-ID`; empty when the relay never accepted it. */
739
+ messageId: string;
740
+ /**
741
+ * The relay's error string when `status` is `failed`, else null.
742
+ *
743
+ * The same reason the send response carries — read from the same
744
+ * column on the same worker.
745
+ */
746
+ sendFeedback: string | null;
747
+ /**
748
+ * The typed failure slug (`"send_failed"`) when `status` is
749
+ * `failed`, else `null`.
750
+ *
751
+ * Optional: an older backend does not send it. When it is present,
752
+ * a `failed` status always carries one — "failed with no reason" is
753
+ * not a state the wire can be in.
754
+ */
755
+ error?: string | null;
756
+ /** `CURRENT_TIMESTAMP` from the worker; opaque to the SDK. */
757
+ createdAt: string | null;
758
+ }
102
759
 
103
760
  /**
104
761
  * Public error hierarchy. Mirrors the SDK backend's JSON contract
@@ -134,9 +791,29 @@ declare class ValidationError extends FlowmailsError {
134
791
  }
135
792
  /**
136
793
  * 408 / 429 — request was rate-limited or timed out. Retryable.
794
+ *
795
+ * A 429 from Flowmails is either a **quota refusal**
796
+ * (`rate_limit_exceeded`) or a request that is **already running**
797
+ * (`idempotency_key_in_progress`). The two need different handling,
798
+ * so the quota facts travel on the error:
799
+ *
800
+ * - `limit` — the limit that was hit.
801
+ * - `remaining` — how many sends are left in the window (`0` when the
802
+ * quota is exhausted).
803
+ * - `resetAt` — ISO-8601 instant the window rolls over.
137
804
  */
138
805
  declare class RateLimitError extends FlowmailsError {
139
- constructor(code?: string, status?: number);
806
+ /** The limit that was hit, when the server named one. */
807
+ readonly limit?: number;
808
+ /** The sends left in the window, when the server named one. */
809
+ readonly remaining?: number;
810
+ /** ISO-8601 instant the window rolls over, when the server named one. */
811
+ readonly resetAt?: string;
812
+ constructor(code?: string, status?: number, facts?: {
813
+ limit?: number;
814
+ remaining?: number;
815
+ resetAt?: string;
816
+ });
140
817
  }
141
818
  /**
142
819
  * 502 / 504 — the SDK backend couldn't reach the upstream
@@ -148,4 +825,4 @@ declare class UpstreamError extends FlowmailsError {
148
825
  constructor(code: string, upstreamMessage: string | undefined, status?: number);
149
826
  }
150
827
 
151
- export { AuthenticationError, Flowmails, FlowmailsError, type FlowmailsOptions, RateLimitError, type SendAttachment, type SendOptions, type SendResult, UpstreamError, ValidationError };
828
+ export { type AccountInfo, type AccountSendingState, type AgentAddress, type AgentAddresses, type AgentDomain, type AgentEvent, type AgentEvents, type AgentMessages, type AgentThreads, type AgentWaits, AuthenticationError, type CreateAddressResult, type CreateWaitOptions, type CreateWaitResult, Flowmails, FlowmailsError, type FlowmailsOptions, type ListEventsOptions, type ListEventsResult, type MessageDetail, RateLimitError, type SearchMessageHit, type SearchMessagesOptions, type SearchMessagesResult, type SendAttachment, type SendOptions, type SendResult, type SendStatus, type ThreadDetail, type ThreadMessage, UpstreamError, ValidationError, type WaitStatus, type WorkerVersionInfo };