@happyvertical/smrt-messages 0.70.1 → 0.70.3
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 +4 -0
- package/agents/send-approval.md +28 -0
- package/dist/access.d.ts +22 -0
- package/dist/access.d.ts.map +1 -1
- package/dist/chunks/{AttachmentCollection-Cs6dC7vz.js → AttachmentCollection-Di2aRb2k.js} +52 -5
- package/dist/chunks/AttachmentCollection-Di2aRb2k.js.map +1 -0
- package/dist/chunks/{Email-C5PO3e6c.js → Email-tEYH6ZRw.js} +6 -6
- package/dist/chunks/{Email-C5PO3e6c.js.map → Email-tEYH6ZRw.js.map} +1 -1
- package/dist/chunks/{EmailAccountCollection-BJH0rOH2.js → EmailAccountCollection-DWo_a-X5.js} +55 -20
- package/dist/chunks/EmailAccountCollection-DWo_a-X5.js.map +1 -0
- package/dist/chunks/{EmailCollection-3iN8bLk4.js → EmailCollection-_Z2JY26I.js} +3 -3
- package/dist/chunks/{EmailCollection-3iN8bLk4.js.map → EmailCollection-_Z2JY26I.js.map} +1 -1
- package/dist/chunks/{EmailFolder-DR6Rz6n9.js → EmailFolder-TyoFZVcC.js} +6 -6
- package/dist/chunks/{EmailFolder-DR6Rz6n9.js.map → EmailFolder-TyoFZVcC.js.map} +1 -1
- package/dist/chunks/{EmailFolderCollection-BByXjljN.js → EmailFolderCollection-CFtttkx6.js} +2 -2
- package/dist/chunks/{EmailFolderCollection-BByXjljN.js.map → EmailFolderCollection-CFtttkx6.js.map} +1 -1
- package/dist/chunks/{EmailSender-DJ899ng7.js → EmailSender-bHwAYzBO.js} +2 -2
- package/dist/chunks/{EmailSender-DJ899ng7.js.map → EmailSender-bHwAYzBO.js.map} +1 -1
- package/dist/chunks/{Message-DuyeDIeW.js → Message-DC877Gl7.js} +145 -10
- package/dist/chunks/Message-DC877Gl7.js.map +1 -0
- package/dist/chunks/{MessageCollection-CrL6570U.js → MessageCollection-yZ6RyAtB.js} +2 -2
- package/dist/chunks/{MessageCollection-CrL6570U.js.map → MessageCollection-yZ6RyAtB.js.map} +1 -1
- package/dist/chunks/{MessagingEndpointCollection-5jqgi9mo.js → MessagingEndpointCollection-CNwpv_ZW.js} +2 -2
- package/dist/chunks/{MessagingEndpointCollection-5jqgi9mo.js.map → MessagingEndpointCollection-CNwpv_ZW.js.map} +1 -1
- package/dist/connect.js +1 -1
- package/dist/index.js +16 -16
- package/dist/manifest.json +63 -1
- package/dist/models/Attachment.d.ts +20 -1
- package/dist/models/Attachment.d.ts.map +1 -1
- package/dist/models/Message.d.ts +32 -0
- package/dist/models/Message.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +59 -9
- package/dist/smrt-knowledge.okf.md +2 -2
- package/package.json +12 -12
- package/dist/chunks/AttachmentCollection-Cs6dC7vz.js.map +0 -1
- package/dist/chunks/EmailAccountCollection-BJH0rOH2.js.map +0 -1
- package/dist/chunks/Message-DuyeDIeW.js.map +0 -1
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.70.
|
|
6
|
+
"packageVersion": "0.70.3",
|
|
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": "a751e45dc7e1de93f144dd2bfbc319cbf97402b8380bd8ced5c8f9b13cd50447",
|
|
11
|
+
"packageJson": "fc9de03a0900ef0c99e79c824591413186940b93686465c0a4917bff63361f92",
|
|
12
|
+
"agents": "ace12c9bfe2b42588489292b7967e597d9bed8dc6784f61fce7f41ea80b047e7",
|
|
13
|
+
"moduleDoc:agents/send-approval.md": "a54a3daaf091c9c77e9a1fc6c3dbf04d15403d915ab08833c2ebf57ee1b74ec3",
|
|
14
14
|
"moduleDoc:agents/mail-search.md": "9dac1619a1486f2fa94980e141ebc5003851c27cd77ced6d5ff64d348429fdb1",
|
|
15
15
|
"moduleDoc:agents/notification-outbox.md": "0e9a870c4b2d5f0fec47af0dff6e61d216fb0121d384d99bccfc506beb6e38ad",
|
|
16
16
|
"moduleDoc:agents/profile-recipients.md": "1b6710bf646ddeafd6836df8270fcbb8e29226dceda716a693d945cc2e914606"
|
|
@@ -3543,6 +3543,7 @@
|
|
|
3543
3543
|
}
|
|
3544
3544
|
],
|
|
3545
3545
|
"methods": [
|
|
3546
|
+
"delete",
|
|
3546
3547
|
"getExtension",
|
|
3547
3548
|
"getFormattedSize",
|
|
3548
3549
|
"getMessage",
|
|
@@ -3552,9 +3553,18 @@
|
|
|
3552
3553
|
"isPdf",
|
|
3553
3554
|
"loadFromId",
|
|
3554
3555
|
"loadFromSlug",
|
|
3555
|
-
"readContent"
|
|
3556
|
+
"readContent",
|
|
3557
|
+
"save"
|
|
3556
3558
|
],
|
|
3557
3559
|
"methodSignatures": [
|
|
3560
|
+
{
|
|
3561
|
+
"name": "delete",
|
|
3562
|
+
"async": true,
|
|
3563
|
+
"params": [
|
|
3564
|
+
"options?: object"
|
|
3565
|
+
],
|
|
3566
|
+
"returns": "Promise<void>"
|
|
3567
|
+
},
|
|
3558
3568
|
{
|
|
3559
3569
|
"name": "getExtension",
|
|
3560
3570
|
"returns": "string"
|
|
@@ -3598,6 +3608,14 @@
|
|
|
3598
3608
|
"name": "readContent",
|
|
3599
3609
|
"async": true,
|
|
3600
3610
|
"returns": "Promise<Buffer | null>"
|
|
3611
|
+
},
|
|
3612
|
+
{
|
|
3613
|
+
"name": "save",
|
|
3614
|
+
"async": true,
|
|
3615
|
+
"params": [
|
|
3616
|
+
"options?: SmrtSaveOptions"
|
|
3617
|
+
],
|
|
3618
|
+
"returns": "Promise<this>"
|
|
3601
3619
|
}
|
|
3602
3620
|
],
|
|
3603
3621
|
"tenant": {
|
|
@@ -3804,6 +3822,13 @@
|
|
|
3804
3822
|
"code": "not-included",
|
|
3805
3823
|
"reason": "not listed in api.include",
|
|
3806
3824
|
"objectName": "@happyvertical/smrt-messages:Attachment"
|
|
3825
|
+
},
|
|
3826
|
+
{
|
|
3827
|
+
"kind": "api",
|
|
3828
|
+
"operation": "save",
|
|
3829
|
+
"code": "lifecycle-method",
|
|
3830
|
+
"reason": "`save` is a framework lifecycle method, not a distinct operation",
|
|
3831
|
+
"objectName": "@happyvertical/smrt-messages:Attachment"
|
|
3807
3832
|
}
|
|
3808
3833
|
],
|
|
3809
3834
|
"relationshipFeatures": [
|
|
@@ -5963,6 +5988,7 @@
|
|
|
5963
5988
|
}
|
|
5964
5989
|
],
|
|
5965
5990
|
"methods": [
|
|
5991
|
+
"delete",
|
|
5966
5992
|
"getEmail",
|
|
5967
5993
|
"getExtension",
|
|
5968
5994
|
"getFormattedSize",
|
|
@@ -5973,9 +5999,18 @@
|
|
|
5973
5999
|
"isPdf",
|
|
5974
6000
|
"loadFromId",
|
|
5975
6001
|
"loadFromSlug",
|
|
5976
|
-
"readContent"
|
|
6002
|
+
"readContent",
|
|
6003
|
+
"save"
|
|
5977
6004
|
],
|
|
5978
6005
|
"methodSignatures": [
|
|
6006
|
+
{
|
|
6007
|
+
"name": "delete",
|
|
6008
|
+
"async": true,
|
|
6009
|
+
"params": [
|
|
6010
|
+
"options?: object"
|
|
6011
|
+
],
|
|
6012
|
+
"returns": "Promise<void>"
|
|
6013
|
+
},
|
|
5979
6014
|
{
|
|
5980
6015
|
"name": "getEmail",
|
|
5981
6016
|
"async": true,
|
|
@@ -6024,6 +6059,14 @@
|
|
|
6024
6059
|
"name": "readContent",
|
|
6025
6060
|
"async": true,
|
|
6026
6061
|
"returns": "Promise<Buffer | null>"
|
|
6062
|
+
},
|
|
6063
|
+
{
|
|
6064
|
+
"name": "save",
|
|
6065
|
+
"async": true,
|
|
6066
|
+
"params": [
|
|
6067
|
+
"options?: SmrtSaveOptions"
|
|
6068
|
+
],
|
|
6069
|
+
"returns": "Promise<this>"
|
|
6027
6070
|
}
|
|
6028
6071
|
],
|
|
6029
6072
|
"conflictColumns": [
|
|
@@ -6238,6 +6281,13 @@
|
|
|
6238
6281
|
"code": "not-included",
|
|
6239
6282
|
"reason": "not listed in api.include",
|
|
6240
6283
|
"objectName": "@happyvertical/smrt-messages:EmailAttachment"
|
|
6284
|
+
},
|
|
6285
|
+
{
|
|
6286
|
+
"kind": "api",
|
|
6287
|
+
"operation": "save",
|
|
6288
|
+
"code": "lifecycle-method",
|
|
6289
|
+
"reason": "`save` is a framework lifecycle method, not a distinct operation",
|
|
6290
|
+
"objectName": "@happyvertical/smrt-messages:EmailAttachment"
|
|
6241
6291
|
}
|
|
6242
6292
|
],
|
|
6243
6293
|
"relationshipFeatures": [
|
|
@@ -14230,12 +14280,12 @@
|
|
|
14230
14280
|
"polymorphicAssociations": 0,
|
|
14231
14281
|
"uuidColumns": 138
|
|
14232
14282
|
},
|
|
14233
|
-
"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- `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## 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()` loads `@happyvertical/files` through core's\n `importOptionalDependency` boundary and keeps its null-on-failure contract\n in builds where the SDK is absent.\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",
|
|
14283
|
+
"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## 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()` loads `@happyvertical/files` through core's\n `importOptionalDependency` boundary and keeps its null-on-failure contract\n in builds where the SDK is absent.\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",
|
|
14234
14284
|
"moduleDocs": [
|
|
14235
14285
|
{
|
|
14236
14286
|
"path": "agents/send-approval.md",
|
|
14237
14287
|
"module": "send-approval",
|
|
14238
|
-
"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"
|
|
14288
|
+
"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 an email that is draft\ncontent now or was when stored, by id or by the slug a new object would take\nover (its own or the one derived from its id), and for both accounts when a\ndraft moves. Draft content is an email flagged `isDraft` (any stored form:\n`true`, `1`, `'1'`, `'true'`) whose `sendStatus` is not `sent`, so `failed`,\n`pending`, `scheduled` and `sending` rows are covered too. The stored row\ndecides, whatever class the handle is. Received mail is not flagged. 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 draft content on an owned account; that\ncheck runs 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. As for read, triage and send, a principal's scope and account\nceilings apply to unowned accounts too; with no principal an owned account is\nclosed and an unowned one is open.\n"
|
|
14239
14289
|
},
|
|
14240
14290
|
{
|
|
14241
14291
|
"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-24T09:42:36Z"
|
|
9
9
|
audience: "internal"
|
|
10
10
|
evidence_level: "source-inspected"
|
|
11
|
-
source_revision: "sha256:
|
|
11
|
+
source_revision: "sha256:ff67afd1fdad7e4675cee768168f4c3a7dc743185ad570e724e9ce2ba6a3e266"
|
|
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.70.
|
|
3
|
+
"version": "0.70.3",
|
|
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.70.
|
|
71
|
-
"@happyvertical/smrt-jobs": "0.70.
|
|
72
|
-
"@happyvertical/smrt-profiles": "0.70.
|
|
73
|
-
"@happyvertical/smrt-secrets": "0.70.
|
|
74
|
-
"@happyvertical/smrt-tenancy": "0.70.
|
|
75
|
-
"@happyvertical/smrt-types": "0.70.
|
|
76
|
-
"@happyvertical/smrt-ui": "0.70.
|
|
77
|
-
"@happyvertical/smrt-users": "0.70.
|
|
70
|
+
"@happyvertical/smrt-core": "0.70.3",
|
|
71
|
+
"@happyvertical/smrt-jobs": "0.70.3",
|
|
72
|
+
"@happyvertical/smrt-profiles": "0.70.3",
|
|
73
|
+
"@happyvertical/smrt-secrets": "0.70.3",
|
|
74
|
+
"@happyvertical/smrt-tenancy": "0.70.3",
|
|
75
|
+
"@happyvertical/smrt-types": "0.70.3",
|
|
76
|
+
"@happyvertical/smrt-ui": "0.70.3",
|
|
77
|
+
"@happyvertical/smrt-users": "0.70.3",
|
|
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.70.
|
|
95
|
-
"@happyvertical/smrt-ledgers": "0.70.
|
|
96
|
-
"@happyvertical/smrt-vitest": "0.70.
|
|
94
|
+
"@happyvertical/smrt-approvals": "0.70.3",
|
|
95
|
+
"@happyvertical/smrt-ledgers": "0.70.3",
|
|
96
|
+
"@happyvertical/smrt-vitest": "0.70.3",
|
|
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-Cs6dC7vz.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 importOptionalDependency,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport { assertHydratedMailAccess } from '../access.js';\nimport type { AttachmentOptions } from '../types';\n\n/**\n * Split an absolute path into its directory and file name, or return null for\n * a relative path. Plain string handling rather than `node:path`: the package\n * root must stay browser-reachable (the bundle-gate forbids `node:*` there).\n */\nfunction splitAbsolutePath(\n filePath: string,\n): { dir: string; base: string } | null {\n // A backslash separates segments only in a Windows path; in a POSIX path it\n // is an ordinary filename character.\n const windows = /^[A-Za-z]:[\\\\/]/.test(filePath);\n if (!windows && !filePath.startsWith('/')) return null;\n const cut = windows\n ? Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\\\'))\n : filePath.lastIndexOf('/');\n const dir = filePath.slice(0, cut) || filePath.slice(0, cut + 1);\n return { dir, base: filePath.slice(cut + 1) };\n}\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 * 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 file content (if stored externally)\n *\n * The files SDK is loaded through core's bundler-invisible optional-import\n * boundary so it never enters provider-neutral consumer bundles (#1979).\n * Absence of the SDK at runtime degrades to the existing null contract.\n *\n * The local provider joins every path onto its base path (the process cwd\n * by default), so an absolute `filePath` is rooted at its own directory, and\n * the bytes are read raw: decoding a PDF as UTF-8 corrupts it (#3808).\n */\n async readContent(): Promise<Buffer | null> {\n if (!this.filePath) return null;\n\n try {\n const { getFilesystem, initializeProviders } =\n (await importOptionalDependency(\n '@happyvertical/files',\n \"Import '@happyvertical/smrt-core/filesystem' (or '@happyvertical/smrt-assets/filesystem') during server startup to read externally-stored attachments in bundled builds.\",\n )) as typeof import('@happyvertical/files');\n // The SDK registers its providers asynchronously on import; make the\n // local one available before asking for it.\n await initializeProviders?.();\n const split = splitAbsolutePath(this.filePath);\n const files = await getFilesystem(\n split ? { type: 'local', basePath: split.dir } : { type: 'local' },\n );\n const data = await files.read(split ? split.base : this.filePath, {\n raw: true,\n });\n return data instanceof Buffer ? data : Buffer.from(data);\n } catch {\n return null;\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 attachment.accountId = message.accountId;\n await attachment.save();\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 queryWithGlobals<Attachment>(\n this,\n tenantId,\n 'Attachment.findWithGlobals',\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,kBACP,UACsC;CAGtC,MAAM,UAAU,kBAAkB,KAAK,QAAQ;CAC/C,IAAI,CAAC,WAAW,CAAC,SAAS,WAAW,GAAG,GAAG,OAAO;CAClD,MAAM,MAAM,UACR,KAAK,IAAI,SAAS,YAAY,GAAG,GAAG,SAAS,YAAY,IAAI,CAAC,IAC9D,SAAS,YAAY,GAAG;CAE5B,OAAO;EAAE,KADG,SAAS,MAAM,GAAG,GAAG,KAAK,SAAS,MAAM,GAAG,MAAM,CAAC;EACjD,MAAM,SAAS,MAAM,MAAM,CAAC;CAAE;AAC9C;AAQO,IAAM,aAAN,cAAyB,WAAW;CAEzC,WAA0B;CAG1B,YAAY;CAQZ,YAA2B;CAC3B,WAAW;CACX,cAAc;CACd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