@flowmails/flowmails-sdk 0.2.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -77,6 +77,29 @@ interface CreateWaitOptions {
77
77
  */
78
78
  timeoutMs?: number;
79
79
  }
80
+ /**
81
+ * How a wait's resolution is delivered besides the poll.
82
+ *
83
+ * The wait's resolution is also delivered as the `wait.resolved`
84
+ * webhook event, on the account's verified outbound webhook — signed,
85
+ * retried and logged. An agent with **no long-running process** (a
86
+ * serverless function, a CI job, a webhook-driven service) therefore
87
+ * does not have to write a polling loop to learn that a mail landed.
88
+ * Polling the wait keeps working either way.
89
+ *
90
+ * ## Why the name is a literal here
91
+ *
92
+ * The SDK is **dependency-free** by design — it is published to npm
93
+ * and the workspace package that holds the contract is private, so
94
+ * this package cannot import the constant the contract file holds.
95
+ *
96
+ * The two are therefore kept in step by a **test**, not by an import:
97
+ * `test/web-agent-sdk-cli-mcp-push-vocabulary.test.mjs` asserts that
98
+ * this string, the CLI's copy and the MCP tool descriptions are all
99
+ * the same value as the shared contract's `AGENT_WAIT_PUSH_EVENT`. A
100
+ * rename is a failing test, not a drift.
101
+ */
102
+ declare const WAIT_RESOLVED_EVENT = "wait.resolved";
80
103
  /** A durable wait, as the platform reports it. */
81
104
  interface WaitStatus {
82
105
  waitId: string;
@@ -89,6 +112,17 @@ interface WaitStatus {
89
112
  resolvedMessageId: string | null;
90
113
  /** ISO-8601 deadline. A wait past it reads as `expired`. */
91
114
  expiresAt: string | number;
115
+ /**
116
+ * How this wait's resolution is also delivered.
117
+ *
118
+ * The event name is the same one the CLI and the MCP tool
119
+ * descriptions name — a client that reads one of them reads the
120
+ * same fact as a client that reads another.
121
+ */
122
+ push?: {
123
+ /** The webhook event this wait's resolution is delivered as. */
124
+ event: typeof WAIT_RESOLVED_EVENT;
125
+ };
92
126
  }
93
127
  /**
94
128
  * A newly-opened wait.
@@ -102,10 +136,36 @@ interface CreateWaitResult extends WaitStatus {
102
136
  /** A hint for the poll loop: check again in a few seconds. */
103
137
  pollAfterMs: number;
104
138
  }
139
+ /**
140
+ * One verification code the platform extracted **on read**.
141
+ *
142
+ * `source` says where it came from: a code in the subject line is the
143
+ * strongest signal there is.
144
+ */
145
+ interface ExtractedVerificationCode {
146
+ code: string;
147
+ source: "subject" | "body";
148
+ }
149
+ /** One authentication-shaped link the platform extracted. */
150
+ interface ExtractedMagicLink {
151
+ url: string;
152
+ label?: string;
153
+ }
154
+ /**
155
+ * The structured facts a message carries.
156
+ *
157
+ * Deterministic — the platform runs the same rules on every read, with no
158
+ * model and no clock — so the same message answers the same thing twice.
159
+ * Both lists are usually empty.
160
+ */
161
+ interface ExtractedContent {
162
+ verificationCodes: ExtractedVerificationCode[];
163
+ magicLinks: ExtractedMagicLink[];
164
+ }
105
165
  /** The full content of one message. Fetched, never pushed. */
