@happyvertical/smrt-messages 0.71.0 → 0.72.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/AGENTS.md +7 -3
- package/agents/send-approval.md +32 -12
- package/dist/access.d.ts +18 -1
- package/dist/access.d.ts.map +1 -1
- package/dist/chunks/{AttachmentCollection-C14dERNK.js → AttachmentCollection-CB5ssbOy.js} +15 -13
- package/dist/chunks/AttachmentCollection-CB5ssbOy.js.map +1 -0
- package/dist/chunks/{Email-Bd1lCLiC.js → Email--1mF4f-0.js} +6 -6
- package/dist/chunks/{Email-Bd1lCLiC.js.map → Email--1mF4f-0.js.map} +1 -1
- package/dist/chunks/{EmailAccountCollection-Clv4kruh.js → EmailAccountCollection-BaWIVvI4.js} +48 -24
- package/dist/chunks/{EmailAccountCollection-Clv4kruh.js.map → EmailAccountCollection-BaWIVvI4.js.map} +1 -1
- package/dist/chunks/{EmailCollection-CiZJ5I2l.js → EmailCollection-Cu7PTw8Y.js} +10 -4
- package/dist/chunks/{EmailCollection-CiZJ5I2l.js.map → EmailCollection-Cu7PTw8Y.js.map} +1 -1
- package/dist/chunks/{EmailFolder-Dvb6M-d_.js → EmailFolder-8CRSnmLs.js} +6 -6
- package/dist/chunks/{EmailFolder-Dvb6M-d_.js.map → EmailFolder-8CRSnmLs.js.map} +1 -1
- package/dist/chunks/{EmailFolderCollection-BR3yh7sp.js → EmailFolderCollection-e6QeSt5j.js} +2 -2
- package/dist/chunks/{EmailFolderCollection-BR3yh7sp.js.map → EmailFolderCollection-e6QeSt5j.js.map} +1 -1
- package/dist/chunks/{EmailSender-B-c7mxbY.js → EmailSender-CQQMuVDg.js} +2 -2
- package/dist/chunks/{EmailSender-B-c7mxbY.js.map → EmailSender-CQQMuVDg.js.map} +1 -1
- package/dist/chunks/{Message-CGyhd0kh.js → Message-CHDqmhWf.js} +102 -43
- package/dist/chunks/Message-CHDqmhWf.js.map +1 -0
- package/dist/chunks/{MessageCollection-DRCtm5z2.js → MessageCollection-B48ZrvCw.js} +7 -3
- package/dist/chunks/MessageCollection-B48ZrvCw.js.map +1 -0
- package/dist/chunks/{MessagingEndpointCollection-Cju_NnJZ.js → MessagingEndpointCollection-Z9eO6PSl.js} +2 -2
- package/dist/chunks/{MessagingEndpointCollection-Cju_NnJZ.js.map → MessagingEndpointCollection-Z9eO6PSl.js.map} +1 -1
- package/dist/collections/EmailCollection.d.ts.map +1 -1
- package/dist/collections/MessageCollection.d.ts.map +1 -1
- package/dist/connect.js +1 -1
- package/dist/index.js +17 -17
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/models/Attachment.d.ts +5 -3
- package/dist/models/Attachment.d.ts.map +1 -1
- package/dist/models/Message.d.ts +24 -12
- package/dist/models/Message.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +7 -7
- package/dist/smrt-knowledge.okf.md +2 -2
- package/package.json +12 -12
- package/dist/chunks/AttachmentCollection-C14dERNK.js.map +0 -1
- package/dist/chunks/Message-CGyhd0kh.js.map +0 -1
- package/dist/chunks/MessageCollection-DRCtm5z2.js.map +0 -1
package/dist/manifest.json
CHANGED
|
@@ -33,9 +33,11 @@ export declare class Attachment extends SmrtObject {
|
|
|
33
33
|
loadFromId(): Promise<void>;
|
|
34
34
|
loadFromSlug(): Promise<void>;
|
|
35
35
|
/**
|
|
36
|
-
* An attachment is part of what its message will send, so writing one on
|
|
37
|
-
*
|
|
38
|
-
* writing the
|
|
36
|
+
* An attachment is part of what its message will send, so writing one on
|
|
37
|
+
* a message of an owned account that is not `sent` needs the same `draft`
|
|
38
|
+
* scope as writing the message (see `Message.save()`), whichever route the
|
|
39
|
+
* write takes. Deleting one on received mail stays open.
|
|
40
|
+
*
|
|
39
41
|
* Both the parent it is saved onto and the parent it is stored on count, so
|
|
40
42
|
* an attachment cannot be moved on or off a draft without the scope.
|
|
41
43
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Attachment.d.ts","sourceRoot":"","sources":["../../src/models/Attachment.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,yBAAyB,CAAC;AACjC,OAAO,EAGL,UAAU,EACV,KAAK,eAAe,EAErB,MAAM,0BAA0B,CAAC;AAalC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAU,CAAC;AAElD,qBAMa,UAAW,SAAQ,UAAU;IAExC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAQ;IAG/B,SAAS,SAAM;IACf;;;;;OAKG;IAEH,SAAS,EAAE,MAAM,GAAG,IAAI,CAAQ;IAChC,QAAQ,SAAM;IACd,WAAW,SAAM;IACjB,IAAI,SAAK;IACT,SAAS,SAAM;IACf,kBAAkB,EAAE,YAAY,GAAG,QAAQ,CAAgB;IAC3D,QAAQ,SAAM;IACd,SAAS,SAAM;IAGf,SAAS,OAAc;gBAEX,OAAO,GAAE,iBAAsB;IAmB3C;;;;OAIG;IACY,UAAU;IAKV,YAAY;IAK3B
|
|
1
|
+
{"version":3,"file":"Attachment.d.ts","sourceRoot":"","sources":["../../src/models/Attachment.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,OAAO,yBAAyB,CAAC;AACjC,OAAO,EAGL,UAAU,EACV,KAAK,eAAe,EAErB,MAAM,0BAA0B,CAAC;AAalC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAU,CAAC;AAElD,qBAMa,UAAW,SAAQ,UAAU;IAExC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAQ;IAG/B,SAAS,SAAM;IACf;;;;;OAKG;IAEH,SAAS,EAAE,MAAM,GAAG,IAAI,CAAQ;IAChC,QAAQ,SAAM;IACd,WAAW,SAAM;IACjB,IAAI,SAAK;IACT,SAAS,SAAM;IACf,kBAAkB,EAAE,YAAY,GAAG,QAAQ,CAAgB;IAC3D,QAAQ,SAAM;IACd,SAAS,SAAM;IAGf,SAAS,OAAc;gBAEX,OAAO,GAAE,iBAAsB;IAmB3C;;;;OAIG;IACY,UAAU;IAKV,YAAY;IAK3B;;;;;;;;OAQG;IACY,IAAI,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAc9C,MAAM,CACnB,OAAO,GAAE;QAAE,iBAAiB,CAAC,EAAE,IAAI,GAAG,MAAM,CAAA;KAAO,GAClD,OAAO,CAAC,IAAI,CAAC;IAKhB;;;OAGG;YACW,gBAAgB;IAgB9B;;;;;;OAMG;YACW,sBAAsB;IAiDpC;;OAEG;IACG,UAAU;IAWhB;;OAEG;IACH,OAAO,IAAI,OAAO;IAIlB;;OAEG;IACH,KAAK,IAAI,OAAO;IAIhB;;OAEG;IACH,QAAQ,IAAI,OAAO;IAInB;;OAEG;IACH,YAAY,IAAI,MAAM;IAMtB;;OAEG;IACH,gBAAgB,IAAI,MAAM;IAa1B;;OAEG;IACH,eAAe,IAAI,OAAO;IAI1B;;;;;;;;;;OAUG;IACG,WAAW,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CAO5C"}
|
package/dist/models/Message.d.ts
CHANGED
|
@@ -9,6 +9,8 @@ import { SmrtObject } from '@happyvertical/smrt-core';
|
|
|
9
9
|
import type { MessageOptions, MessageSendResult, SendMessageOptions, SendStatus } from "../types.js";
|
|
10
10
|
/** `metadata` key recording that the last failed send may have been accepted. */
|
|
11
11
|
export declare const SEND_OUTCOME_UNKNOWN_METADATA_KEY = "sendOutcomeUnknown";
|
|
12
|
+
/** Internal: not exported from the package index. */
|
|
13
|
+
export declare function saveQueuedForSend(message: Message): Promise<void>;
|
|
12
14
|
export declare class Message extends SmrtObject {
|
|
13
15
|
tenantId: string | null;
|
|
14
16
|
accountId: string;
|
|
@@ -47,21 +49,28 @@ export declare class Message extends SmrtObject {
|
|
|
47
49
|
expectedUpdatedAt?: Date | string;
|
|
48
50
|
}): Promise<void>;
|
|
49
51
|
/**
|
|
50
|
-
* Creating, changing or deleting
|
|
51
|
-
* `draft` scope, whichever route the write
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
52
|
+
* Creating, changing or deleting mail that a later send would transmit
|
|
53
|
+
* needs the `draft` scope on an owned account, whichever route the write
|
|
54
|
+
* takes ({@link isMailWriteGated}): every row that is not `sent`, received
|
|
55
|
+
* mail included when it is saved, so content cannot be written without the
|
|
56
|
+
* scope and then flipped into a draft. A row counts by its stored state and
|
|
57
|
+
* by the state it is moved into, so it cannot be edited by first relabelling
|
|
58
|
+
* it, and both accounts count when it moves. A fresh row needs the scope
|
|
59
|
+
* too. Received mail (provider-tagged, unflagged, plain `draft`) is never
|
|
60
|
+
* sent ({@link Message.send} refuses it), may be deleted, and a stored
|
|
61
|
+
* `sent` row cannot leave `sent`. The stored row decides, whatever class
|
|
62
|
+
* this instance is. Trusted system work, unowned accounts and sent mail are
|
|
63
|
+
* unaffected.
|
|
64
|
+
*
|
|
65
|
+
* A save that changes only the triage fields (read and flagged state) of a
|
|
66
|
+
* stored row needs nothing here: they are not content a send transmits.
|
|
59
67
|
*
|
|
60
68
|
* `lifecycle` is the send path's own save (status changes, a held send moved
|
|
61
69
|
* back to draft): it needs the `send` scope instead, and passes only while
|
|
62
70
|
* every field outside {@link SEND_PATH_MAY_CHANGE} still equals the stored
|
|
63
71
|
* row, so it cannot carry an edit. A row the send path itself creates (an
|
|
64
|
-
* unsaved message being sent)
|
|
72
|
+
* unsaved message being sent), or a service-queued row saved through
|
|
73
|
+
* {@link saveQueuedForSend}, needs `send` too.
|
|
65
74
|
*
|
|
66
75
|
* Returns the requirements it enforced (empty for system work).
|
|
67
76
|
*/
|
|
@@ -76,8 +85,11 @@ export declare class Message extends SmrtObject {
|
|
|
76
85
|
private assertDraftScopeStillHolds;
|
|
77
86
|
/** The `scope:accountId` pairs this write needs, read through `this.db`. */
|
|
78
87
|
private draftScopeRequirements;
|
|
79
|
-
/**
|
|
80
|
-
|
|
88
|
+
/**
|
|
89
|
+
* Whether every field outside `allowed` equals `stored`. `held` lets a held
|
|
90
|
+
* send raise the draft flag.
|
|
91
|
+
*/
|
|
92
|
+
private matchesStoredBeyond;
|
|
81
93
|
private finalizeSendLifecycle;
|
|
82
94
|
/**
|
|
83
95
|
* Get to addresses as parsed array
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Message.d.ts","sourceRoot":"","sources":["../../src/models/Message.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,eAAe,EAChB,MAAM,0BAA0B,CAAC;AAUlC;;;;GAIG;AAIH,OAAO,yBAAyB,CAAC;AACjC,OAAO,EAKL,UAAU,EAIX,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"Message.d.ts","sourceRoot":"","sources":["../../src/models/Message.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,eAAe,EAChB,MAAM,0BAA0B,CAAC;AAUlC;;;;GAIG;AAIH,OAAO,yBAAyB,CAAC;AACjC,OAAO,EAKL,UAAU,EAIX,MAAM,0BAA0B,CAAC;AAsBlC,OAAO,KAAK,EACV,cAAc,EACd,iBAAiB,EACjB,kBAAkB,EAClB,UAAU,EACX,MAAM,aAAU,CAAC;AAElB,iFAAiF;AACjF,eAAO,MAAM,iCAAiC,uBAAuB,CAAC;AAqEtE,qDAAqD;AACrD,wBAAsB,iBAAiB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAOvE;AA+HD,qBAOa,OAAQ,SAAQ,UAAU;IAErC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAQ;IAM/B,SAAS,SAAM;IAQf,SAAS,EAAE,MAAM,GAAG,IAAI,CAAQ;IAGhC,UAAU,EAAE,MAAM,GAAG,IAAI,CAAQ;IAKjC,aAAa,SAAM;IAEnB,QAAQ,SAAM;IAEd,OAAO,SAAM;IAEb,IAAI,SAAM;IAEV,WAAW,SAAM;IAEjB,QAAQ,SAAM;IAEd,WAAW,SAAM;I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A;KAAE,GAAG,OAAO;IA0BvD;;OAEG;IACH,aAAa,IAAI,OAAO;IA0BxB;;OAEG;IACH,SAAS,CAAC,eAAe,IAAI,MAAM;CAapC"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,14 +3,14 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-messages",
|
|
6
|
-
"packageVersion": "0.
|
|
6
|
+
"packageVersion": "0.72.0",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
13
|
-
"moduleDoc:agents/send-approval.md": "
|
|
10
|
+
"manifest": "2154dcacc966f55c189e83efc76a4b97c3d54883fa385acaf7181f317537c7e5",
|
|
11
|
+
"packageJson": "ec6d60c74a82a0aa134697c532cdece282813bf642f80e3d8eec57e2af83d181",
|
|
12
|
+
"agents": "f75852f92b25b413b1c1461de0c228406f270d20a060eccd15b397721546b8d3",
|
|
13
|
+
"moduleDoc:agents/send-approval.md": "edf16ea3b4627e0d6d8f7174de5836c1ea7a24e79f68d74f42b644306af875a2",
|
|
14
14
|
"moduleDoc:agents/mail-search.md": "9dac1619a1486f2fa94980e141ebc5003851c27cd77ced6d5ff64d348429fdb1",
|
|
15
15
|
"moduleDoc:agents/attachment-storage.md": "f08dc3087f883ce0a8ba5eeb08a53ee9f51da8bf705160daa35f15d7b1b32821",
|
|
16
16
|
"moduleDoc:agents/notification-outbox.md": "0e9a870c4b2d5f0fec47af0dff6e61d216fb0121d384d99bccfc506beb6e38ad",
|
|
@@ -14281,12 +14281,12 @@
|
|
|
14281
14281
|
"polymorphicAssociations": 0,
|
|
14282
14282
|
"uuidColumns": 138
|
|
14283
14283
|
},
|
|
14284
|
-
"agentDoc": "# @happyvertical/smrt-messages\n\nMulti-channel messaging with STI hierarchies for both messages and accounts. Credential encryption via smrt-secrets.\n\n## STI Hierarchies\n\n**Messages** (share `messages` table):\n- `Message` (base): accountId, personaId, endpointId, correlationId, threadId, subject, body, fromAddress, toAddresses (JSON), sendStatus (draft/sending/sent/failed), retryCount\n- `Email`: messageId (RFC 822), inReplyTo, ccAddresses, bccAddresses, htmlBody, textBody, folderId, labels, headers\n- `Tweet`: tweetId, retweetCount, likeCount, mediaUrls, hashtags, mentions\n- `SlackMessage`: channelId, slackTs, slackThreadTs, reactions, blocks\n\n**Accounts** (share `accounts` table):\n- `Account` (base): channelType, providerType, public configuration,\n credentialSecretId, isActive, lastSyncAt, deprecated sensitive settings\n- `EmailAccount`, `TwitterAccount`, `SlackAccount`, `ZulipAccount`,\n `TelegramAccount`: provider-specific identity/sender behavior\n\n## Persona messaging\n\n- `MessagingEndpoint`: tenant-owned, write-only destination JSON with masked\n display helper.\n- `PersonaMessageRoute`: persona → account + endpoint, selected by purpose and\n descending priority.\n- `PersonaMessagingService`: persists and sends through an enabled route.\n- Provider registry: public setup descriptors + optional sender factory. Keep\n channel (`sms`) separate from provider (`twilio`).\n- Permissions: `messages.send`, `messages.manage-routes`,\n `messages.manage-credentials`.\n- `MessagingSettingsService` is the permissioned server boundary;\n its host-supplied `resolvePersonaTenantId` proves cross-package ownership.\n `MessagingSettingsPanel` is the callback-driven Svelte surface.\n- Account, endpoint, and route generated surfaces are read-only. Do not add\n generated mutations around the settings service or make secret fields writable.\n- **Recipe `messages.slack`** (`src/recipes.ts`, help in `src/help/slack.md`): lists Slack messages and workspaces beside the Mailbox and Notifications recipes; workspaces stay read-only and sending goes through the senders, not generated routes. Fields it shows carry `@field({ description })` in plain words; keep them when editing the models.\n\n## Per-account mail access (owner + grants)\n\nOptional by default: `Account.ownerUserId` is nullable, and an account without\nan owner stays tenant-wide. Apps that want private or shared mailboxes set\nowners and call `configureMailAccess({ options, resolvePrincipal })` at startup\n(`access.ts`); smrt never knows the host's credential model, the host returns a\n`MailPrincipal` (`userId` + tenant, optional `scopes` / `accountIds` ceilings).\n\n- Scopes `read`, `triage`, `draft`, `send` are `ResourceGrant` rows (resource\n type `messages:account`, permission `messages.<scope>`) checked by\n `checkResourceOperationPermission`, so the grantee also needs the tenant\n `messages.<scope>` permission (the ceiling). The owner holds every scope\n implicitly. Agents are `User` rows the host maps its credential to; the\n principal ceilings are intersected with the grant, never added to it.\n- `access-enforcement.ts` is a `GlobalInterceptors` entry registered at package\n load. Emails, folders and attachments (matched by STI ancestry) are filtered\n in `beforeList`/`afterList`/`afterGet`; raw `query()` on them is refused while\n any account is closed to the principal. Fail closed: no principal, no\n resolver or a foreign tenant means owned accounts are invisible. No tenant\n admin or super-admin bypass; trusted work (sync, outbox) uses\n `runWithMailSystemAccess()`. `EmailAccount.syncFrom()` does so itself.\n- Attachments carry a denormalized `accountId` (always derived from the message in a\n `beforeSave` interceptor, never caller-supplied) so lists, projections and counts filter in SQL; run\n `AttachmentCollection.backfillAccountIds()` once after upgrading (legacy rows\n without it are hidden from every read until then).\n- `connectMailbox` refuses by default: give the service `allowedMailHosts`\n (and optionally `allowedMailPorts`) or your own `validateMailbox`. The\n built-in validator never connects to private, loopback or link-local\n addresses and returns only a generic error. It checks every target field\n present (`host`, `endpoint`, and the `jmap` provider's `url`): https only, no\n userinfo, listed host and port. The `jmap` provider stays `available: false`\n on purpose (`available` means outbound transport; JMAP is receive and sync\n only), and `connectMailbox` still connects it. Policy lookups use the\n configured db handle, not a caller's transaction.\n- Draft writes (and their attachments) need the `draft` scope on an owned\n account, checked in `Message.save()`/`delete()` and\n `Attachment.save()`/`delete()`; rules and bypasses:\n [agents/send-approval.md](agents/send-approval.md#draft-writes).\n- `Message.send()` needs the `send` scope on an owned account. Agent sends\n (principal `kind` other than `person`/`human`) on a mail account are held\n for a person's approval unless the owner opted in to `auto_send`;\n approve / edit-then-approve / reject / release (as an approving person,\n never the agent) through `MailSendApprovalService`,\n drafts through `MailDraftService`, \"handled by\" on every message. Gate,\n binding and bypass rules: [agents/send-approval.md](agents/send-approval.md). Account rows are\n not filtered (senders, routes and the outbox read them without a principal).\n- `MailAccessService` (`grant`, `revoke`, `list`, `setOwner`) needs tenant\n `messages.manage-access` AND ownership (or delegation); an administrator\n cannot read, self-grant or take over an owned mailbox. Unowned accounts can be\n claimed once with `messages.manage-credentials`.\n- `MessagingSettingsService.listAccounts({ limit, cursor })` is the account\n discovery for a principal: only accounts it owns or holds an active grant on\n (never unowned or foreign accounts), with effective `scopes` and\n `relation: 'owner' | 'shared'`, via `decideMailAccess`. Fail closed with no\n principal user, a tenant mismatch or no `configureMailAccess`.\n- `seedMessagesRolePermissions({ db })` seeds the tenant `messages.*` slugs for\n the system roles (owner/admin: read, triage, draft, send, manage-credentials,\n manage-access; member: the four scopes; viewer: read). Idempotent, additive,\n system roles only; without it grants and `manage-access` fail closed on a\n fresh app. The matrix is `MESSAGES_ROLE_PERMISSION_MATRIX`.\n- Before `configureMailAccess` is called the policy still fails closed on\n owned accounts: every collection operation on a mail class (the core `onCollectionReady`\n interceptor hook, so STI subclasses on a default collection are covered) registers its\n database, per database, and the policy hides every owned account's mail\n through list, count, projections, facets and raw queries; it learns the database from the first mail or account row it\n sees and, with no principal resolver, hides every owned account's mail.\n Direct hydration (`new Email({ id }).initialize()`, `loadRelated()`) is gated\n in the models' `loadFromId`/`loadFromSlug`.\n- `connectionStatus` (`connected` / `needs_reconnect`) and `statusMessage` mark\n an account whose sign-in the server refused; `syncFrom()` sets it.\n\n## Mail search and private correspondents (#5132)\n\n`MailSearchService` searches only `read`-scoped accounts from `listAccounts()`;\n`CorrespondentService` derives owner-private contacts (optional `Profile` link).\nBoth fail closed. Details: [agents/mail-search.md](agents/mail-search.md).\n\n## Attachment storage root (#5645)\n\n`Attachment.filePath` is `<accountId>/...` relative to the root set once at startup with\n`configureAttachmentStorage({ root })` (beside `configureMailAccess`). Without\nit stored files are never read (fail closed). Rules, send behaviour and the\nupgrade step: [agents/attachment-storage.md](agents/attachment-storage.md).\n\n## Mailbox connect (provider-neutral)\n\nCredentials reach smrt-secrets in two ways; neither writes the plaintext `settings` fallback.\n\n- **Write-only app password**: `MessagingSettingsService.connectMailbox()`\n (permission `messages.manage-credentials`). The candidate credential is\n validated by opening a session first (`validateMailbox` option, default the\n provider's email client); a refusal leaves no account and no secret, and the\n error text has the secret redacted. The connecting user becomes the owner;\n `label` and the per-account endpoint (`configuration`) are stored; reconnect\n replaces the secret and is owner-only. `setAccountActive()` pauses/resumes\n (`isActive`), `removeAccount()` deletes the secret, the synced mail and the\n account. IMAP/POP3 are admitted here (receive-only), not by `saveAccount`.\n- **Generic OAuth 2.0 / OIDC**: `@happyvertical/smrt-messages/connect`\n (`startMailOAuthConnect`, `completeMailOAuthConnect`, `MailOAuthProvider`)\n on the shared kernel `@happyvertical/smrt-secrets/connect` (single-use\n tenant- and user-bound `ConnectState`, PKCE, safe return path, OIDC\n discovery with issuer check). The signed-in user becomes the owner; an\n account owned by someone else or by no one is never taken over. No role\n checks in the flow: authorize before calling.\n- **Reconnect**: `syncFrom()` marks an auth failure `connectionStatus =\n 'needs_reconnect'` (`Account.markNeedsReconnect/markConnected`) instead of\n failing silently.\n- The Google provider is a later step (sdk#1405), not part of this flow.\n\n## In-app notifications (`UserNotification`)\n\nThe in-app channel: one stored row per person, with read state.\n`user_notifications`: `tenantId` (required), `recipientUserId`\n(`@crossPackageRef` smrt-users:User, uuid), `kind`, `title`, `body`, `href`,\n`severity` (info/success/warning/error), `sourceRef`, `occurredAt`, `readAt`,\n`dismissedAt`. Conflict identity `(tenant_id, recipient_user_id, source_ref)`.\n\n- `UserNotificationService` is the only access path: `notify()` /\n `notifyMany()` (dedupe on `sourceRef`, existing row returned untouched;\n a unique ref is generated when omitted), `listForUser()` / `countUnread()`\n across explicit `tenantIds` (each read under `withTenant`), `markRead()`,\n `dismiss()` (also marks read), `markAllRead()`. Every write filters on the\n recipient, so another user's id matches nothing.\n- Generated REST/MCP/CLI are off (`api`/`mcp`/`cli: false`): a tenant-scoped\n list would expose every member's rows. Hosts expose their own routes that\n pass the signed-in user's id, never a request-chosen one.\n- Hosts decide who is told (e.g. `SocialPost.createdByUserId` for a failed\n post). New table: consumers run `db:migrate`.\n\n## Notification email outbox (`NotificationDelivery`)\n\n`NotificationOutboxService` is the external-channel counterpart of\n`UserNotificationService`: `enqueueEmail()` stores one delivery per\n`(tenant, recipient, channel, sourceRef)` after the host resolves the\nrecipient address and same-tenant sender account (callers never choose an\naddress); `dispatchDue()` leases due rows by compare-and-set\n(`NotificationDelivery.transition()`), creates the single outbound `Email`\nunder the lease, and settles sent/retry/failed/uncertain. Never resend an\n`uncertain` row automatically. Contract, retry, and reconciliation policy:\n[agents/notification-outbox.md](agents/notification-outbox.md). New table:\nconsumers run `db:migrate`.\n\n`NotificationOptOut` (`notification_opt_outs`, tenant-required, generated\nsurfaces off) is the per-recipient opt-out ledger for the outbox's\n`isSuppressed` hook, keyed `(tenant, recipient, channel, scope)` with scope `*`\nor `project:<uuid>`-style keys. `NotificationOptOutService`: idempotent\n`optOut`/`optIn` (with a `principal` only `userId === recipientUserId` may\nchange a row, and only in the principal's own `tenantId`, else\n`NotificationOptOutDeniedError`; no principal = trusted host code), trusted `isOptedOut` (a `*` row matches every scope), `listForRecipient`\n(principal required). `optOutSuppression(service, scopeOf)` builds the\n`isSuppressed` function. Details in the outbox doc; consumers run `db:migrate`.\n\n## Credential Security\n\nAccount credentials stored via tenant-bound `credentialSecretId` →\nsmrt-secrets. Use `setCredentials()`/`getCredentials()` — never store passwords\ndirectly. Credential descriptor schemas contain field definitions, never values.\n\n## Send Lifecycle\n\n`message.send()`: resolves account → creates provider sender → updates sendStatus. Retry support with `maxRetries` budget.\nA failure the provider may still have accepted carries\n`MessageSendResult.outcomeUnknown` (set by `EmailSender` unless\n`isDefiniteSendRejection()` proves a refusal, and when a sender throws) and is\npersisted as `metadata.sendOutcomeUnknown`; never auto-resend it.\n`EmailSender` attaches the message's stored `Attachment` rows (read through\n`Attachment.readContent()`, under the message's tenant context) plus\n`SendEmailOptions.attachments` bytes; an unreadable or file-less row fails the\nsend with the error on `sendError`, never a silent drop (#3808).\n`PersonaMessagingService.send({ attachments })` accepts them on email routes only.\n\n## Provider entry points (bundle boundary, #1979)\n\nThe package root is provider-neutral: models, collections, services,\npermissions, and the provider registry carry **zero provider-SDK weight**.\nProvider SDK wrappers (`@happyvertical/email`, `@happyvertical/messages`) are\nreachable only through explicit entry points, imported once at server startup:\n\n```ts\nimport '@happyvertical/smrt-messages/providers/email'; // smtp/imap/pop3/gmail\nimport '@happyvertical/smrt-messages/providers/slack';\nimport '@happyvertical/smrt-messages/providers/twitter';\nimport '@happyvertical/smrt-messages/providers/all'; // all of the above\n```\n\n- Without the matching entry, `EmailAccount.createClient()` (send + mailbox\n sync) throws an actionable error and `SlackSender`/`TweetSender` return a\n failure result naming the entry to import. Telegram and Zulip are\n fetch-based and always work from the root.\n- Builtin registry definitions stay metadata-only (setup fields for UIs); the\n entries upgrade them with `createEmailClient`/`createMessageClient`/\n `createSender` hooks. Never import a provider SDK from any module reachable\n from `src/index.ts` — the consumer bundle gate (`packages/bundle-gate`)\n fails CI when one becomes reachable.\n- `Attachment.readContent()` reads with `node:fs` through `host.ts` (stubbed\n in `host.browser.ts`), not `@happyvertical/files`; see Attachment storage.\n\n## Gotchas\n\n- **Manifest before decorators**: every decorated model imports\n `../__smrt-register__.js`, and `package.json#sideEffects` lists\n `./src/__smrt-register__.ts`. Without both, the library build dropped or\n reordered the self-registration, so dist classes registered with only their\n decorated fields and could adopt smrt-ledgers' same-named `Account` (#3098).\n- **`Account` is not unique**: smrt-ledgers also declares `Account` (on\n `ledger_accounts`). Resolve by constructor or qualified name; the\n coexistence tests (`ledger-account-identity-*`, and the PostgreSQL lane\n `pnpm test:postgres`) load both packages in both orders.\n Both declare the `accounts` collection, so registering the ledgers `Account`\n auto-loads this family from its manifest as STI siblings. Core loads this\n base with them and never takes the ledgers `Account` for it (#4735,\n `ledger-account-identity-sti-siblings.test.ts`).\n- **STI `_meta_type`**: qualified format `@happyvertical/smrt-messages:Email`\n- **JSON fields**: all address/metadata fields are JSON strings with `getX()`/`setX()` helpers\n- **RFC 822 threading**: Email uses `inReplyTo`/`messageId`/`references` — manual management required\n- **Attachment.messageId**: use this field (not `emailId`); old getter/setter mapped via deprecation wrapper\n- **Optional tenancy**: `@TenantScoped({ mode: 'optional' })` on Message, Account, Attachment\n- **Required tenancy**: endpoints and persona routes are always tenant scoped\n- **Secrets are write-only**: never serialize credentials or endpoint.address to an app\n\n## Intake byte snapshots\n\n`EmailAccount.readIntakeMessage(providerLookup, maxBytes, imapIdentity?)` is the authorized host seam for\nopt-in ingestion. It copies full-message attachment bytes from the registered\nemail provider and fails when only attachment metadata is available; it never\nreads provider-supplied paths or advances sync checkpoints. Keep this path\nprovider-neutral and exclude arbitrary headers/credentials from its snapshot.\nIMAP lookup must include folder/UIDVALIDITY/UID verification; sender Message-ID\nis a lookup hint, never the durable delivery identity.\n\nProtected notification Emails carry durable delivery provenance. Their canonical\n`send`/`retrySend`, ordinary save/delete, and default EmailSender handoff are\nconstrained by `protected-notification-handoff.ts` (package-private, never a root\nexport). Only the outbox enters its exact one-use scope after current trusted\npolicy/byte validation. Preserve old-row/constructor identity checks, current\npersisted lease checks at the actual provider boundary, copied byte buffers and\nunknown-outcome marker protection. See the outbox contract and shared protected\nhandoff suite (SQLite and migrated PostgreSQL).\n\n## Protected external contacts\n\nProfile email uses exclusive `recipientProfileId` plus `resolveProfileRecipient`, a reserved `profileNotificationPolicy` and exact current tenant-owned public Profile email. No User account is required. Before activating profiles, run normal framework schema migration and public `planNotificationProfileRecipients` / `migrateNotificationProfileRecipients`; runtime verifies physical constraints and never applies DDL. Legacy User notification and opt-out paths remain User-only. See [profile recipient contract and matrix](agents/profile-recipients.md).\n\n## Incremental mail sync (change feed)\n\n`EmailAccount.syncChanges({ limit?, maxBatches?, since? })` (`mail-sync.ts`) drives\n`EmailClient.getChanges()` (JMAP provider `jmap`; `@happyvertical/email` 0.114+).\n`syncFrom()` stays the polling path for IMAP/POP3.\n\n- `EmailAccount.syncCursor` is the opaque feed cursor (sensitive + readonly, never\n on generated surfaces). It is saved only after its batch is applied; a failure\n anywhere leaves it where it was, so the job just retries.\n- Rows are keyed on `Email.providerMessageId` (the server's own id, per account),\n so applying a batch twice changes nothing. Added/changed messages upsert,\n `removed` deletes, `folders` upserts `EmailFolder` by path and counts are\n recomputed for touched folders. Metadata-only changes keep stored bodies.\n- `resync-required` clears the cursor and runs a full pass in the same run; a\n full pass from no cursor deletes stored messages (with a `providerMessageId`)\n the server no longer has. A second resync request in one run throws.\n- One lane per account: runs queue behind each other in-process, work on the\n stored (revision-guarded) row, and the job is deduplicated per tenant+account.\n Inactive and `needs_reconnect` accounts, and clients without `getChanges`,\n return `{ status: 'skipped' }`. Auth failures call `markNeedsReconnect()` and\n throw with `retryable: false`. The sync runs under `runWithMailSystemAccess()`.\n- Job: `enqueueMailSync(account)` / `enqueueDueMailSyncs(accounts)`\n (`mail-sync-jobs.ts`, queue `mail-sync`, dedupe key `mail-sync:<accountId>`)\n target `EmailAccount.syncChanges` through `@happyvertical/smrt-jobs` (optional\n peer). The host runs the `TaskRunner` and schedules `enqueueDueMailSyncs`.\n- Backfill horizon (#5200): optional `EmailAccount.backfillSince` (null = whole\n mailbox, the default) or per-run `since` (`Date`/ISO string, `null` lifts the\n stored one; `enqueueMailSync({ since })` forwards it as an ISO string). A\n message dated before it is not stored unless it already is; undated mail is\n kept; `MailSyncResult.beforeHorizon` counts the skips. The SDK change feed\n cannot filter by date, so the server still sends the older mail and it is\n dropped here (saves rows, not transfer; a server-side horizon needs an SDK change).\n- Horizon vs cursor: `cursorHorizon` records the horizon the saved cursor was\n built under (null = unbounded, also legacy cursors). If a run's effective\n horizon is earlier than it, or cleared (`since: null`), the cursor is dropped\n and the run does a full pass with prune; narrowing or an unchanged horizon\n keeps the cursor.\n- Persisted health (#5200): `lastSyncError` is set on any failed run (also\n client-build failures and sign-in refusals, which additionally set\n `needs_reconnect`) and cleared by the next successful run; a transient failure\n never changes `connectionStatus`. `backlog` mirrors `MailSyncResult.hasMore`\n of the last successful run. Both are plain optional columns (additive).\n- Known gaps: attachment rows are not created (only `hasAttachments`/`size`);\n a renamed server folder creates a new folder row (stored messages keep the old\n path until they change); `jmap` has no connect-flow validator yet and is not an\n outbound transport.\n\n## Triage write-back\n\n`EmailAccount.triage(action, emailIds)` (and `Email.triage(action)`,\n`mail-triage.ts`) writes mark read/unread, star/unstar, archive, spam/not spam,\nlabel add/remove and move to the server, then updates the local row. Actions are\n`{ kind: 'markRead' | 'markUnread' | 'star' | 'unstar' | 'archive' | 'markSpam' |\n'unmarkSpam' }`, `{ kind: 'addLabels' | 'removeLabels', labels }` and\n`{ kind: 'move', folder }`; ids are local `Email` row ids.\n\n- Access: needs `read` **and** `triage` on the account (`assertMailAccess`, fail\n closed; `MailAccessError`) before any server call or local write.\n- Server first, per message: the result is `{ updated, failed, stale }`. Only ids\n the server accepted are written; refusals (and ids that are missing, on another\n account, or not yet synced) come back in `failed`. A thrown client error\n changes nothing. Auth failures mark the account `needs_reconnect`.\n- Convergence: an accepted message is read back (`getMessage`) and stored through\n `applyServerMessage`, exactly as sync stores it, so the next sync is a no-op.\n If the read-back fails the id is `stale` and sync fixes the row. Triage runs in\n the account's sync lane (`inLane`), so it never interleaves with a sync here.\n- Providers whose `getCapabilities().writeBack` lacks the needed key (`flags`,\n `labels`, `archive`, `spam`) throw `MailWriteBackUnsupportedError` first.\n- `move` removes a message from the mailboxes it is in now (from its stored\n labels) and adds `folder`; pass a path as stored on `EmailFolder`.\n- Every public method on an `@smrt()` class becomes a `<collection>.<method>`\n permission; `Email.triage` is why `messages.triage` in `permissions.ts` carries\n the generated name and description (the catalog rejects two for one slug).\n- Known gaps: drafts and send, the acting principal is not recorded (#5141), and\n a mailbox the server has not reported yet has no `EmailFolder` row until sync.\n",
|
|
14284
|
+
"agentDoc": "# @happyvertical/smrt-messages\n\nMulti-channel messaging with STI hierarchies for both messages and accounts. Credential encryption via smrt-secrets.\n\n## STI Hierarchies\n\n**Messages** (share `messages` table):\n- `Message` (base): accountId, personaId, endpointId, correlationId, threadId, subject, body, fromAddress, toAddresses (JSON), sendStatus (draft/sending/sent/failed), retryCount\n- `Email`: messageId (RFC 822), inReplyTo, ccAddresses, bccAddresses, htmlBody, textBody, folderId, labels, headers\n- `Tweet`: tweetId, retweetCount, likeCount, mediaUrls, hashtags, mentions\n- `SlackMessage`: channelId, slackTs, slackThreadTs, reactions, blocks\n\n**Accounts** (share `accounts` table):\n- `Account` (base): channelType, providerType, public configuration,\n credentialSecretId, isActive, lastSyncAt, deprecated sensitive settings\n- `EmailAccount`, `TwitterAccount`, `SlackAccount`, `ZulipAccount`,\n `TelegramAccount`: provider-specific identity/sender behavior\n\n## Persona messaging\n\n- `MessagingEndpoint`: tenant-owned, write-only destination JSON with masked\n display helper.\n- `PersonaMessageRoute`: persona → account + endpoint, selected by purpose and\n descending priority.\n- `PersonaMessagingService`: persists and sends through an enabled route.\n- Provider registry: public setup descriptors + optional sender factory. Keep\n channel (`sms`) separate from provider (`twilio`).\n- Permissions: `messages.send`, `messages.manage-routes`,\n `messages.manage-credentials`.\n- `MessagingSettingsService` is the permissioned server boundary;\n its host-supplied `resolvePersonaTenantId` proves cross-package ownership.\n `MessagingSettingsPanel` is the callback-driven Svelte surface.\n- Account, endpoint, and route generated surfaces are read-only. Do not add\n generated mutations around the settings service or make secret fields writable.\n- **Recipe `messages.slack`** (`src/recipes.ts`, help in `src/help/slack.md`): lists Slack messages and workspaces beside the Mailbox and Notifications recipes; workspaces stay read-only and sending goes through the senders, not generated routes. Fields it shows carry `@field({ description })` in plain words; keep them when editing the models.\n\n## Per-account mail access (owner + grants)\n\nOptional by default: `Account.ownerUserId` is nullable, and an account without\nan owner stays tenant-wide. Apps that want private or shared mailboxes set\nowners and call `configureMailAccess({ options, resolvePrincipal })` at startup\n(`access.ts`); smrt never knows the host's credential model, the host returns a\n`MailPrincipal` (`userId` + tenant, optional `scopes` / `accountIds` ceilings).\n\n- Scopes `read`, `triage`, `draft`, `send` are `ResourceGrant` rows (resource\n type `messages:account`, permission `messages.<scope>`) checked by\n `checkResourceOperationPermission`, so the grantee also needs the tenant\n `messages.<scope>` permission (the ceiling). The owner holds every scope\n implicitly. Agents are `User` rows the host maps its credential to; the\n principal ceilings are intersected with the grant, never added to it.\n- `access-enforcement.ts` is a `GlobalInterceptors` entry registered at package\n load. Emails, folders and attachments (matched by STI ancestry) are filtered\n in `beforeList`/`afterList`/`afterGet`; raw `query()` on them is refused while\n any account is closed to the principal. Fail closed: no principal, no\n resolver or a foreign tenant means owned accounts are invisible. No tenant\n admin or super-admin bypass; trusted work (sync, outbox) uses\n `runWithMailSystemAccess()`. `EmailAccount.syncFrom()` does so itself.\n- Attachments carry a denormalized `accountId` (always derived from the message in a\n `beforeSave` interceptor, never caller-supplied) so lists, projections and counts filter in SQL; run\n `AttachmentCollection.backfillAccountIds()` once after upgrading (legacy rows\n without it are hidden from every read until then).\n- `connectMailbox` refuses by default: give the service `allowedMailHosts`\n (and optionally `allowedMailPorts`) or your own `validateMailbox`. The\n built-in validator never connects to private, loopback or link-local\n addresses and returns only a generic error. It checks every target field\n present (`host`, `endpoint`, and the `jmap` provider's `url`): https only, no\n userinfo, listed host and port. The `jmap` provider stays `available: false`\n on purpose (`available` means outbound transport; JMAP is receive and sync\n only), and `connectMailbox` still connects it. Policy lookups use the\n configured db handle, not a caller's transaction.\n- Writes to anything a later send would transmit (every row that is not\n `sent`: drafts, `pending`, `scheduled`, `sending`, `failed`, received mail\n saved, and any fresh row), attachments included, need the `draft` scope on\n an owned account, checked in `Message.save()`/`delete()` and\n `Attachment.save()`/`delete()`. Received mail (provider id, unflagged, plain\n `draft`) is never sent and may be deleted; a stored `sent` row cannot leave\n `sent`; read/flag changes alone need only `triage`. Rules and bypasses:\n [agents/send-approval.md](agents/send-approval.md#draft-writes).\n- `Message.send()` needs the `send` scope on an owned account. Agent sends\n (principal `kind` other than `person`/`human`) on a mail account are held\n for a person's approval unless the owner opted in to `auto_send`;\n approve / edit-then-approve / reject / release (as an approving person,\n never the agent) through `MailSendApprovalService`,\n drafts through `MailDraftService`, \"handled by\" on every message. Gate,\n binding and bypass rules: [agents/send-approval.md](agents/send-approval.md). Account rows are\n not filtered (senders, routes and the outbox read them without a principal).\n- `MailAccessService` (`grant`, `revoke`, `list`, `setOwner`) needs tenant\n `messages.manage-access` AND ownership (or delegation); an administrator\n cannot read, self-grant or take over an owned mailbox. Unowned accounts can be\n claimed once with `messages.manage-credentials`.\n- `MessagingSettingsService.listAccounts({ limit, cursor })` is the account\n discovery for a principal: only accounts it owns or holds an active grant on\n (never unowned or foreign accounts), with effective `scopes` and\n `relation: 'owner' | 'shared'`, via `decideMailAccess`. Fail closed with no\n principal user, a tenant mismatch or no `configureMailAccess`.\n- `seedMessagesRolePermissions({ db })` seeds the tenant `messages.*` slugs for\n the system roles (owner/admin: read, triage, draft, send, manage-credentials,\n manage-access; member: the four scopes; viewer: read). Idempotent, additive,\n system roles only; without it grants and `manage-access` fail closed on a\n fresh app. The matrix is `MESSAGES_ROLE_PERMISSION_MATRIX`.\n- Before `configureMailAccess` is called the policy still fails closed on\n owned accounts: every collection operation on a mail class (the core `onCollectionReady`\n interceptor hook, so STI subclasses on a default collection are covered) registers its\n database, per database, and the policy hides every owned account's mail\n through list, count, projections, facets and raw queries; it learns the database from the first mail or account row it\n sees and, with no principal resolver, hides every owned account's mail.\n Direct hydration (`new Email({ id }).initialize()`, `loadRelated()`) is gated\n in the models' `loadFromId`/`loadFromSlug`.\n- `connectionStatus` (`connected` / `needs_reconnect`) and `statusMessage` mark\n an account whose sign-in the server refused; `syncFrom()` sets it.\n\n## Mail search and private correspondents (#5132)\n\n`MailSearchService` searches only `read`-scoped accounts from `listAccounts()`;\n`CorrespondentService` derives owner-private contacts (optional `Profile` link).\nBoth fail closed. Details: [agents/mail-search.md](agents/mail-search.md).\n\n## Attachment storage root (#5645)\n\n`Attachment.filePath` is `<accountId>/...` relative to the root set once at startup with\n`configureAttachmentStorage({ root })` (beside `configureMailAccess`). Without\nit stored files are never read (fail closed). Rules, send behaviour and the\nupgrade step: [agents/attachment-storage.md](agents/attachment-storage.md).\n\n## Mailbox connect (provider-neutral)\n\nCredentials reach smrt-secrets in two ways; neither writes the plaintext `settings` fallback.\n\n- **Write-only app password**: `MessagingSettingsService.connectMailbox()`\n (permission `messages.manage-credentials`). The candidate credential is\n validated by opening a session first (`validateMailbox` option, default the\n provider's email client); a refusal leaves no account and no secret, and the\n error text has the secret redacted. The connecting user becomes the owner;\n `label` and the per-account endpoint (`configuration`) are stored; reconnect\n replaces the secret and is owner-only. `setAccountActive()` pauses/resumes\n (`isActive`), `removeAccount()` deletes the secret, the synced mail and the\n account. IMAP/POP3 are admitted here (receive-only), not by `saveAccount`.\n- **Generic OAuth 2.0 / OIDC**: `@happyvertical/smrt-messages/connect`\n (`startMailOAuthConnect`, `completeMailOAuthConnect`, `MailOAuthProvider`)\n on the shared kernel `@happyvertical/smrt-secrets/connect` (single-use\n tenant- and user-bound `ConnectState`, PKCE, safe return path, OIDC\n discovery with issuer check). The signed-in user becomes the owner; an\n account owned by someone else or by no one is never taken over. No role\n checks in the flow: authorize before calling.\n- **Reconnect**: `syncFrom()` marks an auth failure `connectionStatus =\n 'needs_reconnect'` (`Account.markNeedsReconnect/markConnected`) instead of\n failing silently.\n- The Google provider is a later step (sdk#1405), not part of this flow.\n\n## In-app notifications (`UserNotification`)\n\nThe in-app channel: one stored row per person, with read state.\n`user_notifications`: `tenantId` (required), `recipientUserId`\n(`@crossPackageRef` smrt-users:User, uuid), `kind`, `title`, `body`, `href`,\n`severity` (info/success/warning/error), `sourceRef`, `occurredAt`, `readAt`,\n`dismissedAt`. Conflict identity `(tenant_id, recipient_user_id, source_ref)`.\n\n- `UserNotificationService` is the only access path: `notify()` /\n `notifyMany()` (dedupe on `sourceRef`, existing row returned untouched;\n a unique ref is generated when omitted), `listForUser()` / `countUnread()`\n across explicit `tenantIds` (each read under `withTenant`), `markRead()`,\n `dismiss()` (also marks read), `markAllRead()`. Every write filters on the\n recipient, so another user's id matches nothing.\n- Generated REST/MCP/CLI are off (`api`/`mcp`/`cli: false`): a tenant-scoped\n list would expose every member's rows. Hosts expose their own routes that\n pass the signed-in user's id, never a request-chosen one.\n- Hosts decide who is told (e.g. `SocialPost.createdByUserId` for a failed\n post). New table: consumers run `db:migrate`.\n\n## Notification email outbox (`NotificationDelivery`)\n\n`NotificationOutboxService` is the external-channel counterpart of\n`UserNotificationService`: `enqueueEmail()` stores one delivery per\n`(tenant, recipient, channel, sourceRef)` after the host resolves the\nrecipient address and same-tenant sender account (callers never choose an\naddress); `dispatchDue()` leases due rows by compare-and-set\n(`NotificationDelivery.transition()`), creates the single outbound `Email`\nunder the lease, and settles sent/retry/failed/uncertain. Never resend an\n`uncertain` row automatically. Contract, retry, and reconciliation policy:\n[agents/notification-outbox.md](agents/notification-outbox.md). New table:\nconsumers run `db:migrate`.\n\n`NotificationOptOut` (`notification_opt_outs`, tenant-required, generated\nsurfaces off) is the per-recipient opt-out ledger for the outbox's\n`isSuppressed` hook, keyed `(tenant, recipient, channel, scope)` with scope `*`\nor `project:<uuid>`-style keys. `NotificationOptOutService`: idempotent\n`optOut`/`optIn` (with a `principal` only `userId === recipientUserId` may\nchange a row, and only in the principal's own `tenantId`, else\n`NotificationOptOutDeniedError`; no principal = trusted host code), trusted `isOptedOut` (a `*` row matches every scope), `listForRecipient`\n(principal required). `optOutSuppression(service, scopeOf)` builds the\n`isSuppressed` function. Details in the outbox doc; consumers run `db:migrate`.\n\n## Credential Security\n\nAccount credentials stored via tenant-bound `credentialSecretId` →\nsmrt-secrets. Use `setCredentials()`/`getCredentials()` — never store passwords\ndirectly. Credential descriptor schemas contain field definitions, never values.\n\n## Send Lifecycle\n\n`message.send()`: resolves account → creates provider sender → updates sendStatus. Retry support with `maxRetries` budget.\nA failure the provider may still have accepted carries\n`MessageSendResult.outcomeUnknown` (set by `EmailSender` unless\n`isDefiniteSendRejection()` proves a refusal, and when a sender throws) and is\npersisted as `metadata.sendOutcomeUnknown`; never auto-resend it.\n`EmailSender` attaches the message's stored `Attachment` rows (read through\n`Attachment.readContent()`, under the message's tenant context) plus\n`SendEmailOptions.attachments` bytes; an unreadable or file-less row fails the\nsend with the error on `sendError`, never a silent drop (#3808).\n`PersonaMessagingService.send({ attachments })` accepts them on email routes only.\n\n## Provider entry points (bundle boundary, #1979)\n\nThe package root is provider-neutral: models, collections, services,\npermissions, and the provider registry carry **zero provider-SDK weight**.\nProvider SDK wrappers (`@happyvertical/email`, `@happyvertical/messages`) are\nreachable only through explicit entry points, imported once at server startup:\n\n```ts\nimport '@happyvertical/smrt-messages/providers/email'; // smtp/imap/pop3/gmail\nimport '@happyvertical/smrt-messages/providers/slack';\nimport '@happyvertical/smrt-messages/providers/twitter';\nimport '@happyvertical/smrt-messages/providers/all'; // all of the above\n```\n\n- Without the matching entry, `EmailAccount.createClient()` (send + mailbox\n sync) throws an actionable error and `SlackSender`/`TweetSender` return a\n failure result naming the entry to import. Telegram and Zulip are\n fetch-based and always work from the root.\n- Builtin registry definitions stay metadata-only (setup fields for UIs); the\n entries upgrade them with `createEmailClient`/`createMessageClient`/\n `createSender` hooks. Never import a provider SDK from any module reachable\n from `src/index.ts` — the consumer bundle gate (`packages/bundle-gate`)\n fails CI when one becomes reachable.\n- `Attachment.readContent()` reads with `node:fs` through `host.ts` (stubbed\n in `host.browser.ts`), not `@happyvertical/files`; see Attachment storage.\n\n## Gotchas\n\n- **Manifest before decorators**: every decorated model imports\n `../__smrt-register__.js`, and `package.json#sideEffects` lists\n `./src/__smrt-register__.ts`. Without both, the library build dropped or\n reordered the self-registration, so dist classes registered with only their\n decorated fields and could adopt smrt-ledgers' same-named `Account` (#3098).\n- **`Account` is not unique**: smrt-ledgers also declares `Account` (on\n `ledger_accounts`). Resolve by constructor or qualified name; the\n coexistence tests (`ledger-account-identity-*`, and the PostgreSQL lane\n `pnpm test:postgres`) load both packages in both orders.\n Both declare the `accounts` collection, so registering the ledgers `Account`\n auto-loads this family from its manifest as STI siblings. Core loads this\n base with them and never takes the ledgers `Account` for it (#4735,\n `ledger-account-identity-sti-siblings.test.ts`).\n- **STI `_meta_type`**: qualified format `@happyvertical/smrt-messages:Email`\n- **JSON fields**: all address/metadata fields are JSON strings with `getX()`/`setX()` helpers\n- **RFC 822 threading**: Email uses `inReplyTo`/`messageId`/`references` — manual management required\n- **Attachment.messageId**: use this field (not `emailId`); old getter/setter mapped via deprecation wrapper\n- **Optional tenancy**: `@TenantScoped({ mode: 'optional' })` on Message, Account, Attachment\n- **Required tenancy**: endpoints and persona routes are always tenant scoped\n- **Secrets are write-only**: never serialize credentials or endpoint.address to an app\n\n## Intake byte snapshots\n\n`EmailAccount.readIntakeMessage(providerLookup, maxBytes, imapIdentity?)` is the authorized host seam for\nopt-in ingestion. It copies full-message attachment bytes from the registered\nemail provider and fails when only attachment metadata is available; it never\nreads provider-supplied paths or advances sync checkpoints. Keep this path\nprovider-neutral and exclude arbitrary headers/credentials from its snapshot.\nIMAP lookup must include folder/UIDVALIDITY/UID verification; sender Message-ID\nis a lookup hint, never the durable delivery identity.\n\nProtected notification Emails carry durable delivery provenance. Their canonical\n`send`/`retrySend`, ordinary save/delete, and default EmailSender handoff are\nconstrained by `protected-notification-handoff.ts` (package-private, never a root\nexport). Only the outbox enters its exact one-use scope after current trusted\npolicy/byte validation. Preserve old-row/constructor identity checks, current\npersisted lease checks at the actual provider boundary, copied byte buffers and\nunknown-outcome marker protection. See the outbox contract and shared protected\nhandoff suite (SQLite and migrated PostgreSQL).\n\n## Protected external contacts\n\nProfile email uses exclusive `recipientProfileId` plus `resolveProfileRecipient`, a reserved `profileNotificationPolicy` and exact current tenant-owned public Profile email. No User account is required. Before activating profiles, run normal framework schema migration and public `planNotificationProfileRecipients` / `migrateNotificationProfileRecipients`; runtime verifies physical constraints and never applies DDL. Legacy User notification and opt-out paths remain User-only. See [profile recipient contract and matrix](agents/profile-recipients.md).\n\n## Incremental mail sync (change feed)\n\n`EmailAccount.syncChanges({ limit?, maxBatches?, since? })` (`mail-sync.ts`) drives\n`EmailClient.getChanges()` (JMAP provider `jmap`; `@happyvertical/email` 0.114+).\n`syncFrom()` stays the polling path for IMAP/POP3.\n\n- `EmailAccount.syncCursor` is the opaque feed cursor (sensitive + readonly, never\n on generated surfaces). It is saved only after its batch is applied; a failure\n anywhere leaves it where it was, so the job just retries.\n- Rows are keyed on `Email.providerMessageId` (the server's own id, per account),\n so applying a batch twice changes nothing. Added/changed messages upsert,\n `removed` deletes, `folders` upserts `EmailFolder` by path and counts are\n recomputed for touched folders. Metadata-only changes keep stored bodies.\n- `resync-required` clears the cursor and runs a full pass in the same run; a\n full pass from no cursor deletes stored messages (with a `providerMessageId`)\n the server no longer has. A second resync request in one run throws.\n- One lane per account: runs queue behind each other in-process, work on the\n stored (revision-guarded) row, and the job is deduplicated per tenant+account.\n Inactive and `needs_reconnect` accounts, and clients without `getChanges`,\n return `{ status: 'skipped' }`. Auth failures call `markNeedsReconnect()` and\n throw with `retryable: false`. The sync runs under `runWithMailSystemAccess()`.\n- Job: `enqueueMailSync(account)` / `enqueueDueMailSyncs(accounts)`\n (`mail-sync-jobs.ts`, queue `mail-sync`, dedupe key `mail-sync:<accountId>`)\n target `EmailAccount.syncChanges` through `@happyvertical/smrt-jobs` (optional\n peer). The host runs the `TaskRunner` and schedules `enqueueDueMailSyncs`.\n- Backfill horizon (#5200): optional `EmailAccount.backfillSince` (null = whole\n mailbox, the default) or per-run `since` (`Date`/ISO string, `null` lifts the\n stored one; `enqueueMailSync({ since })` forwards it as an ISO string). A\n message dated before it is not stored unless it already is; undated mail is\n kept; `MailSyncResult.beforeHorizon` counts the skips. The SDK change feed\n cannot filter by date, so the server still sends the older mail and it is\n dropped here (saves rows, not transfer; a server-side horizon needs an SDK change).\n- Horizon vs cursor: `cursorHorizon` records the horizon the saved cursor was\n built under (null = unbounded, also legacy cursors). If a run's effective\n horizon is earlier than it, or cleared (`since: null`), the cursor is dropped\n and the run does a full pass with prune; narrowing or an unchanged horizon\n keeps the cursor.\n- Persisted health (#5200): `lastSyncError` is set on any failed run (also\n client-build failures and sign-in refusals, which additionally set\n `needs_reconnect`) and cleared by the next successful run; a transient failure\n never changes `connectionStatus`. `backlog` mirrors `MailSyncResult.hasMore`\n of the last successful run. Both are plain optional columns (additive).\n- Known gaps: attachment rows are not created (only `hasAttachments`/`size`);\n a renamed server folder creates a new folder row (stored messages keep the old\n path until they change); `jmap` has no connect-flow validator yet and is not an\n outbound transport.\n\n## Triage write-back\n\n`EmailAccount.triage(action, emailIds)` (and `Email.triage(action)`,\n`mail-triage.ts`) writes mark read/unread, star/unstar, archive, spam/not spam,\nlabel add/remove and move to the server, then updates the local row. Actions are\n`{ kind: 'markRead' | 'markUnread' | 'star' | 'unstar' | 'archive' | 'markSpam' |\n'unmarkSpam' }`, `{ kind: 'addLabels' | 'removeLabels', labels }` and\n`{ kind: 'move', folder }`; ids are local `Email` row ids.\n\n- Access: needs `read` **and** `triage` on the account (`assertMailAccess`, fail\n closed; `MailAccessError`) before any server call or local write.\n- Server first, per message: the result is `{ updated, failed, stale }`. Only ids\n the server accepted are written; refusals (and ids that are missing, on another\n account, or not yet synced) come back in `failed`. A thrown client error\n changes nothing. Auth failures mark the account `needs_reconnect`.\n- Convergence: an accepted message is read back (`getMessage`) and stored through\n `applyServerMessage`, exactly as sync stores it, so the next sync is a no-op.\n If the read-back fails the id is `stale` and sync fixes the row. Triage runs in\n the account's sync lane (`inLane`), so it never interleaves with a sync here.\n- Providers whose `getCapabilities().writeBack` lacks the needed key (`flags`,\n `labels`, `archive`, `spam`) throw `MailWriteBackUnsupportedError` first.\n- `move` removes a message from the mailboxes it is in now (from its stored\n labels) and adds `folder`; pass a path as stored on `EmailFolder`.\n- Every public method on an `@smrt()` class becomes a `<collection>.<method>`\n permission; `Email.triage` is why `messages.triage` in `permissions.ts` carries\n the generated name and description (the catalog rejects two for one slug).\n- Known gaps: drafts and send, the acting principal is not recorded (#5141), and\n a mailbox the server has not reported yet has no `EmailFolder` row until sync.\n",
|
|
14285
14285
|
"moduleDocs": [
|
|
14286
14286
|
{
|
|
14287
14287
|
"path": "agents/send-approval.md",
|
|
14288
14288
|
"module": "send-approval",
|
|
14289
|
-
"content": "# Agent send policy, held sends, drafts and \"handled by\" (#5141)\n\nEpic I (happyvertical.com#585). Code: `src/send-approval.ts`,\n`src/mail-drafts.ts`, the send path in `src/models/Message.ts`.\n\n## Who is an agent\n\nThe host supplies the acting principal through `configureMailAccess`'s\n`resolvePrincipal`. Only `kind: 'person'` (or `'human'`) is a person;\nanything else, including no label, is an agent. A persona route\n(`message.personaId`, `PersonaMessagingService`) is an agent send whoever\ninvoked it (requester `persona:<id>`). Trusted system work\n(`runWithMailSystemAccess`: sync, the outbox) is never held. With no\nprincipal: when a gate is configured, a persona send is held and any other\nsend is refused; without a gate, behaviour is unchanged.\n\n## Policy\n\n`EmailAccount.agentSendPolicy`: null or `require_approval` (default) holds an\nagent's send; `auto_send` lets it leave. Only the account owner, as a person,\nwith tenant `messages.manage-access`, changes it\n(`MailAccessService.setAgentSendPolicy`); raising to `auto_send` needs\n`confirmAutoSend: true` (the smrt-social public-latch pattern), lowering is\ninstant, and a change of owner resets it to null. A host per-rule hook (`configureMailSendApprovals({\nresolveAgentSendPolicy })`) may answer either way for one send; null falls\nback to the account. Non-mail accounts have no policy and are not held.\n\n## Held send\n\n`Message.send()` checks `send` scope, then send-as (on an owned account a\nprincipal sends only from the account's own address), then\n`holdAgentSend()`. Send-as applies to every mail account (owned or not)\noutside system access. For an agent under `require_approval` it:\n\n1. refuses without a configured gate, without a tenant, for an unsaved draft\n or a caller copy that differs from the stored row, and for send-time\n attachment bytes;\n2. hashes the stored draft (`mailSendBindingHash`: account, from, to/cc/bcc,\n subject, bodies, threading headers, stored attachment rows and a SHA-256\n of each attachment file's bytes);\n3. calls the gate's `check`, which only reports: `pending` or `approved`\n both return `pendingApproval` and send nothing. The agent never sends a\n held draft itself; it goes out once, as the approving person.\n\nA held message is set to `draft` (a persona route creates it `pending`), so\nit leaves every pending/scheduled outbox and a person can decide it. A\npersona message is held even under system access, so a system drain never\nsends it around its approval. Send-time attachment bytes (for example\n`PersonaMessagingService` `attachments`) are refused on a held send: they are\nnot stored, so no person could review them and nothing could bind them;\nstore them as `Attachment` rows on the message instead. A refused send of a\n`pending`/`scheduled` message is marked `failed` (definite), never left\nqueued.\n\nAfter the row is claimed, a send an approval released re-hashes the draft\n(attachment rows included); a mismatch fails definitely and sends nothing.\nThe approval request carries a neutral summary, never mail content: request\nand event rows are readable tenant-wide.\n\nThe gate is structural; smrt-approvals' `createApprovalMailSendGate`\nimplements it (kind `messages.mail.send`). smrt-messages has a dev dependency\non smrt-approvals for tests only.\n\n## Deciding\n\n`MailSendApprovalService` acts as the resolved principal, which must be a\nperson holding `read` and `send` on the draft's account in the same tenant.\nDeciding also needs the tenant `messages.send` permission, checked through\nsmrt-users with no bypass (on an unowned account the per-account decision\nchecks none). `approve(id, { edits? })` refuses a draft that changed since\nthe request (`draft_changed`); with edits it approves the revised hash first\n(edit-then-approve), then saves the edits; once the approval is complete it\nconsumes it and sends as the person. `release(id)` sends a request already\napproved elsewhere (a generic inbox), only by one of its approvers. Before\nany consume every counted approver is re-verified (tenant `messages.send`\nand `send` on the account). `reject(id, reason)` keeps the draft.\nDouble release is prevented by the single-use consume and the send claim.\n\n## Audit and \"handled by\"\n\nTriage, draft saves and sends stamp `handledById` / `handledByKind` /\n`handledAt` on the message (`getHandledBy()`, `threadHandledBy()` for a\nthread). When the host runs the action inside smrt-core `withAuditContext()`,\n`auditMailAction` writes `messages.draft.save`, `messages.send.held`,\n`messages.send.approved[-with-edits]`, `messages.send.rejected`,\n`messages.send` (before the provider call; a writer failure stops the send)\nand `messages.triage.<action>`. Mail models are not `audit: true`: that makes\nevery sync and outbox write demand a writer.\n\nDeciding needs an unsent draft or a definitely failed send (`not_a_draft`\notherwise; an outcome-unknown send is never re-approved). On an unowned\n(tenant-wide) account the per-account checks pass for any tenant person, the\nsame authority as sending directly from it.\n\n## Known gaps\n\n- No approval-queue or handled-by Svelte component yet.\n- Attachment bytes are re-read by the sender after the post-claim check, a\n narrow window.\n- A crash between consume and send leaves a consumed approval and an unsent\n draft; the agent resubmits for a new approval.\n\n## Draft writes\n\nThe `draft` scope is needed: `Message.save()` and `Message.delete()`\ncheck it (`assertMailScopeOn`, `access.ts`) for
|
|
14289
|
+
"content": "# Agent send policy, held sends, drafts and \"handled by\" (#5141)\n\nEpic I (happyvertical.com#585). Code: `src/send-approval.ts`,\n`src/mail-drafts.ts`, the send path in `src/models/Message.ts`.\n\n## Who is an agent\n\nThe host supplies the acting principal through `configureMailAccess`'s\n`resolvePrincipal`. Only `kind: 'person'` (or `'human'`) is a person;\nanything else, including no label, is an agent. A persona route\n(`message.personaId`, `PersonaMessagingService`) is an agent send whoever\ninvoked it (requester `persona:<id>`). Trusted system work\n(`runWithMailSystemAccess`: sync, the outbox) is never held. With no\nprincipal: when a gate is configured, a persona send is held and any other\nsend is refused; without a gate, behaviour is unchanged.\n\n## Policy\n\n`EmailAccount.agentSendPolicy`: null or `require_approval` (default) holds an\nagent's send; `auto_send` lets it leave. Only the account owner, as a person,\nwith tenant `messages.manage-access`, changes it\n(`MailAccessService.setAgentSendPolicy`); raising to `auto_send` needs\n`confirmAutoSend: true` (the smrt-social public-latch pattern), lowering is\ninstant, and a change of owner resets it to null. A host per-rule hook (`configureMailSendApprovals({\nresolveAgentSendPolicy })`) may answer either way for one send; null falls\nback to the account. Non-mail accounts have no policy and are not held.\n\n## Held send\n\n`Message.send()` checks `send` scope, then send-as (on an owned account a\nprincipal sends only from the account's own address), then\n`holdAgentSend()`. Send-as applies to every mail account (owned or not)\noutside system access. For an agent under `require_approval` it:\n\n1. refuses without a configured gate, without a tenant, for an unsaved draft\n or a caller copy that differs from the stored row, and for send-time\n attachment bytes;\n2. hashes the stored draft (`mailSendBindingHash`: account, from, to/cc/bcc,\n subject, bodies, threading headers, stored attachment rows and a SHA-256\n of each attachment file's bytes);\n3. calls the gate's `check`, which only reports: `pending` or `approved`\n both return `pendingApproval` and send nothing. The agent never sends a\n held draft itself; it goes out once, as the approving person.\n\nA held message is set to `draft` and flagged `isDraft` (a persona route creates it `pending`), so\nit leaves every pending/scheduled outbox and a person can decide it. A\npersona message is held even under system access, so a system drain never\nsends it around its approval. Send-time attachment bytes (for example\n`PersonaMessagingService` `attachments`) are refused on a held send: they are\nnot stored, so no person could review them and nothing could bind them;\nstore them as `Attachment` rows on the message instead. A refused send of a\n`pending`/`scheduled` message is marked `failed` (definite), never left\nqueued.\n\nAfter the row is claimed, a send an approval released re-hashes the draft\n(attachment rows included); a mismatch fails definitely and sends nothing.\nThe approval request carries a neutral summary, never mail content: request\nand event rows are readable tenant-wide.\n\nThe gate is structural; smrt-approvals' `createApprovalMailSendGate`\nimplements it (kind `messages.mail.send`). smrt-messages has a dev dependency\non smrt-approvals for tests only.\n\n## Deciding\n\n`MailSendApprovalService` acts as the resolved principal, which must be a\nperson holding `read` and `send` on the draft's account in the same tenant.\nDeciding also needs the tenant `messages.send` permission, checked through\nsmrt-users with no bypass (on an unowned account the per-account decision\nchecks none). `approve(id, { edits? })` refuses a draft that changed since\nthe request (`draft_changed`); with edits it approves the revised hash first\n(edit-then-approve), then saves the edits; once the approval is complete it\nconsumes it and sends as the person. `release(id)` sends a request already\napproved elsewhere (a generic inbox), only by one of its approvers. Before\nany consume every counted approver is re-verified (tenant `messages.send`\nand `send` on the account). `reject(id, reason)` keeps the draft.\nDouble release is prevented by the single-use consume and the send claim.\n\n## Audit and \"handled by\"\n\nTriage, draft saves and sends stamp `handledById` / `handledByKind` /\n`handledAt` on the message (`getHandledBy()`, `threadHandledBy()` for a\nthread). When the host runs the action inside smrt-core `withAuditContext()`,\n`auditMailAction` writes `messages.draft.save`, `messages.send.held`,\n`messages.send.approved[-with-edits]`, `messages.send.rejected`,\n`messages.send` (before the provider call; a writer failure stops the send)\nand `messages.triage.<action>`. Mail models are not `audit: true`: that makes\nevery sync and outbox write demand a writer.\n\nDeciding needs an unsent draft or a definitely failed send (`not_a_draft`\notherwise; an outcome-unknown send is never re-approved). On an unowned\n(tenant-wide) account the per-account checks pass for any tenant person, the\nsame authority as sending directly from it.\n\n## Known gaps\n\n- No approval-queue or handled-by Svelte component yet.\n- Attachment bytes are re-read by the sender after the post-claim check, a\n narrow window.\n- A crash between consume and send leaves a consumed approval and an unsent\n draft; the agent resubmits for a new approval.\n\n## Draft writes\n\nThe `draft` scope is needed: `Message.save()` and `Message.delete()`\ncheck it (`assertMailScopeOn`, `access.ts`) for unsent outgoing mail (below)\nnow or when stored, by id or by the slug a new object would take over (its own\nor the one derived from its id), and for both accounts when a row moves. A\ndraft flag is `isDraft` in any stored form (`true`, `1`, `'1'`, `'true'`). The\nstored row decides, whatever class the handle is. The\ngrants and account owner are read before the write (a single-connection\nengine cannot serve the policy handle inside a transaction); the write then\nre-reads the stored row and refuses a save that now needs more.\n`Attachment.save()`/`delete()` need the same scope when the message they\nbelong to (or are moved from) is gated (`isMailWriteGated`). A write is gated\nfor every row that is not `sent`, because a later send would transmit it. That\nincludes received mail when it is saved, so content cannot be written without\nthe scope and then flipped into a draft; deleting received mail (and its\nattachments) stays open. Received mail is a provider-tagged row (`messageId`,\n`providerMessageId`, `folderId`, `tweetId` or `slackTs` set) that is unflagged\nand still `draft`; `Message.send()` refuses it, stored row included. A `draft`\nrow with no provider id, a flagged draft, and `pending`, `scheduled`,\n`sending`, `failed` or an unknown status are gated like any other.\n`Message.save()`/`delete()` apply the same test to the stored row and to the\nstate a row is moved into, so a row cannot be relabelled or stripped of its\nprovider id around the check. A stored `sent` row cannot be moved out of\n`sent` by a principal (sent mail is a record); an instance loaded before the\nrow was sent is refused the same way, so a stale save cannot make it sendable\nagain. A fresh row needs `draft` too, except a row the send path itself creates\n(an unsaved message being sent) or the persona route queues, which needs\n`send` (the route saves through a module-private helper, `saveQueuedForSend`,\nvalid only for a fresh row). A save that changes only `isRead` and `isFlagged`\nof a stored row needs the `triage` scope instead of `draft`, so triage marks work on queued rows, and\n`markAllRead` / `markFolderRead` try every row before raising the first error.\nSync stores received mail under `runWithMailSystemAccess`; a host that stores received mail itself does the same. A held\nsend's binding hash still covers its attachment rows. The attachment check\nruns just before the write, not inside it.\nThat covers generated routes, collection `delete`/`getOrUpsert`,\n`createReply`/`createForward` + `save()` and `MailDraftService`. Trusted work\n(`runWithMailSystemAccess`: sync, outbox, triage write-back, approval edits)\nskips it. The send lifecycle's own saves and a held send's move back to draft\nneed `send` instead, and only while every stored field outside the lifecycle\nfields (`sendStatus`, `sentAt`, `sendError`, `retryCount`, handled-by,\n`updatedAt`) is unchanged, tenant, slug, context and subclass fields included.\nA row the send path itself creates (an unsaved message being sent) needs\n`send` too (a queued row whose account no longer exists is marked `failed`\nwith nothing else changed, without a scope). As for read, triage and send, a\nprincipal's scope and account ceilings apply to unowned accounts too; with no principal an owned account is\nclosed and an unowned one is open.\n"
|
|
14290
14290
|
},
|
|
14291
14291
|
{
|
|
14292
14292
|
"path": "agents/mail-search.md",
|
|
@@ -5,10 +5,10 @@ description: "Unified multi-channel messaging with STI-based hierarchies"
|
|
|
5
5
|
status: "stable"
|
|
6
6
|
generated:
|
|
7
7
|
by: "smrt/scripts/generate-knowledge-okf.ts"
|
|
8
|
-
at: "2026-11-
|
|
8
|
+
at: "2026-11-26T12:28:07Z"
|
|
9
9
|
audience: "internal"
|
|
10
10
|
evidence_level: "source-inspected"
|
|
11
|
-
source_revision: "sha256:
|
|
11
|
+
source_revision: "sha256:fb30937962165389551630afb4c4aa2bc50d49b6a6224e59932c892770ee7980"
|
|
12
12
|
sources:
|
|
13
13
|
- id: "manifest"
|
|
14
14
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/messages/package.json"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-messages",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.72.0",
|
|
4
4
|
"smrtJsdoc": "strict",
|
|
5
5
|
"description": "Unified multi-channel messaging with STI-based hierarchies",
|
|
6
6
|
"type": "module",
|
|
@@ -67,14 +67,14 @@
|
|
|
67
67
|
"@happyvertical/files": "^0.116.6",
|
|
68
68
|
"@happyvertical/logger": "^0.116.6",
|
|
69
69
|
"@happyvertical/messages": "^0.116.6",
|
|
70
|
-
"@happyvertical/smrt-core": "0.
|
|
71
|
-
"@happyvertical/smrt-jobs": "0.
|
|
72
|
-
"@happyvertical/smrt-profiles": "0.
|
|
73
|
-
"@happyvertical/smrt-secrets": "0.
|
|
74
|
-
"@happyvertical/smrt-tenancy": "0.
|
|
75
|
-
"@happyvertical/smrt-types": "0.
|
|
76
|
-
"@happyvertical/smrt-ui": "0.
|
|
77
|
-
"@happyvertical/smrt-users": "0.
|
|
70
|
+
"@happyvertical/smrt-core": "0.72.0",
|
|
71
|
+
"@happyvertical/smrt-jobs": "0.72.0",
|
|
72
|
+
"@happyvertical/smrt-profiles": "0.72.0",
|
|
73
|
+
"@happyvertical/smrt-secrets": "0.72.0",
|
|
74
|
+
"@happyvertical/smrt-tenancy": "0.72.0",
|
|
75
|
+
"@happyvertical/smrt-types": "0.72.0",
|
|
76
|
+
"@happyvertical/smrt-ui": "0.72.0",
|
|
77
|
+
"@happyvertical/smrt-users": "0.72.0",
|
|
78
78
|
"@happyvertical/sql": "^0.116.6",
|
|
79
79
|
"@happyvertical/utils": "^0.116.6"
|
|
80
80
|
},
|
|
@@ -91,9 +91,9 @@
|
|
|
91
91
|
}
|
|
92
92
|
},
|
|
93
93
|
"devDependencies": {
|
|
94
|
-
"@happyvertical/smrt-approvals": "0.
|
|
95
|
-
"@happyvertical/smrt-ledgers": "0.
|
|
96
|
-
"@happyvertical/smrt-vitest": "0.
|
|
94
|
+
"@happyvertical/smrt-approvals": "0.72.0",
|
|
95
|
+
"@happyvertical/smrt-ledgers": "0.72.0",
|
|
96
|
+
"@happyvertical/smrt-vitest": "0.72.0",
|
|
97
97
|
"@sveltejs/package": "^2.5.8",
|
|
98
98
|
"@sveltejs/vite-plugin-svelte": "^7.3.0",
|
|
99
99
|
"@types/node": "24.13.6",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"AttachmentCollection-C14dERNK.js","names":[],"sources":["../../src/models/Attachment.ts","../../src/collections/AttachmentCollection.ts"],"sourcesContent":["/**\n * Attachment model - Generalized attachment for any message type\n *\n * Uses messageId instead of emailId for cross-type support.\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n foreignKey,\n ObjectRegistry,\n SmrtObject,\n type SmrtSaveOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport {\n assertHydratedMailAccess,\n assertMailDraftWrite,\n inMailSystemAccess,\n isUnsentDraft,\n learnMailAccessOptions,\n} from '../access.js';\nimport {\n readStoredAttachmentFile,\n scopeAttachmentPath,\n} from '../attachment-storage.js';\nimport type { AttachmentOptions } from '../types';\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get', 'create', 'delete'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class Attachment extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n @foreignKey('Message')\n messageId = '';\n /**\n * The mail account this file belongs to. Copied from its message when the\n * attachment is saved, so per-account mail access can filter attachment\n * reads (lists, projections, counts) without a join. Null for rows saved\n * before the column existed: run `AttachmentCollection.backfillAccountIds()`.\n */\n @foreignKey('Account')\n accountId: string | null = null;\n filename = '';\n contentType = '';\n size = 0;\n contentId = ''; // For inline images (<img src=\"cid:...\">)\n contentDisposition: 'attachment' | 'inline' = 'attachment';\n filePath = ''; // External file storage path\n sourceUrl = ''; // For non-email attachments (media URLs, etc.)\n\n // Timestamps\n createdAt = new Date();\n\n constructor(options: AttachmentOptions = {}) {\n super(options);\n\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.messageId !== undefined) this.messageId = options.messageId;\n if (options.accountId !== undefined)\n this.accountId = options.accountId || null;\n if (options.filename !== undefined) this.filename = options.filename;\n if (options.contentType !== undefined)\n this.contentType = options.contentType;\n if (options.size !== undefined) this.size = options.size;\n if (options.contentId !== undefined) this.contentId = options.contentId;\n if (options.contentDisposition !== undefined)\n this.contentDisposition = options.contentDisposition;\n if (options.filePath !== undefined) this.filePath = options.filePath;\n if (options.sourceUrl !== undefined) this.sourceUrl = options.sourceUrl;\n if (options.createdAt) this.createdAt = options.createdAt;\n }\n\n /**\n * Direct hydration (`new X({ id }).initialize()`, `loadRelated()`) bypasses\n * the collection read hooks, so the per-account mail policy is applied here\n * too: a row of an account closed to the principal never hydrates.\n */\n override async loadFromId() {\n await super.loadFromId();\n await assertHydratedMailAccess(this);\n }\n\n override async loadFromSlug() {\n await super.loadFromSlug();\n await assertHydratedMailAccess(this);\n }\n\n /**\n * An attachment is part of what its message will send, so writing one on an\n * unsent email draft of an owned account needs the same `draft` scope as\n * writing the draft (see `Message.save()`), whichever route the write takes.\n * Both the parent it is saved onto and the parent it is stored on count, so\n * an attachment cannot be moved on or off a draft without the scope.\n */\n override async save(options?: SmrtSaveOptions): Promise<this> {\n // A stored path is relative to the attachment storage root and under the\n // message account's directory: refuse anything else before it is written,\n // and keep the normalised form.\n if (this.filePath) {\n this.filePath = scopeAttachmentPath(\n this.filePath,\n await this.currentAccountId(),\n );\n }\n await this.assertDraftParentWrite();\n return super.save(options);\n }\n\n override async delete(\n options: { expectedUpdatedAt?: Date | string } = {},\n ): Promise<void> {\n await this.assertDraftParentWrite();\n return super.delete(options);\n }\n\n /**\n * The account of the message this row is stored on now, read from the\n * stored message (never from the row's own `accountId`), or null.\n */\n private async currentAccountId(): Promise<string | null> {\n if (!this.messageId) return null;\n try {\n const { MessageCollection } = await import(\n '../collections/MessageCollection.js'\n );\n const messages = await MessageCollection.create(this.options as never);\n const parent = (await this.db.get(messages.tableName, {\n id: this.messageId,\n })) as Record<string, unknown> | null;\n return (parent?.account_id as string | null) || null;\n } catch {\n return null;\n }\n }\n\n /**\n * Trusted system work and non-draft parents pass. Unlike the message check\n * this runs before the write, not inside its transaction: the attachment\n * save interceptor builds collections from the instance's options, and\n * inside a transaction those would register the transaction's handle as a\n * policy database.\n */\n private async assertDraftParentWrite(): Promise<void> {\n learnMailAccessOptions(this.options);\n if (inMailSystemAccess()) return;\n const parentIds = new Set<string>();\n if (this.messageId) parentIds.add(this.messageId);\n if (this.id) {\n const stored = await this.getCanonicalPersistedRow({ id: this.id });\n if (typeof stored?.message_id === 'string' && stored.message_id) {\n parentIds.add(stored.message_id);\n }\n }\n // A new attachment is written over the stored row that carries its slug\n // (its own, or the one the save derives from its id): that row's parent is\n // the one it changes.\n const slug = this.isPersisted ? '' : this.slug || (await this.getSlug());\n if (slug) {\n const columns = ObjectRegistry.getConflictColumns(\n this.getResolvedQualifiedName(),\n );\n if (columns.includes('slug')) {\n for (const keyed of await this.getCanonicalPersistedRows({\n slug,\n })) {\n if (typeof keyed.message_id === 'string' && keyed.message_id) {\n parentIds.add(keyed.message_id);\n }\n }\n }\n }\n if (!parentIds.size) return;\n const { MessageCollection } = await import(\n '../collections/MessageCollection.js'\n );\n const messages = await MessageCollection.create(this.options as never);\n const accountIds: Array<string | null> = [];\n for (const id of parentIds) {\n const parent = (await this.db.get(messages.tableName, { id })) as Record<\n string,\n unknown\n > | null;\n if (parent && isUnsentDraft(parent.send_status, parent.is_draft)) {\n accountIds.push((parent.account_id as string | null) ?? null);\n }\n }\n await assertMailDraftWrite(accountIds, this.options);\n }\n\n /**\n * Get the message this attachment belongs to\n */\n async getMessage() {\n if (!this.messageId) return null;\n\n const { MessageCollection } = await import(\n '../collections/MessageCollection'\n );\n const collection = await MessageCollection.create(this.options);\n\n return await collection.get({ id: this.messageId });\n }\n\n /**\n * Check if attachment is an image\n */\n isImage(): boolean {\n return this.contentType.startsWith('image/');\n }\n\n /**\n * Check if attachment is a PDF\n */\n isPdf(): boolean {\n return this.contentType === 'application/pdf';\n }\n\n /**\n * Check if attachment is inline (embedded in message body)\n */\n isInline(): boolean {\n return this.contentDisposition === 'inline';\n }\n\n /**\n * Get file extension from filename\n */\n getExtension(): string {\n if (!this.filename) return '';\n const parts = this.filename.split('.');\n return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';\n }\n\n /**\n * Get human-readable file size\n */\n getFormattedSize(): string {\n const units = ['B', 'KB', 'MB', 'GB'];\n let size = this.size;\n let unitIndex = 0;\n\n while (size >= 1024 && unitIndex < units.length - 1) {\n size /= 1024;\n unitIndex++;\n }\n\n return `${size.toFixed(1)} ${units[unitIndex]}`;\n }\n\n /**\n * Check if file is stored externally\n */\n hasExternalFile(): boolean {\n return !!this.filePath;\n }\n\n /**\n * Read the stored file's bytes, or null when the row has no file or the\n * file is missing or unreadable.\n *\n * `filePath` is relative to the root set with `configureAttachmentStorage`\n * and must lie under `<accountId>/` of the message's current account.\n * Throws `AttachmentStorageError` when no root is configured, or when the\n * stored path (or a symlink under it) leaves the root or the account's\n * directory; this includes rows stored before the root existed. The bytes are read\n * raw: decoding a PDF as UTF-8 corrupts it (#3808).\n */\n async readContent(): Promise<Buffer | null> {\n if (!this.filePath) return null;\n return readStoredAttachmentFile(\n this.filePath,\n await this.currentAccountId(),\n );\n }\n}\n","/**\n * AttachmentCollection - Generalized attachment collection using messageId\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { runWithMailSystemAccess } from '../access.js';\nimport { queryGlobal, queryWithGlobals } from '../host.js';\nimport { Attachment } from '../models/Attachment';\n\nexport class AttachmentCollection extends SmrtCollection<Attachment> {\n static readonly _itemClass = Attachment;\n\n /**\n * Fill `accountId` on attachments saved before the column existed, from\n * their message. Run once per tenant after upgrading; safe to repeat.\n * Returns the number of rows updated.\n */\n async backfillAccountIds(): Promise<number> {\n return runWithMailSystemAccess(async () => {\n const { MessageCollection } = await import('./MessageCollection');\n const messages = await MessageCollection.create(this.options);\n let updated = 0;\n for (const attachment of await this.list({\n where: { accountId: null },\n })) {\n if (!attachment.messageId) continue;\n const message = await messages.get({ id: attachment.messageId });\n if (!message?.accountId) continue;\n // A direct column write: a row stored before the attachment storage\n // root existed may hold a path `save()` now refuses, and the backfill\n // must still make it visible.\n await this.db.update(\n this.tableName,\n { id: attachment.id },\n { account_id: message.accountId },\n );\n updated++;\n }\n return updated;\n });\n }\n\n /**\n * Get attachments for a message\n */\n async getByMessage(messageId: string): Promise<Attachment[]> {\n return await this.list({ where: { messageId } });\n }\n\n /**\n * Get attachments by content type\n */\n async getByContentType(contentType: string): Promise<Attachment[]> {\n return await this.list({ where: { contentType } });\n }\n\n /**\n * Get image attachments\n */\n async getImages(messageId?: string): Promise<Attachment[]> {\n const attachments = messageId\n ? await this.getByMessage(messageId)\n : await this.list({});\n\n return attachments.filter((a) => a.isImage());\n }\n\n /**\n * Get PDF attachments\n */\n async getPdfs(messageId?: string): Promise<Attachment[]> {\n const attachments = messageId\n ? await this.getByMessage(messageId)\n : await this.list({});\n\n return attachments.filter((a) => a.isPdf());\n }\n\n /**\n * Get inline attachments (embedded in message body)\n */\n async getInline(messageId: string): Promise<Attachment[]> {\n const attachments = await this.getByMessage(messageId);\n return attachments.filter((a) => a.isInline());\n }\n\n /**\n * Get regular attachments (not inline)\n */\n async getRegular(messageId: string): Promise<Attachment[]> {\n const attachments = await this.getByMessage(messageId);\n return attachments.filter((a) => !a.isInline());\n }\n\n /**\n * Get attachments with external files\n */\n async getWithExternalFiles(): Promise<Attachment[]> {\n const attachments = await this.list({});\n return attachments.filter((a) => a.hasExternalFile());\n }\n\n /**\n * Get total size of attachments for a message\n */\n async getTotalSize(messageId: string): Promise<number> {\n const attachments = await this.getByMessage(messageId);\n return attachments.reduce((sum, a) => sum + a.size, 0);\n }\n\n /**\n * Get largest attachments\n */\n async getLargest(limit = 10): Promise<Attachment[]> {\n const attachments = await this.list({});\n return attachments.sort((a, b) => b.size - a.size).slice(0, limit);\n }\n\n /**\n * Search attachments by filename\n */\n async searchByFilename(query: string): Promise<Attachment[]> {\n const attachments = await this.list({});\n const lowerQuery = query.toLowerCase();\n\n return attachments.filter((a) =>\n a.filename?.toLowerCase().includes(lowerQuery),\n );\n }\n\n /**\n * Get attachments by extension\n */\n async getByExtension(extension: string): Promise<Attachment[]> {\n const attachments = await this.list({});\n const lowerExt = extension.toLowerCase().replace(/^\\./, '');\n\n return attachments.filter((a) => a.getExtension() === lowerExt);\n }\n\n /**\n * Get attachment statistics\n */\n async getStats(): Promise<{\n total: number;\n totalSize: number;\n byType: Record<string, number>;\n inline: number;\n regular: number;\n }> {\n const attachments = await this.list({});\n\n const byType: Record<string, number> = {};\n for (const attachment of attachments) {\n const type = attachment.contentType.split('/')[0] || 'other';\n byType[type] = (byType[type] || 0) + 1;\n }\n\n return {\n total: attachments.length,\n totalSize: attachments.reduce((sum, a) => sum + a.size, 0),\n byType,\n inline: attachments.filter((a) => a.isInline()).length,\n regular: attachments.filter((a) => !a.isInline()).length,\n };\n }\n\n /**\n * Delete all attachments for a message\n */\n async deleteByMessage(messageId: string): Promise<number> {\n const attachments = await this.getByMessage(messageId);\n let count = 0;\n\n for (const attachment of attachments) {\n await attachment.delete();\n count++;\n }\n\n return count;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n async findByTenant(tenantId: string): Promise<Attachment[]> {\n return this.list({ where: { tenantId } });\n }\n\n // Attachment is @TenantScoped (CTI, own `attachments` table). Under an active\n // tenant context list({ tenantId: null }) throws and unflagged raw SQL is\n // blocked (#1596); route through the raw helpers.\n async findGlobal(): Promise<Attachment[]> {\n return queryGlobal<Attachment>(this);\n }\n\n async findWithGlobals(tenantId: string): Promise<Attachment[]> {\n return que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message-CGyhd0kh.js","names":["result"],"sources":["../../src/models/Message.ts"],"sourcesContent":["import type {\n SmrtClassOptions,\n SmrtSaveOptions,\n} from '@happyvertical/smrt-core';\nimport {\n assertProtectedNotificationDelete,\n assertProtectedNotificationRetry,\n assertProtectedNotificationSave,\n assertProtectedSenderHandoff,\n beginProtectedNotificationSend,\n ProtectedNotificationHandoffError,\n rememberNotificationOrigin,\n} from '../protected-notification-handoff.js';\n/**\n * Message model - Base class for all message types (STI)\n *\n * Common fields shared across email, tweets, slack messages, etc.\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n crossPackageRef,\n field,\n foreignKey,\n ObjectRegistry,\n SmrtObject,\n smrt,\n usesEmbeddedRevisionFallback,\n withEmbeddedWriteQueue,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport {\n assertHydratedMailAccess,\n assertMailScopeOn,\n decideMailAccess,\n inMailSystemAccess,\n isUnsentDraft,\n learnMailAccessOptions,\n MailAccessError,\n type MailPrincipal,\n type MailScope,\n mailFlag,\n resolveMailPrincipal,\n} from '../access.js';\nimport {\n approvedDraftChanged,\n auditMailAction,\n holdAgentSend,\n stampHandledBy,\n} from '../send-approval.js';\nimport type {\n MessageOptions,\n MessageSendResult,\n SendMessageOptions,\n SendStatus,\n} from '../types';\n\n/** `metadata` key recording that the last failed send may have been accepted. */\nexport const SEND_OUTCOME_UNKNOWN_METADATA_KEY = 'sendOutcomeUnknown';\n\n/**\n * The stored metadata JSON with the outcome-unknown marker set or cleared, or\n * undefined when it needs no change (or is not a JSON object to edit).\n */\nfunction withSendOutcomeMarker(\n stored: unknown,\n outcomeUnknown: boolean,\n): string | undefined {\n let bag: Record<string, unknown> = {};\n if (typeof stored === 'string' && stored.trim()) {\n try {\n const parsed: unknown = JSON.parse(stored);\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return undefined;\n }\n bag = parsed as Record<string, unknown>;\n } catch {\n return undefined;\n }\n }\n if (Boolean(bag[SEND_OUTCOME_UNKNOWN_METADATA_KEY]) === outcomeUnknown) {\n return undefined;\n }\n if (outcomeUnknown) bag[SEND_OUTCOME_UNKNOWN_METADATA_KEY] = true;\n else delete bag[SEND_OUTCOME_UNKNOWN_METADATA_KEY];\n return JSON.stringify(bag);\n}\n\n// Only the canonical send/retry implementation can authorize its exact local\n// lifecycle save. An active provider scope never grants arbitrary public saves.\nconst lifecycleSaves = new WeakMap<Message, string>();\nfunction lifecycleSignature(message: Message): string {\n return JSON.stringify([\n message.sendStatus,\n message.retryCount,\n message.maxRetries,\n message.sendError,\n message.sentAt,\n message.scheduledSendAt,\n message.metadata,\n ]);\n}\nasync function saveSendLifecycle(message: Message): Promise<void> {\n lifecycleSaves.set(message, lifecycleSignature(message));\n try {\n await message.save();\n } finally {\n lifecycleSaves.delete(message);\n }\n}\n\n// Internal saves that already hold the `send` decision and may move a message\n// back to draft (a held send); they skip the draft-scope check.\nconst heldSaves = new WeakSet<Message>();\nasync function saveHeld(message: Message): Promise<void> {\n heldSaves.add(message);\n try {\n await message.save();\n } finally {\n heldSaves.delete(message);\n }\n}\n\n/**\n * The only fields a send-path save of a draft may change: the send lifecycle,\n * the handled-by stamp and the revision. Everything else, including fields the\n * package does not know (tenant, slug, context, subclass fields), must equal\n * the stored row.\n */\nconst SEND_PATH_MAY_CHANGE = new Set([\n 'sendStatus',\n 'sentAt',\n 'sendError',\n 'retryCount',\n 'handledById',\n 'handledByKind',\n 'handledAt',\n 'updatedAt',\n]);\n\nconst DATE_LIKE =\n /^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$/;\n\n/** One comparable form of a field value, whether instance or stored row. */\nfunction canonValue(value: unknown): string {\n if (value === undefined || value === null) return '';\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? '' : value.toISOString();\n }\n if (typeof value === 'object') return JSON.stringify(value);\n if (typeof value === 'string') {\n if (DATE_LIKE.test(value)) {\n const time = Date.parse(value);\n if (!Number.isNaN(time)) return new Date(time).toISOString();\n }\n if (value.startsWith('[') || value.startsWith('{')) {\n try {\n return JSON.stringify(JSON.parse(value));\n } catch {\n return value;\n }\n }\n }\n return String(value);\n}\n\nconst DRAFT_CARRIED_FIELDS = new Set(['tenantId', 'metadata', 'correlationId']);\n\n/**\n * Stored fields declared by Message and Email. A derived reply/forward draft\n * starts without any of them; the registry adds subclass fields at runtime.\n */\nconst DRAFT_RESET_FIELDS = [\n 'accountId',\n 'personaId',\n 'endpointId',\n 'correlationId',\n 'threadId',\n 'subject',\n 'body',\n 'fromAddress',\n 'fromName',\n 'toAddresses',\n 'date',\n 'isRead',\n 'isFlagged',\n 'hasAttachments',\n 'size',\n 'metadata',\n 'sendStatus',\n 'sentAt',\n 'sendError',\n 'retryCount',\n 'maxRetries',\n 'scheduledSendAt',\n 'inReplyToMessageId',\n 'handledById',\n 'handledByKind',\n 'handledAt',\n 'createdAt',\n 'updatedAt',\n 'messageId',\n 'inReplyTo',\n 'providerMessageId',\n 'ccAddresses',\n 'bccAddresses',\n 'replyToAddress',\n 'replyToName',\n 'textBody',\n 'htmlBody',\n 'folderId',\n 'folderPath',\n 'labels',\n 'flags',\n 'isAnswered',\n 'isDraft',\n 'rawMessage',\n 'headers',\n];\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class Message extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n @foreignKey('Account')\n @field({\n description: 'The connected account used to receive or send this message.',\n })\n accountId = '';\n @crossPackageRef('@happyvertical/smrt-personas:AgentPersona', {\n nullable: true,\n })\n @field({\n description:\n 'The assistant identity associated with this message, when one was used.',\n })\n personaId: string | null = null;\n @foreignKey('MessagingEndpoint')\n @field({ description: 'The saved destination used to deliver this message.' })\n endpointId: string | null = null;\n @field({\n description:\n 'A tracking reference that connects this message to related activity.',\n })\n correlationId = '';\n @field({ description: 'The conversation this message belongs to.' })\n threadId = '';\n @field({ description: 'The subject shown in the message list.' })\n subject = '';\n @field({ description: 'The message content in plain text.' })\n body = ''; // Normalized plain text\n @field({ description: 'The address the message was sent from.' })\n fromAddress = '';\n @field({ description: 'The sender name shown beside their address.' })\n fromName = '';\n @field({ description: 'The people or addresses receiving this message.' })\n toAddresses = ''; // JSON array of {address, name}\n @field({ description: 'When the message was sent or received.' })\n date: Date | null = null;\n @field({ description: 'Whether this message has been marked as read.' })\n isRead = false;\n @field({ description: 'Whether this message is flagged for follow-up.' })\n isFlagged = false;\n @field({ description: 'Whether files are attached to this message.' })\n hasAttachments = false;\n @field({ description: 'The size of the message in bytes.' })\n size = 0;\n @field({\n description: 'Additional details supplied by the messaging connection.',\n })\n metadata = ''; // JSON extension bag\n\n // Send lifecycle fields\n @field({\n description:\n 'The latest sending state: draft, sending, sent, or failed. Received mail may also show draft here.',\n })\n sendStatus: SendStatus = 'draft';\n @field({ description: 'When the message was successfully sent.' })\n sentAt: Date | null = null;\n @field({ description: 'The reason the latest send attempt failed.' })\n sendError = '';\n @field({ description: 'How many times delivery has been retried.' })\n retryCount = 0;\n @field({ description: 'The maximum number of delivery retries allowed.' })\n maxRetries = 3;\n @field({ description: 'When this message is scheduled to be sent.' })\n scheduledSendAt: Date | null = null;\n @foreignKey('Message')\n @field({ description: 'The earlier message this one replies to.' })\n inReplyToMessageId = '';\n\n // Who handled this message last (a person or an agent), recorded from the\n // host-supplied acting principal by triage, drafting and sending.\n @field({\n readonly: true,\n description: 'The person or assistant who last acted on this message.',\n })\n handledById: string | null = null;\n @field({\n readonly: true,\n description: 'Whether a person or an assistant last acted on this message.',\n })\n handledByKind: string | null = null;\n @field({\n readonly: true,\n description: 'When someone last acted on this message.',\n })\n handledAt: Date | null = null;\n\n // Timestamps\n @field({ description: 'When this message was recorded.' })\n createdAt = new Date();\n @field({ description: 'When this message was last changed.' })\n updatedAt = new Date();\n\n constructor(options: MessageOptions = {}) {\n super(options);\n\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.accountId !== undefined) this.accountId = options.accountId;\n if (options.personaId !== undefined) this.personaId = options.personaId;\n if (options.endpointId !== undefined) this.endpointId = options.endpointId;\n if (options.correlationId !== undefined)\n this.correlationId = options.correlationId;\n if (options.threadId !== undefined) this.threadId = options.threadId;\n if (options.subject !== undefined) this.subject = options.subject;\n if (options.body !== undefined) this.body = options.body;\n if (options.fromAddress !== undefined)\n this.fromAddress = options.fromAddress;\n if (options.fromName !== undefined) this.fromName = options.fromName;\n if (options.toAddresses !== undefined)\n this.toAddresses = options.toAddresses;\n if (options.date !== undefined) this.date = options.date || null;\n if (options.isRead !== undefined) this.isRead = options.isRead;\n if (options.isFlagged !== undefined) this.isFlagged = options.isFlagged;\n if (options.hasAttachments !== undefined)\n this.hasAttachments = options.hasAttachments;\n if (options.size !== undefined) this.size = options.size;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n if (options.sendStatus !== undefined) this.sendStatus = options.sendStatus;\n if (options.sentAt !== undefined) this.sentAt = options.sentAt || null;\n if (options.sendError !== undefined) this.sendError = options.sendError;\n if (options.retryCount !== undefined) this.retryCount = options.retryCount;\n if (options.maxRetries !== undefined) this.maxRetries = options.maxRetries;\n if (options.scheduledSendAt !== undefined)\n this.scheduledSendAt = options.scheduledSendAt || null;\n if (options.inReplyToMessageId !== undefined)\n this.inReplyToMessageId = options.inReplyToMessageId;\n if (options.handledById !== undefined)\n this.handledById = options.handledById;\n if (options.handledByKind !== undefined)\n this.handledByKind = options.handledByKind;\n if (options.handledAt !== undefined)\n this.handledAt = options.handledAt || null;\n if (options.createdAt) this.createdAt = options.createdAt;\n if (options.updatedAt) this.updatedAt = options.updatedAt;\n rememberNotificationOrigin(this);\n }\n\n /** Ordinary saves preserve protected outbox provenance and approved content. */\n override async save(options?: SmrtSaveOptions): Promise<this> {\n const signature = lifecycleSaves.get(this);\n lifecycleSaves.delete(this);\n const authorized =\n signature !== undefined && signature === lifecycleSignature(this);\n const lifecycle = authorized || heldSaves.has(this);\n const required = await this.enforceDraftScope(lifecycle);\n return this.withTransaction(async () => {\n // The decision above used the stored row as it was then; inside the\n // write, the row this save replaces must still need nothing more.\n await this.assertDraftScopeStillHolds(lifecycle, required);\n await assertProtectedNotificationSave(this, options, authorized);\n if (signature !== undefined && signature !== lifecycleSignature(this))\n throw new Error('Message lifecycle changed during its guarded save.');\n const result = await super.save(options);\n // Core may adopt a natural-key row that appeared during save. Verify\n // its resulting durable identity before this transaction can commit.\n await assertProtectedNotificationSave(this, options, authorized);\n if (signature !== undefined && signature !== lifecycleSignature(this))\n throw new Error('Message lifecycle changed during its guarded save.');\n rememberNotificationOrigin(this);\n return result;\n });\n }\n\n /** Protected outbound evidence is retained; ordinary message deletion remains unchanged. */\n override async delete(\n options: { expectedUpdatedAt?: Date | string } = {},\n ): Promise<void> {\n const required = await this.enforceDraftScope(false);\n return this.withTransaction(async () => {\n await this.assertDraftScopeStillHolds(false, required);\n await assertProtectedNotificationDelete(this);\n return super.delete(options);\n });\n }\n\n /**\n * Creating, changing or deleting a draft on an owned account needs the\n * `draft` scope, whichever route the write takes. A draft is an email\n * flagged `isDraft` that has not been sent (any send status but `sent`), in\n * whatever form the flag is stored; received mail is not flagged. The stored\n * row decides, whatever class this instance is, so a base `Message` handle\n * on a stored draft is covered. Both the new and the stored state count, so\n * a draft cannot be edited by first relabelling it, and both accounts count\n * when a draft moves. Trusted system work, unowned accounts and rows that\n * are not drafts are unaffected.\n *\n * `lifecycle` is the send path's own save (status changes, a held send moved\n * back to draft): it needs the `send` scope instead, and passes only while\n * every field outside {@link SEND_PATH_MAY_CHANGE} still equals the stored\n * row, so it cannot carry an edit. A row the send path itself creates (an\n * unsaved message being sent) needs `send` too.\n *\n * Returns the requirements it enforced (empty for system work).\n */\n private async enforceDraftScope(lifecycle: boolean): Promise<Set<string>> {\n if (inMailSystemAccess()) return new Set();\n const rootOptions = { ...this.options } as SmrtClassOptions;\n learnMailAccessOptions(rootOptions);\n const required = await this.draftScopeRequirements(lifecycle);\n for (const key of required) {\n const at = key.indexOf(':');\n await assertMailScopeOn(\n [key.slice(at + 1)],\n key.slice(0, at) as MailScope,\n rootOptions,\n );\n }\n return required;\n }\n\n /**\n * The same decision re-read inside the write transaction. The policy lookups\n * (grants, account owner) use the configured database handle, which a\n * single-connection engine cannot serve while a transaction is open, so they\n * stay outside; what the write re-checks is the stored row. A row that now\n * needs more than was enforced is refused, and the caller retries.\n */\n private async assertDraftScopeStillHolds(\n lifecycle: boolean,\n enforced: Set<string>,\n ): Promise<void> {\n if (inMailSystemAccess()) return;\n for (const key of await this.draftScopeRequirements(lifecycle)) {\n if (!enforced.has(key)) {\n throw new MailAccessError(\n key.slice(0, key.indexOf(':')) as MailScope,\n 'denied',\n );\n }\n }\n }\n\n /** The `scope:accountId` pairs this write needs, read through `this.db`. */\n private async draftScopeRequirements(\n lifecycle: boolean,\n ): Promise<Set<string>> {\n const needed = new Set<string>();\n const row = this as unknown as Record<string, unknown>;\n const draftNow =\n 'isDraft' in this && isUnsentDraft(row.sendStatus, row.isDraft);\n const priorAccountIds: string[] = [];\n let stored: Record<string, unknown> | null = null;\n let unchanged = false;\n if (this.id) {\n stored = await this.getCanonicalPersistedRow({ id: this.id });\n if (stored) {\n if (isUnsentDraft(stored.send_status, stored.is_draft)) {\n priorAccountIds.push(String(stored.account_id ?? ''));\n }\n unchanged = this.matchesStoredBeyondSendPath(stored);\n }\n }\n // A new object is written over the stored row that carries its natural\n // key (the slug it has, or the one the save derives from its id), whatever\n // its own id: that row, not the id, is what the save changes.\n let takesOver = false;\n if (!this.isPersisted) {\n const columns = ObjectRegistry.getConflictColumns(\n this.getResolvedQualifiedName(),\n );\n if (columns.includes('slug')) {\n const slug =\n typeof row.slug === 'string' && row.slug\n ? row.slug\n : await this.getSlug();\n if (typeof slug === 'string' && slug) {\n // Match on the slug alone: the tenant is filled in during the save,\n // after this check, so any narrower filter could miss the row the\n // save takes over. It can only over-match, which means an extra\n // check.\n for (const keyed of await this.getCanonicalPersistedRows({ slug })) {\n if (keyed.id === this.id) continue;\n takesOver = true;\n unchanged = false;\n if (isUnsentDraft(keyed.send_status, keyed.is_draft)) {\n priorAccountIds.push(String(keyed.account_id ?? ''));\n }\n }\n }\n }\n }\n if (!draftNow && !priorAccountIds.length) return needed;\n const scope: MailScope =\n lifecycle && ((stored && unchanged) || (!stored && !takesOver))\n ? 'send'\n : 'draft';\n for (const id of [draftNow ? this.accountId : '', ...priorAccountIds]) {\n if (id) needed.add(`${scope}:${id}`);\n }\n return needed;\n }\n\n /** Whether every field outside {@link SEND_PATH_MAY_CHANGE} equals `stored`. */\n private matchesStoredBeyondSendPath(\n stored: Record<string, unknown>,\n ): boolean {\n const row = this as unknown as Record<string, unknown>;\n const names = new Set([\n ...this.draftFieldNames(),\n 'tenantId',\n 'slug',\n 'context',\n ]);\n for (const name of names) {\n if (SEND_PATH_MAY_CHANGE.has(name)) continue;\n const column = name.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);\n // A property with no column cannot be stored, so it cannot carry an edit.\n if (!(column in stored)) continue;\n const mine = row[name];\n const same =\n typeof mine === 'boolean'\n ? mine === mailFlag(stored[column])\n : canonValue(mine) === canonValue(stored[column]);\n if (!same) return false;\n }\n return true;\n }\n\n private async finalizeSendLifecycle(\n result: MessageSendResult,\n actor: MailPrincipal | null = null,\n ): Promise<void> {\n if (!this.id) throw new Error('Cannot finalize an unsaved message send');\n\n const sendStatus: SendStatus = result.success ? 'sent' : 'failed';\n const sendError = result.success ? '' : (result.error ?? 'Send failed');\n const useEmbeddedFallback = usesEmbeddedRevisionFallback(this.db);\n for (let attempt = 0; attempt < 8; attempt += 1) {\n let nextRevision: Date | undefined;\n await withEmbeddedWriteQueue(this.db, useEmbeddedFallback, async () => {\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n if (current?.send_status !== 'sending') return;\n const currentRevision = current.updated_at;\n const currentRevisionMs = new Date(String(currentRevision)).getTime();\n if (!Number.isFinite(currentRevisionMs)) return;\n nextRevision = new Date(Math.max(Date.now(), currentRevisionMs + 1));\n // Record durably whether a failure may still have been accepted, so a\n // later reconciliation can tell it from a definite rejection.\n const metadata = withSendOutcomeMarker(\n current.metadata,\n !result.success && result.outcomeUnknown === true,\n );\n if (actor) stampHandledBy(this, actor, nextRevision);\n const values = {\n send_status: sendStatus,\n sent_at: result.success ? result.sentAt : null,\n send_error: sendError,\n updated_at: nextRevision,\n ...(metadata === undefined ? {} : { metadata }),\n ...(actor\n ? {\n handled_by_id: this.handledById,\n handled_by_kind: this.handledByKind,\n handled_at: this.handledAt,\n }\n : {}),\n };\n if (useEmbeddedFallback) {\n await this.db.upsert(this.tableName, ['id'], {\n ...current,\n ...values,\n });\n return;\n }\n await this.db.update(\n this.tableName,\n {\n id: this.id,\n send_status: 'sending',\n updated_at:\n currentRevision instanceof Date\n ? currentRevision.toISOString()\n : currentRevision,\n },\n values,\n );\n });\n // DuckDB's generic update result reports one affected row even when the\n // predicate matched none. Verify the durable lifecycle value instead of\n // trusting adapter row-count metadata before declaring finalization.\n const verified = await this.getCanonicalPersistedRow({ id: this.id });\n if (verified?.send_status === sendStatus) {\n await this.completePersistedUpdate(verified);\n return;\n }\n }\n throw new Error('Cannot finalize: message revision kept changing');\n }\n\n /**\n * Get to addresses as parsed array\n */\n getToAddresses(): Array<{ address: string; name?: string }> {\n if (!this.toAddresses) return [];\n try {\n return JSON.parse(this.toAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Set to addresses from array\n */\n setToAddresses(addresses: Array<{ address: string; name?: string }>): void {\n this.toAddresses = JSON.stringify(addresses);\n }\n\n /**\n * Get metadata as parsed object\n */\n getMetadata(): Record<string, unknown> {\n if (!this.metadata) return {};\n try {\n return JSON.parse(this.metadata);\n } catch {\n return {};\n }\n }\n\n /**\n * Set metadata from object\n */\n setMetadata(data: Record<string, unknown>): void {\n this.metadata = JSON.stringify(data);\n }\n\n /**\n * Mark message as read\n */\n async markRead(): Promise<void> {\n this.isRead = true;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Mark message as unread\n */\n async markUnread(): Promise<void> {\n this.isRead = false;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Toggle flagged status\n */\n async toggleFlagged(): Promise<void> {\n this.isFlagged = !this.isFlagged;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Check if message is unread\n */\n isUnread(): boolean {\n return !this.isRead;\n }\n\n /**\n * Get a short preview of the message body\n */\n getPreview(maxLength = 200): string {\n const text = this.body || '';\n if (text.length <= maxLength) return text;\n return `${text.slice(0, maxLength)}...`;\n }\n\n /**\n * Direct hydration (`new X({ id }).initialize()`, `loadRelated()`) bypasses\n * the collection read hooks, so the per-account mail policy is applied here\n * too: a row of an account closed to the principal never hydrates.\n */\n override async loadFromId() {\n await super.loadFromId();\n await assertHydratedMailAccess({\n accountId: this.accountId,\n options: this.options,\n });\n }\n\n override async loadFromSlug() {\n await super.loadFromSlug();\n await assertHydratedMailAccess({\n accountId: this.accountId,\n options: this.options,\n });\n }\n\n /**\n * Get the account for this message\n */\n async getAccount() {\n if (!this.accountId) return null;\n\n const { AccountCollection } = await import(\n '../collections/AccountCollection'\n );\n const collection = await AccountCollection.create(this.options);\n\n return await collection.get({ id: this.accountId });\n }\n\n async getEndpoint() {\n if (!this.endpointId) return null;\n const { MessagingEndpointCollection } = await import(\n '../collections/MessagingEndpointCollection.js'\n );\n const collection = await MessagingEndpointCollection.create(this.options);\n return collection.get({ id: this.endpointId });\n }\n\n /**\n * Get messages in the same thread\n */\n async getThreadMessages(): Promise<Message[]> {\n if (!this.threadId) return [this];\n\n const { MessageCollection } = await import(\n '../collections/MessageCollection'\n );\n const collection = await MessageCollection.create(this.options);\n\n return await collection.list({ where: { threadId: this.threadId } });\n }\n\n /**\n * Get attachments for this message\n */\n async getAttachments() {\n const { AttachmentCollection } = await import(\n '../collections/AttachmentCollection'\n );\n const collection = await AttachmentCollection.create(this.options);\n\n return await collection.list({ where: { messageId: this.id } });\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Send Lifecycle\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Send this message via its account's sender\n */\n async send(options?: SendMessageOptions): Promise<MessageSendResult> {\n try {\n await beginProtectedNotificationSend(this, options);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n sentAt: new Date(),\n };\n }\n // Entry guard: a message that is already in flight or delivered must not be\n // sent again. Catches same-instance double-clicks before any work happens.\n if (this.sendStatus === 'sending' || this.sendStatus === 'sent') {\n return {\n success: false,\n error: `Cannot send: message is already '${this.sendStatus}'`,\n sentAt: new Date(),\n };\n }\n\n // Resolve account\n const account = await this.getAccount();\n if (!account) {\n const result: MessageSendResult = {\n success: false,\n error: 'No account associated with this message',\n sentAt: new Date(),\n };\n this.sendStatus = 'failed';\n this.sendError = result.error ?? '';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n return result;\n }\n\n if (!account.isActive) {\n const result: MessageSendResult = {\n success: false,\n error: 'Messaging account is inactive',\n sentAt: new Date(),\n };\n this.sendStatus = 'failed';\n this.sendError = result.error ?? '';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n return result;\n }\n\n // Owned accounts need the `send` scope. A denial leaves the message as it\n // was: a refused principal must not mark someone else's draft failed.\n const access = await decideMailAccess(account, 'send');\n if (!access.allowed) {\n return {\n success: false,\n error: 'Mail access denied for scope send',\n sentAt: new Date(),\n };\n }\n\n // The acting principal (host-supplied). Trusted system work (sync, the\n // notification outbox) has none and is never held or stamped.\n const actor = inMailSystemAccess() ? null : await resolveMailPrincipal();\n\n // Send-as: from any mail account, everything but trusted system work\n // sends only from the account's own address. Sending as anyone else needs\n // a delegation grant, which does not exist yet, so it is refused.\n if (!inMailSystemAccess() && 'email' in account) {\n const from = (this.fromAddress || '').trim().toLowerCase();\n const own = String((account as { email?: unknown }).email ?? '')\n .trim()\n .toLowerCase();\n if (from && from !== own) {\n return {\n success: false,\n error: \"Mail can only be sent from the account's own address.\",\n sentAt: new Date(),\n };\n }\n }\n\n // Agents follow the account's send policy: by default the draft is held\n // for a person's approval and nothing leaves (smrt#5141).\n // Trusted system work is not held, except a persona (agent) message: a\n // system drain must never send an agent's message around its approval.\n const held =\n inMailSystemAccess() && !this.personaId\n ? null\n : await holdAgentSend(this, account, options, actor);\n if (held) {\n // A held message is a draft: out of any pending/scheduled outbox, and\n // decidable by a person. Content is untouched, so the binding holds.\n const toDraft =\n held.pendingApproval !== undefined && this.sendStatus !== 'draft';\n if (toDraft) this.sendStatus = 'draft';\n if (held.pendingApproval?.created) stampHandledBy(this, actor);\n if (toDraft || held.pendingApproval?.created) await saveHeld(this);\n // A refused send of a queued message fails definitely (nothing left),\n // so it does not linger as `pending` for a later drain.\n if (\n held.pendingApproval === undefined &&\n (this.sendStatus === 'pending' || this.sendStatus === 'scheduled') &&\n this.isPersisted\n ) {\n this.sendStatus = 'failed';\n this.sendError = held.error ?? 'Send refused';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n }\n return held;\n }\n // Audited before anything is claimed: an audit failure sends nothing.\n if (actor) await auditMailAction('messages.send', this);\n\n // Get sender from account\n let sender: Awaited<ReturnType<typeof account.createSender>>;\n try {\n sender = await account.createSender();\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n this.sendStatus = 'failed';\n this.sendError = errorMessage;\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n return {\n success: false,\n error: errorMessage,\n sentAt: new Date(),\n };\n }\n\n // Claim the send. For a persisted row, do a compare-and-set so only one\n // concurrent sender wins: flip send_status to 'sending' atomically, gated on\n // the status we observed. If no row matched, another sender already claimed\n // it — abort without delivering (prevents duplicate sends). For an unsaved\n // draft there is no row yet, so the in-memory transition + save() (INSERT)\n // serves as the claim.\n const claimFromStatus = this.sendStatus;\n if (this.isPersisted && this.id) {\n const loadedRevision = this.updated_at;\n if (!loadedRevision) {\n return {\n success: false,\n error: 'Cannot send: persisted message has no loaded revision',\n sentAt: new Date(),\n };\n }\n const claimedRevision = new Date(\n Math.max(Date.now(), loadedRevision.getTime() + 1),\n );\n const useEmbeddedFallback = usesEmbeddedRevisionFallback(this.db);\n let claimed = false;\n await withEmbeddedWriteQueue(this.db, useEmbeddedFallback, async () => {\n if (useEmbeddedFallback) {\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n const storedRevision = current?.updated_at;\n const currentRevision =\n storedRevision instanceof Date\n ? storedRevision.getTime()\n : typeof storedRevision === 'string'\n ? Date.parse(storedRevision)\n : Number.NaN;\n if (\n !current ||\n current.send_status !== claimFromStatus ||\n !Number.isFinite(currentRevision) ||\n currentRevision !== loadedRevision.getTime()\n )\n return;\n await this.db.upsert(this.tableName, ['id'], {\n ...current,\n send_status: 'sending',\n updated_at: claimedRevision,\n });\n claimed = true;\n return;\n }\n const claim = await this.db.update(\n this.tableName,\n {\n id: this.id,\n send_status: claimFromStatus,\n updated_at: loadedRevision.toISOString(),\n },\n { send_status: 'sending', updated_at: claimedRevision },\n );\n claimed = claim?.affected === 1;\n });\n if (!claimed) {\n return {\n success: false,\n error: 'Cannot send: message is already being sent',\n sentAt: new Date(),\n };\n }\n this.sendStatus = 'sending';\n this.updated_at = claimedRevision;\n this.updatedAt = new Date();\n } else {\n this.sendStatus = 'sending';\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n }\n\n // A send an approval released must still be the approved draft now that\n // the row is claimed (attachment rows are not covered by the claim).\n if (await approvedDraftChanged(this)) {\n const changed: MessageSendResult = {\n success: false,\n error: 'The draft changed after it was approved; nothing was sent.',\n sentAt: new Date(),\n };\n await this.finalizeSendLifecycle(changed, actor);\n return changed;\n }\n\n let result: MessageSendResult;\n try {\n await assertProtectedSenderHandoff(this, options);\n result = await sender.send(this, options);\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n // A sender that throws mid-send says nothing about provider acceptance.\n result = {\n success: false,\n error: errorMessage,\n ...(error instanceof ProtectedNotificationHandoffError\n ? {}\n : { outcomeUnknown: true }),\n sentAt: new Date(),\n };\n }\n await this.finalizeSendLifecycle(result, actor);\n return result;\n }\n\n /** Who last acted on this message, or null. */\n getHandledBy(): { id: string; kind: string; at: Date | null } | null {\n if (!this.handledById) return null;\n return {\n id: this.handledById,\n kind: this.handledByKind || 'agent',\n at: this.handledAt,\n };\n }\n\n /**\n * Whether the latest failed send may still have been accepted by the\n * provider (see `MessageSendResult.outcomeUnknown`).\n */\n isSendOutcomeUnknown(): boolean {\n return (\n this.sendStatus === 'failed' &&\n this.getMetadata()[SEND_OUTCOME_UNKNOWN_METADATA_KEY] === true\n );\n }\n\n /**\n * Release a send claim whose sender is gone (a crash or lost lease left the\n * row in `sending`): move it to `failed` with an unknown outcome so the\n * owner of the delivery decision can send it again. Returns false, changing\n * nothing, unless the stored row is still `sending`. Only for callers that\n * have established that no live sender holds the claim.\n */\n async abandonSendAttempt(reason: string): Promise<boolean> {\n if (!this.id) return false;\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n if (current?.send_status !== 'sending') return false;\n try {\n await this.finalizeSendLifecycle({\n success: false,\n error: reason,\n outcomeUnknown: true,\n sentAt: new Date(),\n });\n } catch {\n return false;\n }\n return this.sendStatus === 'failed';\n }\n\n /**\n * Retry sending a failed message\n */\n async retrySend(options?: SendMessageOptions): Promise<MessageSendResult> {\n try {\n await assertProtectedNotificationRetry(this, options);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n sentAt: new Date(),\n };\n }\n if (this.sendStatus !== 'failed') {\n return {\n success: false,\n error: `Cannot retry: message status is '${this.sendStatus}', expected 'failed'`,\n sentAt: new Date(),\n };\n }\n\n if (this.retryCount >= this.maxRetries) {\n return {\n success: false,\n error: `Retry budget exhausted (${this.retryCount}/${this.maxRetries})`,\n sentAt: new Date(),\n };\n }\n\n this.retryCount++;\n this.updatedAt = new Date();\n await saveSendLifecycle(this);\n\n return this.send(options);\n }\n\n /**\n * Options for a derived draft (reply/forward) built from this message. Carries\n * the DB connection + tenant context from `this.options`, but strips this\n * message's own identity fields. When this message was hydrated from the DB,\n * `this.options` holds the row's `id`/`slug`/`context`/`_skipLoad`; spreading\n * those into a new draft would make `draft.save()` upsert onto the natural-key\n * conflict columns (`slug`/`context`/`_meta_type`) and overwrite the ORIGINAL\n * message instead of inserting a new row. See EmailAccount.childOptions().\n */\n protected draftOptions(): Record<string, unknown> {\n const rest = { ...(this.options as Record<string, unknown>) };\n delete rest.id;\n delete rest.slug;\n delete rest.context;\n delete rest._skipLoad;\n // `this.options` of a hydrated row carries every stored column. A derived\n // draft must not inherit any of them (htmlBody, bcc, messageId, headers,\n // send state, handled-by, ...); createReply/createForward then set back\n // only what reply/forward semantics define. Only connection and tenant\n // context survive.\n // `personaId` is dropped on purpose: a reply is authored by the replying\n // principal, so it falls under that principal's hold rules, not the\n // persona the inbound message happened to be addressed through.\n // `metadata` and `correlationId` stay: the protected-notification\n // handoff keys its provenance on them, so a derived draft of a protected\n // notification must keep failing closed. Neither is sent as mail content.\n for (const name of this.draftFieldNames()) {\n if (!DRAFT_CARRIED_FIELDS.has(name)) delete rest[name];\n }\n return rest;\n }\n\n /** Every stored field name of this message's class, including subclasses. */\n private draftFieldNames(): string[] {\n const names = new Set<string>(DRAFT_RESET_FIELDS);\n try {\n for (const key of ObjectRegistry.getFields(\n this.getResolvedQualifiedName(),\n ).keys()) {\n names.add(key);\n }\n } catch {\n // The static list above still covers every field this package declares.\n }\n return [...names];\n }\n\n /**\n * Create a reply to this message (returns unsaved draft)\n */\n createReply(_options?: { replyAll?: boolean }): Message {\n const reply = new (this.constructor as typeof Message)({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: this.threadId || this.id || '',\n subject: this.subject.startsWith('Re:')\n ? this.subject\n : `Re: ${this.subject}`,\n toAddresses: JSON.stringify([\n { address: this.fromAddress, name: this.fromName },\n ]),\n fromAddress: '',\n fromName: '',\n body: this.buildQuotedBody(),\n inReplyToMessageId: this.id || '',\n sendStatus: 'draft',\n isRead: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n });\n\n return reply;\n }\n\n /**\n * Create a forward of this message (returns unsaved draft)\n */\n createForward(): Message {\n const forward = new (this.constructor as typeof Message)({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: '',\n subject: this.subject.startsWith('Fwd:')\n ? this.subject\n : `Fwd: ${this.subject}`,\n toAddresses: '[]',\n fromAddress: '',\n fromName: '',\n body: this.buildQuotedBody(),\n // Attachment rows are not copied, so the draft has none.\n hasAttachments: false,\n inReplyToMessageId: '',\n sendStatus: 'draft',\n isRead: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n });\n\n return forward;\n }\n\n /**\n * Build quoted body for reply/forward\n */\n protected buildQuotedBody(): string {\n const dateStr = this.date ? this.date.toLocaleString() : 'unknown date';\n const from = this.fromName\n ? `${this.fromName} <${this.fromAddress}>`\n : this.fromAddress;\n\n const quotedLines = (this.body || '')\n .split('\\n')\n .map((line) => `> ${line}`)\n .join('\\n');\n\n return `\\n\\nOn ${dateStr}, ${from} wrote:\\n${quotedLines}`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4DO,IAAM,oCAAoC;AAMjD,SAAS,sBACP,QACA,gBACoB;CACpB,IAAI,MAA+B,CAAC;CACpC,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,GAC5C,IAAI;EACF,MAAM,SAAkB,KAAK,MAAM,MAAM;EACzC,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,GAC/D;EAEF,MAAM;CACR,QAAQ;EACN;CACF;CAEF,IAAI,QAAQ,IAAA,qBAAsC,MAAM,gBACtD;CAEF,IAAI,gBAAgB,IAAI,qCAAqC;MACxD,OAAO,IAAI;CAChB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