106
166
  interface MessageDetail {
107
- /** The worker's numeric row id. */
108
- id: number | string;
167
+ /** The mailstore's UUIDv7 row id. */
168
+ id: string;
109
169
  /** The SMTP `Message-ID` the event carried. */
110
170
  messageId: string;
111
171
  from: string;
@@ -115,16 +175,64 @@ interface MessageDetail {
115
175
  subject: string | null;
116
176
  /** Plain-text body. Ideal for regexing a verification code out. */
117
177
  text: string | null;
118
- /** Rendered HTML body, when the message had one. */
178
+ /**
179
+ * Rendered HTML body, when the message had one.
180
+ *
181
+ * `null` when {@link GetMessageOptions.format} was `"markdown"` — that
182
+ * mode omits the raw markup on purpose.
183
+ */
119
184
  html: string | null;
185
+ /**
186
+ * A clean Markdown projection of the HTML body: head/style/script,
187
+ * hidden preheader text and tracking pixels removed; headings, lists,
188
+ * links and emphasis kept.
189
+ */
190
+ markdown: string | null;
191
+ /** Verification codes and authentication links, extracted on read. */
192
+ extracted: ExtractedContent | null;
193
+ /**
194
+ * The prompt-injection verdict — the firewall's read-time answer about this
195
+ * message.
196
+ *
197
+ * Present when the domain's firewall mode is not `off`; absent (not `null`)
198
+ * when the domain does not scan, so "not scanned" and "scanned clean" stay
199
+ * distinguishable. `hidden_payload` means an instruction was concealed in
200
+ * the HTML (a `display:none` block, an HTML comment, or a run of invisible
201
+ * characters) — the shape a human reading the mail would never see.
202
+ *
203
+ * The `signals[].evidence` strings are **untrusted text**. Escape them, and
204
+ * never treat them as an instruction.
205
+ */
206
+ security?: MessageSecurity;
120
207
  receivedAt: string | null;
121
208
  attachments: Array<{
209
+ /** The attachment id — what {@link AgentMessages.attachmentText} takes. */
210
+ id: string | null;
122
211
  filename: string | null;
123
212
  mimeType: string | null;
124
213
  size: number | null;
125
214
  url: string | null;
126
215
  }>;
127
216
  }
217
+ /** One matched signal behind a message's prompt-injection verdict. */
218
+ interface MessageSecuritySignal {
219
+ /**
220
+ * `instruction_override` | `role_hijack` | `data_exfiltration` |
221
+ * `tool_abuse` | `hidden_payload`.
222
+ */
223
+ kind: string;
224
+ /** The points this signal contributed. */
225
+ weight: number;
226
+ /** A bounded snippet of the matched text. Untrusted. */
227
+ evidence: string;
228
+ }
229
+ /** The prompt-injection verdict for one message. */
230
+ interface MessageSecurity {
231
+ promptInjectionRisk: "none" | "low" | "medium" | "high";
232
+ /** `0..=100`. */
233
+ score: number;
234
+ signals: MessageSecuritySignal[];
235
+ }
128
236
  /** One address (mailbox) the platform accepts mail for. */
129
237
  interface AgentAddress {
130
238
  address: string;
@@ -142,7 +250,10 @@ interface AgentDomain {
142
250
  name: string;
143
251
  routingMode: "catchall" | "rules";
144
252
  localParts: string[];
145
- /** False when the per-account receive worker is not deployed yet. */
253
+ /**
254
+ * False when the domain's route table is not bound in the mail
255
+ * worker yet — its mail is not being accepted.
256
+ */
146
257
  ready: boolean;
147
258
  }
148
259
  /** Result of {@link AgentAddresses.create}. */
@@ -192,6 +303,186 @@ interface ThreadDetail {
192
303
  /** The chain, oldest first. */
193
304
  messages: ThreadMessage[];
194
305
  }
306
+ /** The four states a draft can be in. */
307
+ declare const DRAFT_STATUS_NAMES: readonly ["pending_review", "approved", "rejected", "sent"];
308
+ type DraftStatusName = (typeof DRAFT_STATUS_NAMES)[number];
309
+ /**
310
+ * A message an agent wrote that a **person** has not approved yet.
311
+ *
312
+ * ## Why this is not a gated send
313
+ *
314
+ * Sending is the agent's decision (`docs/agent-platform.md` §3), and
315
+ * `fm.send()` still sends immediately. The draft is a **different
316
+ * capability**: `drafts:write` (without `messages:send`) lets a
317
+ * credential prepare a message and deliver nothing. Nothing leaves
318
+ * until a human approves it from the dashboard, and the approval
319
+ * dispatches through the platform's own audited send path.
320
+ *
321
+ * ```ts
322
+ * const draft = await fm.drafts.create({
323
+ * from: "support@acme.test",
324
+ * to: "customer@example.com",
325
+ * subject: "Re: your invoice",
326
+ * replyToMessageId: event.messageId,
327
+ * useAiContext: true,
328
+ * });
329
+ * // …nothing has been sent. Poll the outcome:
330
+ * const later = await fm.drafts.get(draft.id);
331
+ * // later.status: "pending_review" | "sent" | "rejected"
332
+ * ```
333
+ */
334
+ interface EmailDraft {
335
+ id: string;
336
+ domainId: string;
337
+ from: string;
338
+ fromName: string | null;
339
+ to: string[];
340
+ replyTo: string | null;
341
+ replyToMessageId: string | null;
342
+ subject: string;
343
+ text: string | null;
344
+ html: string | null;
345
+ status: DraftStatusName;
346
+ source: "agent" | "human";
347
+ useAiContext: boolean;
348
+ aiRoleName: string | null;
349
+ /** Which credential wrote it; `null` when a human wrote it. */
350
+ createdByCredentialType: string | null;
351
+ /** The reviewer's note, on an approved or rejected draft. */
352
+ reviewNote: string | null;
353
+ /** The relay's SMTP `Message-ID`, once sent. */
354
+ sentMessageId: string | null;
355
+ sentEmailId: string | null;
356
+ createdAt: number;
357
+ updatedAt: number;
358
+ reviewedAt: number | null;
359
+ }
360
+ /**
361
+ * Options for {@link AgentDrafts.create}.
362
+ *
363
+ * `text` or `html` is required for a hand-written draft. With
364
+ * `useAiContext: true` both are optional and `replyToMessageId` is
365
+ * required — the body is generated from the message being answered and
366
+ * the domain's knowledge base.
367
+ */
368
+ interface CreateDraftOptions {
369
+ from: string;
370
+ fromName?: string;
371
+ to: string | string[];
372
+ subject: string;
373
+ text?: string;
374
+ html?: string;
375
+ replyTo?: string;
376
+ replyToMessageId?: string;
377
+ /**
378
+ * Draft the reply from the domain's AI context instead of a
379
+ * hand-written body. A plan without AI context answers `402`.
380
+ */
381
+ useAiContext?: boolean;
382
+ }
383
+ /** Options for {@link AgentDrafts.list}. */
384
+ interface ListDraftsOptions {
385
+ status?: DraftStatusName;
386
+ domainId?: string;
387
+ limit?: number;
388
+ }
389
+ /** The answer of {@link AgentDrafts.list}. */
390
+ interface ListDraftsResult {
391
+ drafts: EmailDraft[];
392
+ total: number;
393
+ }
394
+ /**
395
+ * The agent's own record of what it did with one message.
396
+ *
397
+ * The event log says a mail arrived; this says whether the agent
398
+ * already handled it. An agent that restarts reads it back to tell
399
+ * "I never saw this" from "I saw it and never finished".
400
+ */
401
+ interface MessageState {
402
+ /** The SMTP `Message-ID` — the id the event log carried. */
403
+ messageId: string;
404
+ /** The platform domain id whose mailbox received the message. */
405
+ domainId: string;
406
+ /**
407
+ * `pending` → `processing` → `done` | `failed`.
408
+ *
409
+ * The platform records what the agent wrote and never moves a row
410
+ * on its own — there is no rule engine and no sweeper behind it.
411
+ */
412
+ state: "pending" | "processing" | "done" | "failed";
413
+ /** Short labels the agent attached to the message. */
414
+ labels: string[];
415
+ /** A free-text note about what the agent did. */
416
+ note: string | null;
417
+ /** Who holds the claim, when the message is `processing`. */
418
+ claimedBy: string | null;
419
+ /** ISO-8601 timestamp of the claim. */
420
+ claimedAt: string | number | null;
421
+ /** ISO-8601 timestamp of the last write. */
422
+ updatedAt: string | number;
423
+ /** ISO-8601 timestamp of when the row was created. */
424
+ createdAt?: string | number;
425
+ }
426
+ /**
427
+ * The state names the platform accepts, in the platform's order.
428
+ *
429
+ * The vocabulary is this one list: the {@link MessageStateName} union
430
+ * below is derived from it, and the SDK's own validation reads it, so a
431
+ * name cannot exist in one place and be refused in the other.
432
+ */
433
+ declare const MESSAGE_STATE_NAMES: readonly ["pending", "processing", "done", "failed"];
434
+ /**
435
+ * The vocabulary of {@link MessageState.state}, as a named union so a
436
+ * caller can pass one without re-typing the literal at every call
437
+ * site.
438
+ */
439
+ type MessageStateName = (typeof MESSAGE_STATE_NAMES)[number];
440
+ /**
441
+ * Options for {@link AgentMessages.listStates}.
442
+ */
443
+ interface ListMessageStatesOptions {
444
+ /**
445
+ * Only the states in this one — `pending`, `processing`, `done` or
446
+ * `failed`.
447
+ *
448
+ * The resume-after-restart read is most useful with
449
+ * `processing`: those are the messages this agent took and never
450
+ * finished.
451
+ */
452
+ state?: MessageStateName;
453
+ /** Narrow to one message. */
454
+ messageId?: string;
455
+ /** The page size. */
456
+ limit?: number;
457
+ }
458
+ /**
459
+ * The agent's own per-message state, read back.
460
+ */
461
+ interface ListMessageStatesResult {
462
+ /** One row per message the calling credential has a state for. */
463
+ states: MessageState[];
464
+ }
465
+ /** Options for {@link AgentMessages.claim}. */
466
+ interface ClaimMessageOptions {
467
+ /** The platform domain id whose mailbox received the message. */
468
+ domainId: string;
469
+ /**
470
+ * Which worker of yours holds the claim, e.g. `worker-1`.
471
+ * Defaults to the credential.
472
+ */
473
+ claimedBy?: string;
474
+ }
475
+ /** Options for {@link AgentMessages.complete}. */
476
+ interface CompleteMessageOptions {
477
+ /** The platform domain id whose mailbox received the message. */
478
+ domainId: string;
479
+ /** `done` when finished with it, `failed` when it did not succeed. */
480
+ state: "done" | "failed";
481
+ /** Short labels to attach, e.g. `["invoice"]`. */
482
+ labels?: string[];
483
+ /** A short free-text note about what the agent did. */
484
+ note?: string;
485
+ }
195
486
  /**
196
487
  * One search hit.
197
488
  *
@@ -200,8 +491,8 @@ interface ThreadDetail {
200
491
  * when the agent decides a message matters.
201
492
  */
202
493
  interface SearchMessageHit {
203
- /** The worker's row id. Accepted by {@link AgentMessages.get}. */
204
- id: number | null;
494
+ /** The mailstore's UUIDv7 row id. Accepted by {@link AgentMessages.get}. */
495
+ id: string | null;
205
496
  /** The SMTP `Message-ID`, when the sender supplied one. */
206
497
  messageId: string;
207
498
  from: string | null;
@@ -250,15 +541,21 @@ interface SendOptions {
250
541
  * to (the SDK backend enforces this with a 422 on mismatch).
251
542
  */
252
543
  from: string;
253
- /** Display name for the sender; the email-worker falls back to the
254
- * local-part capitalised. */
544
+ /**
545
+ * Display name for the sender, e.g. `"Billing"`.
546
+ *
547
+ * Optional: when it is absent the mail worker stores the address's
548
+ * local part **verbatim** (`billing@…` → `billing`), so the column is
549
+ * never blank. It does not capitalise it — a display name is the
550
+ * caller's choice.
551
+ */
255
552
  fromName?: string;
256
553
  /** One recipient or an array. */
257
554
  to: string | string[];
258
555
  /** Optional reply-to override. */
259
556
  replyTo?: string;
260
557
  /**
261
- * Reply in thread: the SMTP `Message-ID` (or numeric id) of the
558
+ * Reply in thread: the SMTP `Message-ID` (or mailstore row UUID) of the
262
559
  * message being answered.
263
560
  *
264
561
  * When set, the SDK backend resolves the parent row and derives
@@ -282,6 +579,23 @@ interface SendOptions {
282
579
  html?: string;
283
580
  /** Attachments. */
284
581
  attachments?: SendAttachment[];
582
+ /**
583
+ * Send **one message per recipient** — the default — or one shared
584
+ * message for everybody.
585
+ *
586
+ * `true` (the default): every recipient gets their own message. They
587
+ * cannot see each other, one refused address does not hold up the
588
+ * others, and {@link SendResult.recipients} reports what happened to
589
+ * **each** address. `false`: everybody is on one envelope — one
590
+ * message, one relay call, one bill from a provider that charges per
591
+ * message — and then a single refused address refuses the whole
592
+ * send, because there was only ever one send.
593
+ *
594
+ * The default is per-recipient because a partial failure has to be
595
+ * observable. With one shared envelope the answer is all-or-nothing
596
+ * by construction.
597
+ */
598
+ perRecipient?: boolean;
285
599
  /**
286
600
  * Idempotency key — the same key under the same account and the
287
601
  * same request returns the **original** result and does not send
@@ -307,6 +621,14 @@ interface SendOptions {
307
621
  * it to {@link AgentMessages.get} to read a reply, or to
308
622
  * {@link AgentMessages.status} to poll delivery.
309
623
  *
624
+ * ## `status` is the send's verdict
625
+ *
626
+ * `status` is the **aggregate** over every recipient:
627
+ *
628
+ * - `"sent"` — everybody was accepted;
629
+ * - `"partial"` — some were accepted and some were refused;
630
+ * - `"failed"` — nobody was accepted.
631
+ *
310
632
  * ## A send that failed
311
633
  *
312
634
  * The backend answers `201` for a send the relay **refused** — the
@@ -317,9 +639,11 @@ interface SendOptions {
317
639
  *
318
640
  * Two fields now say what happened:
319
641
  *
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.
642
+ * - `error` — the typed slug (`"send_failed"`), or `null` when every
643
+ * recipient was accepted. **It is never `null` on a failed or a
644
+ * partial send**, so "failed with no reason" is not a state the
645
+ * wire can be in, and "check `result.error` before treating a 201
646
+ * as sent" stays true.
323
647
  * - `sendFeedback` — the relay's own reason, when it gave one
324
648
  * (`null` when it did not).
325
649
  *
@@ -329,7 +653,7 @@ interface SendOptions {
329
653
  interface SendResult {
330
654
  /** Numeric email row id (stringified for JSON safety). */
331
655
  id: string;
332
- /** The row's lifecycle state at send time. */
656
+ /** The send's aggregate state at send time. */
333
657
  status: string;
334
658
  /**
335
659
  * The SMTP `Message-ID` the relay assigned (the receive worker's
@@ -343,13 +667,46 @@ interface SendResult {
343
667
  */
344
668
  sendFeedback?: string | null;
345
669
  /**
346
- * The typed failure slug (`"send_failed"`), or `null` when the
347
- * send did not fail.
670
+ * The typed failure slug (`"send_failed"`), or `null` when the send
671
+ * did not fail.
348
672
  *
349
673
  * A failed send always carries one: `status: "failed"` with
350
- * `error: null` is not a state the backend can answer.
674
+ * `error: null` is not a state the backend can answer. A **partial**
675
+ * send carries it too — `status: "partial"` says *some* recipients
676
+ * were refused, and `error` says "not all of them got through".
351
677
  */
352
678
  error?: string | null;
679
+ /**
680
+ * One entry per recipient — what happened to **each** address.
681
+ *
682
+ * This is the per-recipient detail a multi-recipient send needs:
683
+ * "the first two went out and the third was refused because X" is a
684
+ * fact the audit log must not flatten, and the answer must not
685
+ * flatten it either.
686
+ *
687
+ * Absent on a body written by an older backend, which had no such
688
+ * field. On those, `status` is the whole answer.
689
+ */
690
+ recipients?: SendRecipientResult[];
691
+ }
692
+ /**
693
+ * One recipient's outcome inside a send.
694
+ *
695
+ * In per-recipient mode each address is its own message, its own row
696
+ * and its own relay call — so this entry is that message: its id, its
697
+ * verdict, and the relay's reason when the relay refused it.
698
+ */
699
+ interface SendRecipientResult {
700
+ /** The address this entry is about. */
701
+ to: string;
702
+ /** The platform's row id for the message that carried it. */
703
+ id: string;
704
+ /** Whether the relay accepted this recipient's message. */
705
+ status: "sent" | "failed";
706
+ /** The SMTP `Message-ID`, when the relay assigned one. */
707
+ messageId?: string;
708
+ /** The relay's reason, when the relay gave one. */
709
+ sendFeedback?: string | null;
353
710
  }
354
711
  /**
355
712
  * The outbound half of a domain — what the platform last recorded
@@ -364,16 +721,26 @@ interface AccountSendingState {
364
721
  /**
365
722
  * True only when the domain can send right now.
366
723
  *
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.
724
+ * Read it **with** `configured` and `state`: `configured: false`
725
+ * means sending was never set up (it is optional), while a
726
+ * configured domain can still be temporarily `canSend: false` with
727
+ * `state: "setup_required"`, `"misconfigured"`, etc.
371
728
  */
372
729
  canSend: boolean;
373
730
  /**
374
- * The outbound verdict, in the platform's vocabulary: `ready`,
375
- * `not_onboarded`, `disabled`, `unconfigured`, `unlocked`,
376
- * `misconfigured`, `no_credential`, `unknown` or `error`.
731
+ * Whether an outbound provider is configured for the bound domain.
732
+ *
733
+ * Sending is optional. `false` means sending was never set up — a
734
+ * different answer from "configured but currently broken", which also
735
+ * reads `canSend: false`. Enable it from the domain page in the
736
+ * dashboard.
737
+ */
738
+ configured: boolean;
739
+ /**
740
+ * The outbound verdict, in the platform's neutral vocabulary:
741
+ * `ready`, `setup_required`, `unverified`, `misconfigured`,
742
+ * `disabled`, `no_credential`, `credential_rejected`, `unknown` or
743
+ * `error`.
377
744
  */
378
745
  state: string;
379
746
  /** The detail the platform recorded with the verdict. */
@@ -403,8 +770,6 @@ interface AccountInfo {
403
770
  * sending. `null` when the credential carries no binding.
404
771
  */
405
772
  domain: string | null;
406
- /** The per-account receive worker the credential sends through. */
407
- workerHost: string | null;
408
773
  /**
409
774
  * Which credential type answered: `"sdk_key"` (the dashboard's
410
775
  * domain-bound API key) or `"agent_credential"` (a scoped
@@ -425,25 +790,22 @@ interface AccountInfo {
425
790
  sending: AccountSendingState | null;
426
791
  }
427
792
  /**
428
- * The account's receive worker, and the version of it.
793
+ * The shared mail worker, and the version of it.
429
794
  *
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.
795
+ * The mail worker is **Flowmails' own** deployment — one shared
796
+ * worker serves every tenant, isolated by the domain id on every row.
797
+ * It is versioned, and an older one silently does less than the
798
+ * platform expects (no route tables before `1.4.0`, no Message-ID
799
+ * lookup before `1.5.1`, no event reporting before `1.6.0`). An agent
800
+ * that cannot see the version cannot tell why its events are empty.
436
801
  */
437
802
  interface WorkerVersionInfo {
438
803
  /**
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).
804
+ * The version the platform last deployed — `null` when it has no
805
+ * record (read {@link lastDeployAt} with it).
442
806
  */
443
807
  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). */
808
+ /** Whether the shared mail worker answered (its schema is migrated before deploy). */
447
809
  bootstrapped: boolean;
448
810
  /** When the platform last deployed this worker (ISO-8601), or `null`. */
449
811
  lastDeployAt: string | null;
@@ -457,13 +819,13 @@ interface FlowmailsOptions {
457
819
  baseURL?: string;
458
820
  /**
459
821
  * 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.
822
+ * (`fm.events`, `fm.messages`, `fm.waits`, `fm.addresses`).
464
823
  *
465
- * Defaults to `https://flowmails.net`. Set it for a self-hosted or
466
- * staging deployment — the same API key authenticates both.
824
+ * @deprecated The whole surface is served by the SDK backend now —
825
+ * the agent platform moved there — so this defaults to the same
826
+ * origin as {@link baseURL}. It is kept so a client that set it
827
+ * keeps working against a private or staging deployment that
828
+ * splits the two. A client that does not set it gets one host.
467
829
  */
468
830
  platformURL?: string;
469
831
  /** Inject a `fetch` implementation (Workers environments, test harnesses). */
@@ -514,6 +876,20 @@ declare class Flowmails {
514
876
  * reason: `error` is the typed slug and `sendFeedback` is the
515
877
  * relay's own words. Check `result.error` before treating a `201`
516
878
  * as "sent".
879
+ *
880
+ * **A partial send is not a success either.** Several recipients
881
+ * each get their own message, and the relay can refuse some of them.
882
+ * `status` is then `"partial"` — `error` is still set, and
883
+ * `result.recipients` says exactly which addresses were refused and
884
+ * why:
885
+ *
886
+ * ```ts
887
+ * const result = await fm.send({ from, to: ["a@x.test", "b@x.test"], subject, text });
888
+ * if (result.status === "partial") {
889
+ * const refused = result.recipients?.filter((r) => r.status === "failed") ?? [];
890
+ * // retry only these
891
+ * }
892
+ * ```
517
893
  */
518
894
  send(opts: SendOptions): Promise<SendResult>;
519
895
  /**
@@ -533,7 +909,8 @@ declare class Flowmails {
533
909
  * ```ts
534
910
  * const me = await fm.me();
535
911
  * if (me.sending && !me.sending.canSend) {
536
- * // me.sending.state says why: "not_onboarded", "unknown", …
912
+ * // me.sending.configured: false means sending was never set up;
913
+ * // otherwise me.sending.state says why: "setup_required", …
537
914
  * }
538
915
  * ```
539
916
  *
@@ -542,10 +919,11 @@ declare class Flowmails {
542
919
  */
543
920
  me(): Promise<AccountInfo>;
544
921
  /**
545
- * The account's receive worker, and the version of it.
922
+ * The shared mail worker, and the version of it.
546
923
  *
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
924
+ * The mail worker does the actual receiving and sending — it is
925
+ * Flowmails' own deployment, one shared worker for every tenant —
926
+ * and it is versioned: `1.4.0` brought the route tables, `1.5.1` the
549
927
  * Message-ID lookup, `1.6.0` the event reporting that fills the
550
928
  * log this SDK reads. An agent whose worker is older than the
551
929
  * platform expects sees an empty event log and has no way to tell
@@ -594,6 +972,21 @@ declare class Flowmails {
594
972
  * `Message-ID`, which is exactly what `email.threadId` holds.
595
973
  */
596
974
  readonly threads: AgentThreads;
975
+ /**
976
+ * The draft queue — a message written for a **person** to review.
977
+ *
978
+ * Nothing here sends. `create` writes a `pending_review` row and
979
+ * `list` / `get` report what a reviewer did with it. A human
980
+ * approves it in the dashboard, and the approval is the send — so
981
+ * the platform's audited send path, quota and domain rules apply
982
+ * unchanged.
983
+ *
984
+ * ```ts
985
+ * const draft = await fm.drafts.create({ from, to, subject, text });
986
+ * const queue = await fm.drafts.list({ status: "pending_review" });
987
+ * ```
988
+ */
989
+ readonly drafts: AgentDrafts;
597
990
  /**
598
991
  * The durable wait — the one thing an agent cannot build for
599
992
  * itself.
@@ -621,6 +1014,17 @@ declare class Flowmails {
621
1014
  */
622
1015
  private request;
623
1016
  }
1017
+ /**
1018
+ * The draft namespace — see {@link Flowmails.drafts}.
1019
+ *
1020
+ * Three operations and no sending: a draft is a message a **person**
1021
+ * approves, which is why this namespace has no `send`.
1022
+ */
1023
+ interface AgentDrafts {
1024
+ create(opts: CreateDraftOptions): Promise<EmailDraft>;
1025
+ list(opts?: ListDraftsOptions): Promise<ListDraftsResult>;
1026
+ get(draftId: string): Promise<EmailDraft>;
1027
+ }
624
1028
  /**
625
1029
  * The event log namespace — see {@link Flowmails.events}.
626
1030
  */
@@ -639,13 +1043,90 @@ interface AgentEvents {
639
1043
  /**
640
1044
  * The message-read namespace — see {@link Flowmails.messages}.
641
1045
  */
1046
+ /**
1047
+ * Options for {@link AgentMessages.get}.
1048
+ *
1049
+ * `format` trades bytes for fidelity: `"full"` (the default) returns the raw
1050
+ * HTML beside the plain text, `"markdown"` omits `html` and returns the
1051
+ * Markdown projection instead. Both modes carry `markdown` and `extracted`
1052
+ * when the message has them.
1053
+ */
1054
+ interface GetMessageOptions {
1055
+ /** Which of the account's domains to look in. */
1056
+ domainId?: string;
1057
+ /** `full` (default) or `markdown`. An unknown value is a `400`. */
1058
+ format?: "full" | "markdown";
1059
+ }
1060
+ /**
1061
+ * One attachment, read as text.
1062
+ *
1063
+ * An attachment with no text representation — an image, an encrypted PDF, a
1064
+ * scanned page — answers `supported: false` with a stable `reason`. That is
1065
+ * an answer, not an error: branch on `supported` instead of retrying.
1066
+ */
1067
+ interface AttachmentText {
1068
+ supported: boolean;
1069
+ /**
1070
+ * A stable slug when `supported` is false: `attachment_too_large`,
1071
+ * `unsupported_format`, `encrypted_pdf`, `suspicious_compression`,
1072
+ * `no_text`, `corrupt_attachment`.
1073
+ */
1074
+ reason: string | null;
1075
+ filename: string | null;
1076
+ mimeType: string | null;
1077
+ sizeBytes: number;
1078
+ /** The extracted text; `null` when unsupported. Untrusted input. */
1079
+ text: string | null;
1080
+ /** `true` when the text was cut at 64 KiB. */
1081
+ truncated: boolean;
1082
+ }
642
1083
  interface AgentMessages {
643
1084
  /** Fetch the full content of one message by SMTP `Message-ID`. */
644
- get(messageId: string, opts?: {
1085
+ get(messageId: string, opts?: GetMessageOptions): Promise<MessageDetail>;
1086
+ /**
1087
+ * `get_attachment_text`: read one attachment as text.
1088
+ *
1089
+ * `attachmentId` is the value in `attachments[].id` of a
1090
+ * {@link AgentMessages.get} answer. Plain text, CSV, Markdown, HTML,
1091
+ * JSON, XML, `.docx` and PDF are supported; anything else answers
1092
+ * `supported: false` with a reason.
1093
+ *
1094
+ * ```ts
1095
+ * const message = await fm.messages.get(event.messageId, { format: "markdown" });
1096
+ * const file = await fm.messages.attachmentText(
1097
+ * event.messageId,
1098
+ * message.attachments[0].id,
1099
+ * );
1100
+ * if (file.supported) console.log(file.text);
1101
+ * ```
1102
+ */
1103
+ attachmentText(messageId: string, attachmentId: string, opts?: {
645
1104
  domainId?: string;
646
- }): Promise<MessageDetail>;
1105
+ }): Promise<AttachmentText>;
647
1106
  /** Poll a sent message's delivery state by row id or `Message-ID`. */
648
1107
  status(id: string): Promise<SendStatus>;
1108
+ /**
1109
+ * `claim_message`: take a message for processing.
1110
+ *
1111
+ * The platform records that this credential is working on the
1112
+ * message now — a **mutex**, so two workers of the same account do
1113
+ * not process the same message at once. It does not judge the mail
1114
+ * and does not act on it.
1115
+ *
1116
+ * @throws {ValidationError} when `messageId` or `domainId` is
1117
+ * missing.
1118
+ */
1119
+ claim(messageId: string, opts: ClaimMessageOptions): Promise<MessageState>;
1120
+ /**
1121
+ * `complete_message`: record the outcome (`done` or `failed`).
1122
+ *
1123
+ * The platform stores what the agent said and takes no further
1124
+ * action on it.
1125
+ *
1126
+ * @throws {ValidationError} when `messageId`, `domainId` or
1127
+ * `state` is missing, or `state` is neither `done` nor `failed`.
1128
+ */
1129
+ complete(messageId: string, opts: CompleteMessageOptions): Promise<MessageState>;
649
1130
  /**
650
1131
  * `search_emails`: look **back** through the mailbox.
651
1132
  *
@@ -660,6 +1141,33 @@ interface AgentMessages {
660
1141
  * query parameter.
661
1142
  */
662
1143
  search(domainId: string, opts: SearchMessagesOptions): Promise<SearchMessagesResult>;
1144
+ /**
1145
+ * `list_message_states`: read the agent's **own** record back.
1146
+ *
1147
+ * The event log says a mail arrived; the claim and the completion
1148
+ * say what this agent did with it. This is the third half — the
1149
+ * read — and it is what makes the other two useful: an agent that
1150
+ * restarted reads it back to tell "I never saw this" from "I saw
1151
+ * it and never finished".
1152
+ *
1153
+ * Two facts the caller must know:
1154
+ *
1155
+ * - **The rows belong to the calling credential.** The platform
1156
+ * stores the state under a fingerprint of the bearer, so another
1157
+ * credential of the same tenant does not read them by accident.
1158
+ * - **`domainId` is required.** The state is scoped to the domain
1159
+ * whose mailbox received the message.
1160
+ *
1161
+ * ```ts
1162
+ * const { states } = await fm.messages.listStates(domainId, {
1163
+ * state: "processing",
1164
+ * });
1165
+ * ```
1166
+ *
1167
+ * @throws {ValidationError} when `domainId` is missing, or `state`
1168
+ * is not one of the four names.
1169
+ */
1170
+ listStates(domainId: string, opts?: ListMessageStatesOptions): Promise<ListMessageStatesResult>;
663
1171
  }
664
1172
  /**
665
1173
  * The conversation namespace — see {@link Flowmails.threads}.
@@ -787,7 +1295,19 @@ declare class AuthenticationError extends FlowmailsError {
787
1295
  */
788
1296
  declare class ValidationError extends FlowmailsError {
789
1297
  readonly detail?: string;
790
- constructor(code: string, detail: string | undefined, status?: number);
1298
+ /**
1299
+ * The rest of the platform's error body, when it carried more than
1300
+ * `error` / `detail`.
1301
+ *
1302
+ * The claim conflict is the case that matters: a `409` from
1303
+ * `POST /api/agent/messages/:messageId/claim` names the credential
1304
+ * holding the live claim (`claimedBy`, `claimedAt`). Dropping those
1305
+ * left a caller with "Validation failed: message already claimed" and
1306
+ * no way to tell which worker holds the message — the one fact the
1307
+ * mutex exists to communicate.
1308
+ */
1309
+ readonly extra?: Record<string, unknown>;
1310
+ constructor(code: string, detail: string | undefined, status?: number, extra?: Record<string, unknown>);
791
1311
  }
792
1312
  /**
793
1313
  * 408 / 429 — request was rate-limited or timed out. Retryable.
@@ -825,4 +1345,4 @@ declare class UpstreamError extends FlowmailsError {
825
1345
  constructor(code: string, upstreamMessage: string | undefined, status?: number);
826
1346
  }
827
1347
 
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 };
1348
+ export { type AccountInfo, type AccountSendingState, type AgentAddress, type AgentAddresses, type AgentDomain, type AgentDrafts, type AgentEvent, type AgentEvents, type AgentMessages, type AgentThreads, type AgentWaits, AuthenticationError, type ClaimMessageOptions, type CompleteMessageOptions, type CreateAddressResult, type CreateDraftOptions, type CreateWaitOptions, type CreateWaitResult, DRAFT_STATUS_NAMES, type DraftStatusName, type EmailDraft, Flowmails, FlowmailsError, type FlowmailsOptions, type ListDraftsOptions, type ListDraftsResult, type ListEventsOptions, type ListEventsResult, type ListMessageStatesOptions, type ListMessageStatesResult, type MessageDetail, type MessageSecurity, type MessageSecuritySignal, type MessageState, type MessageStateName, RateLimitError, type SearchMessageHit, type SearchMessagesOptions, type SearchMessagesResult, type SendAttachment, type SendOptions, type SendRecipientResult, type SendResult, type SendStatus, type ThreadDetail, type ThreadMessage, UpstreamError, ValidationError, WAIT_RESOLVED_EVENT, type WaitStatus, type WorkerVersionInfo };