@plotday/twister 0.62.0 → 0.64.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.
@@ -5,4 +5,4 @@
5
5
  * Generated from: prebuild.ts
6
6
  */
7
7
 
8
- export default "import { type Actor, type ActorId, type Contact, type DeliveryError, type Link, type NewLinkWithNotes, type Note, type Thread, type Uuid } from \"./plot\";\nimport type { ScheduleContactStatus } from \"./schedule\";\nimport {\n type AuthProvider,\n type AuthToken,\n type Authorization,\n type Channel,\n type LinkTypeConfig,\n type SyncContext,\n} from \"./tools/integrations\";\nimport { Twist } from \"./twist\";\n\n/**\n * Declares how a connector's platform handles emoji reactions.\n *\n * Drives Plot UI behavior (e.g. the picker filters the available\n * reactions on notes whose primary connector declares `fixed`) and\n * outbound dispatch (Plot won't try to push an emoji the platform\n * can't accept).\n *\n * Variants:\n * - `open-unicode`: Platform accepts any Unicode emoji. `customEmoji`\n * indicates whether the platform additionally supports workspace\n * custom emoji (Slack, Google Chat).\n * - `unicode-subset`: Platform accepts Unicode but only a finite set.\n * `subset` lists the allowed emoji (omit for \"currently full Unicode\n * per docs, future-proofed for shrinkage\").\n * - `fixed`: Platform only accepts a fixed set (e.g. LinkedIn\n * Messaging's 7-reaction set). `allowed` lists every supported emoji.\n */\nexport type ReactionCapabilities =\n | { mode: \"open-unicode\"; customEmoji?: \"workspace\" | \"none\" }\n | { mode: \"unicode-subset\"; subset?: readonly string[] }\n | { mode: \"fixed\"; allowed: readonly string[] };\n\n/**\n * Result returned from {@link Connector.onNoteCreated} and\n * {@link Connector.onNoteUpdated} to report what the external system now\n * has stored for the note.\n *\n * The runtime hashes `externalContent` and stores it as the note's sync\n * baseline. On the next sync-in, if the incoming content hashes to the\n * same value, the runtime knows the external side hasn't changed and\n * preserves Plot's (possibly formatted) content. When the external side\n * is edited, the hash diverges and the runtime overwrites Plot's content\n * with the new external version.\n *\n * Omitting `externalContent` skips baseline tracking — the next sync-in\n * will overwrite Plot's content (previous behavior). Always provide it\n * when the write-back's return value reflects what the external system\n * actually stored (often lossy plain-text), so the round-trip does not\n * clobber the original Plot markdown.\n *\n * The hash covers only the content string — the runtime intentionally\n * does not include a content-type in the hash, so write-back and sync-in\n * do not have to agree on a content-type label for the same underlying\n * bytes. Return exactly the string your connector's sync-in path will\n * emit as `NewNote.content` for this note on the next re-ingest.\n *\n * For back-compat, `onNoteCreated` may also return a plain string, which\n * is treated as `{ key }` with no baseline.\n */\nexport type NoteWriteBackResult = {\n /**\n * External system identifier assigned to this note. Set as the note's\n * `key` for future upsert matching. Required when the runtime does not\n * already know the key (i.e., from `onNoteCreated`); ignored from\n * `onNoteUpdated` when the key was already established on create.\n */\n key?: string;\n /**\n * The content string as the external system now stores it, post-write.\n * For systems whose write-back returns a representation of what was\n * actually stored (e.g. Google Drive comment `content` after a create),\n * pass that verbatim. For systems that only accept plain text, this\n * will often be a lossy plain-text version of the Plot markdown — that\n * is exactly the point: storing the lossy form as baseline lets the\n * next sync-in recognize it and skip overwriting the richer Plot\n * version.\n *\n * Must exactly match the string your connector's sync-in path emits as\n * `NewNote.content` for this note on re-ingest.\n */\n externalContent?: string;\n /**\n * Reports that the outbound send / write-back for this note FAILED and\n * could not be recovered (after the connector's own retries). The runtime\n * records it on the note — surfacing a \"Failed to send\" affordance (Retry /\n * Discard) to the user — and marks the thread unread.\n *\n * - object → record the failure.\n * - `null` → clear a previously-recorded failure (e.g. a successful retry).\n * - omitted (`undefined`) → leave any existing delivery state untouched.\n *\n * A successful write-back (any result without a `deliveryError`) also clears\n * a previously-recorded failure, so connectors usually only need to SET this\n * on failure.\n *\n * Prefer RETURNING this over throwing for expected, user-visible failures\n * (rejected recipient, message too large, quota exhausted): a thrown error\n * pages error tracking, whereas a returned `deliveryError` does not. Reserve\n * throwing for genuinely unexpected errors. Connectors that simply throw on a\n * failed write-back still get a generic \"Failed to send\" surfaced by the\n * runtime, just without a specific reason.\n */\n deliveryError?: DeliveryError | null;\n};\n\n/**\n * A Plot contact pre-resolved to its platform account ID, ready for use\n * in a messaging dispatch.\n *\n * Populated by the runtime for link types with `compose.targets: \"contacts\"` before\n * `onCreateLink` is called. The connector should use `externalAccountId`\n * directly to address the recipient on the platform (e.g. Slack user ID,\n * LinkedIn URN, Gmail address) without performing its own contact lookup.\n */\nexport type ResolvedRecipient = {\n /** Plot contact UUID */\n id: Uuid;\n /** Display name, or null if not set */\n name: string | null;\n /** Platform-specific account identifier pre-resolved at dispatch time (e.g. Slack `U…`, LinkedIn URN, Gmail email address) */\n externalAccountId: string;\n /**\n * The contact's role on the originating thread, resolved from\n * `thread.contact_meta` against the link type's `contactRoles` (e.g.\n * `\"to\"` / `\"cc\"` / `\"bcc\"` for Gmail). `null` when the contact had no\n * explicit role entry — connectors should treat `null` as the link\n * type's default role (the `contactRoles` entry marked `default: true`).\n *\n * Connectors that distinguish roles MUST honor this when addressing the\n * recipient — e.g. Gmail must place `\"cc\"`/`\"bcc\"` recipients in the\n * Cc/Bcc headers, never the To header, so BCC recipients are not\n * exposed to the other recipients. Connectors that don't distinguish\n * roles (Slack, Linear) can ignore it.\n */\n role: string | null;\n};\n\n/**\n * Fields captured in Plot when a user initiates creation of a new external\n * item via a connector's `onCreateLink` hook.\n *\n * Thread-agnostic on purpose — connectors do not receive the Plot thread.\n * The platform attaches the returned `NewLinkWithNotes` to the originating\n * thread once `onCreateLink` resolves.\n */\nexport type CreateLinkDraft = {\n /** The channel (account + resource) the new item belongs to. */\n channelId: string;\n /** Link type identifier, matches a `LinkTypeConfig.type`. */\n type: string;\n /**\n * Status the user selected. Matches a `statuses[].status` for `type`,\n * or null for status-less link types (the parent linkType declares no\n * `statuses` and no `compose.status`).\n */\n status: string | null;\n /** Title of the originating Plot thread (post AI title generation). */\n title: string;\n /** Markdown content of the thread's first note, or null if none. */\n noteContent: string | null;\n /**\n * Contacts attached to the originating Plot thread, excluding the\n * creating user. Use these as recipients (email, chat DM members, etc.)\n * when the external item is a message or invite. An empty list means\n * the user did not add anyone to the thread.\n *\n * For link types with `compose.targets: \"contacts\"`, prefer `recipients` over\n * re-resolving contacts yourself: the runtime pre-resolves each contact\n * to its platform account ID (`externalAccountId`) and populates\n * `recipients` before `onCreateLink` is called.\n */\n contacts: Actor[];\n /**\n * Pre-resolved recipients for link types whose `compose.targets` is\n * `\"contacts\"` or `\"addresses\"`.\n *\n * Only populated for those link types; otherwise undefined. Each entry contains the Plot\n * contact UUID, the platform-specific account ID\n * (`externalAccountId`) the connector should use to address the\n * recipient without performing its own lookup, and the contact's\n * `role` on the thread (e.g. `\"to\"` / `\"cc\"` / `\"bcc\"`) resolved from\n * `thread.contact_meta`. For `\"addresses\"` link types, contacts without\n * a connection-scoped row fall back to `contact.email`.\n */\n recipients?: ResolvedRecipient[];\n /**\n * Free-form addresses the user typed into the picker (no Plot contact\n * row). Only populated for link types with `compose.targets: \"addresses\"`; otherwise\n * undefined. Connectors should append these alongside `recipients`\n * when constructing the recipient list (e.g. `To:` header for Gmail).\n */\n inviteEmails?: string[];\n};\n\n/** An optional OAuth scope group the user can toggle at connect time. */\nexport type OptionalScopeGroup = {\n /** Stable id used to track the user's selection. */\n id: string;\n /** Value-forward switch label, e.g. \"Add names to events using contacts\". */\n label: string;\n /** Optional secondary line shown under the label. */\n description?: string;\n /** The OAuth scope strings this group grants. */\n scopes: string[];\n /** Whether the group is requested by default (switch on). */\n default: boolean;\n};\n\n/**\n * Structured scope declaration. `required` scopes must be granted — auth fails\n * and re-prompts if any is declined. `optional` groups are requested by default\n * but auth still succeeds if the user declines them; the connector should detect\n * the absence via the granted `token.scopes` and degrade gracefully.\n */\nexport type ScopeConfig = {\n required: string[];\n optional?: OptionalScopeGroup[];\n};\n\n/**\n * Base class for connectors — twists that sync data from external services.\n *\n * Connectors declare a single OAuth provider and scopes, and implement channel\n * lifecycle methods for discovering and syncing external resources. They save\n * data directly via `integrations.saveLink()` instead of using the Plot tool.\n *\n * @example\n * ```typescript\n * class LinearConnector extends Connector<LinearConnector> {\n * readonly provider = AuthProvider.Linear;\n * readonly scopes = [\"read\", \"write\"];\n * readonly linkTypes = [{\n * type: \"issue\",\n * label: \"Issue\",\n * statuses: [\n * { status: \"open\", label: \"Open\", icon: \"todo\" },\n * { status: \"done\", label: \"Done\", icon: \"done\", done: true },\n * ],\n * }];\n *\n * build(build: ToolBuilder) {\n * return {\n * integrations: build(Integrations),\n * };\n * }\n *\n * async getChannels(auth: Authorization, token: AuthToken): Promise<Channel[]> {\n * const teams = await this.listTeams(token);\n * return teams.map(t => ({ id: t.id, title: t.name }));\n * }\n *\n * async onChannelEnabled(channel: Channel) {\n * const issues = await this.fetchIssues(channel.id);\n * for (const issue of issues) {\n * await this.tools.integrations.saveLink(issue);\n * }\n * }\n *\n * async onChannelDisabled(channel: Channel) {\n * // Clean up webhooks, sync state, etc.\n * }\n * }\n * ```\n */\nexport abstract class Connector<TSelf> extends Twist<TSelf> {\n /**\n * Static marker to identify Connector subclasses without instanceof checks\n * across worker boundaries.\n */\n static readonly isConnector = true;\n\n // ---- Identity (abstract — every connector must declare) ----\n\n /** The OAuth provider this connector authenticates with. */\n readonly provider?: AuthProvider;\n\n /** OAuth scopes to request for this connector — a flat list (all required), or\n * a {@link ScopeConfig} declaring required + optional scope groups. */\n readonly scopes?: string[] | ScopeConfig;\n\n /**\n * Plain-language bullets describing what access connecting this service\n * grants the user — shown on the connect screen regardless of auth mechanism\n * (OAuth, API key, or hosted). For OAuth connectors it also previews what the\n * provider's consent screen will request. These are justifications for what\n * Plot accesses, not a one-to-one mapping of scope strings.\n */\n readonly access?: string[];\n\n // ---- Auth model ----\n\n /**\n * When true, one credential is shared across all users in the workspace,\n * entered once by the installer. When false (default), each user provides\n * their own credential.\n *\n * Applies to both OAuth and key-based connectors:\n * - Shared OAuth: e.g. Slack bot token (workspace-level)\n * - Shared key: e.g. Attio workspace API key\n * - Individual OAuth: e.g. Google Calendar (per-user)\n * - Individual key: e.g. Fellow (per-user API key)\n */\n readonly shared?: boolean;\n\n /**\n * The Options field name that contains the authentication key (e.g. \"apiKey\").\n * Must reference a `secure: true` field in the Options schema.\n *\n * When set, this connector uses key-based auth instead of OAuth.\n * For individual connectors (`shared` is false), this field is stored\n * per-user rather than in shared config.\n */\n readonly keyOption?: string;\n\n // ---- Optional metadata ----\n\n /**\n * When true, this connector has a single implicit channel.\n * `getChannels()` must return exactly one Channel.\n * The UI will show channel config inline instead of a channel list.\n */\n readonly singleChannel?: boolean;\n\n /**\n * The user-facing noun for this connector's channels — what each\n * {@link Channel} returned by {@link getChannels} actually represents in the\n * external service. Many connectors map \"channels\" onto a domain concept\n * (folders, projects, calendars, labels, spaces, repositories, …), so the\n * generic word \"channel\" reads as jargon. Set this and the UI substitutes it\n * everywhere it would otherwise say \"channel(s)\" — e.g. the per-connection\n * toggle becomes \"Sync new folders\" / \"When a new folder is added, …\".\n *\n * Provide lowercase nouns (the UI capitalizes where needed):\n * `{ singular: \"folder\", plural: \"folders\" }`. Defaults to\n * `{ singular: \"channel\", plural: \"channels\" }` when omitted.\n */\n readonly channelNoun?: { singular: string; plural: string };\n\n /**\n * Whether the per-connection \"Sync new channels\" preference starts ON for\n * newly added connections of this connector. Defaults to `false` (opt-in).\n *\n * Set `true` for connectors that select **all** of their channels by default\n * (i.e. {@link getChannels} returns no channels marked\n * `enabledByDefault: false`). If syncing every channel is the intended\n * default, then channels discovered later should also sync automatically.\n * Leave `false`/omitted for selective connectors that exclude some channels\n * by default (e.g. Gmail syncs only Inbox/Sent, Google Calendar only\n * owner calendars) — for those, a newly discovered channel is just as\n * uncertain and should wait for the user to opt in.\n *\n * Only affects the **default** for new connections; the user's explicit\n * toggle always wins, and existing connections keep their stored preference.\n */\n readonly autoEnableNewChannelsByDefault?: boolean;\n\n /**\n * Whether this connector supports the platform's sequential auto-threading —\n * folding a conversation that arrives as a run of separate top-level messages\n * into a single thread. Set `true` for conversational connectors (chat,\n * messaging) that mark eligible links with {@link NewLink.autoThread}. The UI\n * shows a per-connection \"Group related messages into conversations\" toggle\n * only for connectors that declare this.\n *\n * Leave undefined/false for connectors whose items are not conversational\n * (calendars, issue trackers, file storage) — marking a link does nothing\n * unless the connection both declares support and the user opted in.\n */\n readonly autoThreading?: boolean;\n\n /**\n * Whether the per-connection auto-threading preference starts ON for newly\n * added connections of this connector. Defaults to `false` (opt-in) — the\n * least-surprise default, since a wrong fold is irreversible. Only meaningful\n * when {@link autoThreading} is `true`. The user's explicit toggle always\n * wins, and existing connections keep their stored preference.\n */\n readonly autoThreadingByDefault?: boolean;\n\n /**\n * Registry of link types this connector creates (e.g., issue, event, message).\n * Used for display in the UI (icons, labels, statuses).\n */\n readonly linkTypes?: LinkTypeConfig[];\n\n /**\n * Declares how this connector's platform handles emoji reactions.\n * Used to filter the reaction picker for notes whose primary connector\n * is this one, and to guard outbound dispatch from sending emoji the\n * platform can't accept.\n *\n * Leave undefined for connectors whose platform has no concept of\n * reactions (calendar, file storage, issue trackers without reactions).\n */\n readonly reactionCapabilities?: ReactionCapabilities;\n\n /**\n * When true, this connector's effective link types are computed dynamically\n * from its enabled channels' per-channel link types (each channel carries the\n * link types for whatever product/resource it represents), rather than the\n * static union of all declared providers' link types. Lets one connection\n * surface different link types depending on what the user has enabled — e.g.\n * a combined Google connection shows calendar/event link types (and thus the\n * agenda) only when a calendar channel is enabled.\n *\n * Defaults to false (static link types — the behavior for every connector\n * that doesn't set this). Requires the connector to attach per-channel\n * `linkTypes` on the channels returned by `getChannels`.\n */\n readonly dynamicLinkTypes?: boolean;\n\n /**\n * When true, this connector is mentioned by default on replies to threads it created.\n * When false (default), this connector cannot be mentioned at all.\n *\n * Set this to true for connectors with bidirectional sync (e.g., issue trackers,\n * messaging) where user replies should be written back to the external service.\n */\n static readonly handleReplies?: boolean;\n\n // ---- Account identity (abstract — every connector must implement) ----\n\n /**\n * Returns a human-readable name for the connected account.\n * Shown in the connections list and edit modal to identify this connection.\n *\n * For OAuth connectors, this is typically the workspace or organization name\n * (e.g., \"Acme Corp\" for a Linear workspace). For API key connectors, this\n * could be the workspace name from the external service.\n *\n * Override this in your connector to return a meaningful account name.\n *\n * @param auth - The authorization (null for no-provider connectors)\n * @param token - The access token (null for no-provider connectors)\n * @returns Promise resolving to the account display name\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getAccountName(\n auth: Authorization | null,\n token: AuthToken | null\n ): Promise<string | null> {\n return Promise.resolve(null);\n }\n\n // ---- Channel lifecycle (abstract — every connector must implement) ----\n\n /**\n * Returns available channels for the authorized actor.\n * Called after OAuth is complete, during the setup/edit modal.\n *\n * @param auth - The completed authorization with provider and actor info\n * @param token - The access token for making API calls\n * @returns Promise resolving to available channels for the user to select\n */\n abstract getChannels(\n auth: Authorization | null,\n token: AuthToken | null\n ): Promise<Channel[]>;\n\n /**\n * Called when a channel resource is enabled for syncing.\n *\n * The framework dispatches this in three cases:\n * 1. **Initial enable** — user toggled the channel on for the first time.\n * 2. **Auto-enable** — `setChannels` discovered a new channel on a\n * connection with `auto_enable_new_channels` set.\n * 3. **Recovery after re-auth** — the user re-authorized a previously-\n * broken connection. The framework calls `onChannelEnabled` for every\n * channel that was already enabled at the time of re-auth, with\n * `context.recovering = true`. See {@link SyncContext.recovering}.\n *\n * Implementations should be **idempotent and overwrite stored state**:\n * the same channel may receive multiple `onChannelEnabled` calls across\n * its lifetime. Use unconditional `this.set()` writes rather than\n * coalesce/skip-if-present logic so a recovery dispatch wipes stale\n * cursors and state from the prior session.\n *\n * **Sync state tracking is automatic.** The framework stamps the\n * connection as \"syncing\" when it dispatches this method and clears\n * that state when:\n * - the connector calls `tools.integrations.channelSyncCompleted(id)`\n * once the initial backfill is done, OR\n * - this method throws an unhandled exception (auto-cleared so the UI\n * doesn't get stuck in \"syncing\" forever).\n *\n * **IMPORTANT: This method runs inline in the HTTP request handler.**\n * Any long-running work (webhook setup, API calls, sync) MUST be queued\n * as a separate task via `this.runTask()`, not executed inline. Blocking\n * here causes the client to spin waiting for the response.\n *\n * Only lightweight operations should appear directly in this method:\n * `this.set()`, `this.get()`, `this.callback()`, and `this.runTask()`.\n *\n * @example\n * ```typescript\n * async onChannelEnabled(channel: Channel, context?: SyncContext): Promise<void> {\n * // Recovery: drop stale cursors so the next sync re-walks history.\n * if (context?.recovering) {\n * await this.clear(`last_sync_token_${channel.id}`);\n * }\n *\n * await this.set(`sync_state_${channel.id}`, { channelId: channel.id });\n *\n * // Queue sync as a task — do NOT use this.run() or call sync methods inline\n * const syncCallback = await this.callback(this.syncBatch, 1, \"full\", channel.id, true);\n * await this.runTask(syncCallback);\n *\n * // Queue webhook setup as a task — do NOT call setupWebhook() inline\n * const webhookCallback = await this.callback(this.setupWebhook, channel.id);\n * await this.runTask(webhookCallback);\n * }\n * ```\n *\n * @param channel - The channel that was enabled\n * @param context - Optional sync context (plan-based hints, recovery flag)\n */\n abstract onChannelEnabled(channel: Channel, context?: SyncContext): Promise<void>;\n\n /**\n * Called when a channel resource is disabled.\n * Should stop sync, clean up webhooks, and remove state.\n *\n * @param channel - The channel that was disabled\n */\n abstract onChannelDisabled(channel: Channel): Promise<void>;\n\n // ---- Write-back hooks (optional, default no-ops) ----\n\n /**\n * Called when a link created by this connector is updated by the user.\n * Override to write back changes to the external service\n * (e.g., changing issue status in Linear when marked done in Plot).\n *\n * @param link - The updated link\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onLinkUpdated(link: Link): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a user creates a thread in Plot that should create a new\n * item in this connector's external system.\n *\n * A connector opts in to Plot-initiated creation by declaring a\n * `compose` block on the relevant `LinkTypeConfig` (see\n * {@link ComposeConfig}). When a user picks \"Create new <type>\" from the\n * Add link modal and the thread is synced, the runtime calls this method\n * with the draft fields.\n *\n * Implementations should create the item in the external service and\n * return a `NewLinkWithNotes` describing the created item. The platform\n * attaches the returned link to the originating thread — do not call\n * `integrations.saveLink` yourself.\n *\n * Returning `null` aborts creation silently (the thread is still saved\n * without a link).\n *\n * @param draft - The fields captured in Plot for the new item.\n * @returns The link to attach, or null to abort creation.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onCreateLink(draft: CreateLinkDraft): Promise<NewLinkWithNotes | null> {\n return Promise.resolve(null);\n }\n\n /**\n * Called when a note is created on a thread owned by this connector.\n * Override to write back comments to the external service\n * (e.g., adding a comment to a Linear issue).\n *\n * Returning a string or {@link NoteWriteBackResult} links the Plot note\n * to its external counterpart. A plain string sets the note's `key`.\n * A `NoteWriteBackResult` additionally sets a sync baseline (via\n * `externalContent`) so the next sync-in can recognize the round-tripped\n * content and preserve Plot's formatted version. See\n * {@link NoteWriteBackResult} for details.\n *\n * @param note - The created note\n * @param thread - The thread the note belongs to (includes thread.meta with connector-specific data)\n * @returns Optional note key or NoteWriteBackResult for external dedup + baseline tracking\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onNoteCreated(note: Note, thread: Thread): Promise<string | NoteWriteBackResult | void> {\n return Promise.resolve();\n }\n\n /**\n * Resolve a `fileRef` action's bytes for download. Called when a user opens\n * an attachment in Plot. Return either a redirect URL (preferred for sources\n * that issue signed URLs, like Linear S3 or Slack permalink_public) or a\n * streamed body (required when bytes are only reachable through an\n * authenticated API call, like Gmail attachments.get).\n *\n * @param ref Opaque value the connector previously emitted on a fileRef action.\n * @returns Either `{ redirectUrl }` or `{ body, mimeType, fileName? }`.\n * @throws If the source is unavailable, the connection is broken, or `ref` is invalid.\n *\n * If not overridden, fileRef actions on this connector's notes will return 410 Gone.\n */\n async downloadAttachment(\n ref: string,\n ): Promise<\n | { redirectUrl: string }\n | { body: ReadableStream | Uint8Array; mimeType: string; fileName?: string }\n > {\n throw new Error(\n `downloadAttachment not implemented for ${this.constructor.name} (ref=${ref})`,\n );\n }\n\n /**\n * Called when a note on a thread owned by this connector is updated.\n * Override to write back changes to the external service\n * (e.g., syncing reaction tags as emoji reactions, or editing a comment\n * whose content changed in Plot).\n *\n * Return a {@link NoteWriteBackResult} with `externalContent` to update\n * the sync baseline after a successful write-back, so the next sync-in\n * recognizes the external version as already-seen and preserves Plot's\n * content.\n *\n * @param note - The updated note (includes current tags)\n * @param thread - The thread the note belongs to (includes thread.meta with connector-specific data)\n * @returns Optional NoteWriteBackResult for baseline tracking\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onNoteUpdated(note: Note, thread: Thread): Promise<NoteWriteBackResult | void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a user reads or unreads a thread owned by this connector.\n * Override to write back read status to the external service\n * (e.g., marking an email as read in Gmail).\n *\n * @param thread - The thread that was read/unread (includes thread.meta with connector-specific data)\n * @param actor - The user who performed the action\n * @param unread - false when marked as read, true when marked as unread\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onThreadRead(thread: Thread, actor: Actor, unread: boolean): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a user changes the **thread-level sharing** of a thread owned\n * by this connector — adding or removing a contact, or (for connectors with\n * roles) changing a contact's role. Override on connectors whose external\n * source can reflect that membership change, e.g. a group DM / multi-party\n * chat (`LinkTypeConfig.sharingModel: \"thread\"`) or an email's To/Cc/Bcc\n * recipients (`sharingModel: \"message\"`). Connectors backed by an immutable\n * roster (most group DMs today) or by channel-level membership\n * (`sharingModel: \"channel\"`) leave this as the default no-op.\n *\n * `role`/`from`/`to` are **null** for connectors without roles (group DMs\n * have no roles); they carry a `contactRoles` id only for connectors that\n * declare roles (e.g. email `to`/`cc`/`bcc`).\n *\n * The dispatch fires after Plot has persisted the change. A connector may\n * reflect it actively (e.g. add/remove a participant on the external chat)\n * or passively on the next outbound note (e.g. building To/Cc/Bcc headers\n * from the current `thread.contacts` × `thread.contactMeta`) — this callback\n * is not the right place to send a standalone notification.\n *\n * @param thread - The thread whose contacts changed\n * @param changes - The added/removed contacts and any role transitions on existing contacts\n */\n /* eslint-disable @typescript-eslint/no-unused-vars */\n onContactsChanged(\n thread: Thread,\n changes: {\n added: Array<{ contact: Contact; role: string | null }>;\n removed: Array<{ contact: Contact; role: string | null }>;\n changed: Array<{ contact: Contact; from: string | null; to: string | null }>;\n },\n ): Promise<void> {\n return Promise.resolve();\n }\n /* eslint-enable @typescript-eslint/no-unused-vars */\n\n /**\n * Called when a user marks or unmarks a thread as todo.\n * Override to sync todo status to the external service\n * (e.g., starring an email in Gmail when marked as todo).\n *\n * @param thread - The thread (includes thread.meta with connector-specific data)\n * @param actor - The user who changed the todo status\n * @param todo - true when marked as todo, false when done or removed\n * @param options - Additional context\n * @param options.date - The todo date (when todo=true)\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onThreadToDo(thread: Thread, actor: Actor, todo: boolean, options: { date?: Date }): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a schedule contact's RSVP status changes on a thread owned by this connector.\n * Override to sync RSVP changes back to the external calendar.\n *\n * @param thread - The thread (includes thread.meta with connector-specific data)\n * @param scheduleId - The schedule ID\n * @param contactId - The contact whose status changed\n * @param status - The new RSVP status ('attend', 'skip', or null)\n * @param actor - The user who changed the status\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onScheduleContactUpdated(thread: Thread, scheduleId: string, contactId: ActorId, status: ScheduleContactStatus | null, actor: Actor): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a user adds or removes a single emoji reaction on a note\n * (one event per `(note, actor, emoji)` state transition).\n *\n * Dispatch is routed to the reacting user's own connector instance via\n * `twist_instance_for_actor` on `note_reaction.actor_id`, so this method\n * already runs under the reactor's auth. Fetch the API client with the\n * connector's normal token-fetch path (`this.tools.integrations.get(...)`)\n * and the external write — e.g. Slack `reactions.add` — will be attributed\n * to the correct user. No `actAs` step required.\n *\n * If the reacting user has no connection of this type, no dispatch fires\n * for that reaction (it stays in Plot only).\n *\n * Override to sync per-actor reactions back to the external system.\n *\n * @param note - The note that was reacted on (partial; `id`, `key`, `content` populated)\n * @param thread - The thread the note belongs to (partial; `id`, `title`, `archived`, `meta` populated)\n * @param actor - The contact who added/removed the reaction\n * @param emoji - The emoji (Unicode grapheme or `provider:workspace/name` custom-emoji ref)\n * @param added - `true` if the reaction is now present, `false` if it was removed\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onNoteReactionChanged(note: Note, thread: Thread, actor: Actor, emoji: string, added: boolean): Promise<void> {\n return Promise.resolve();\n }\n\n // ---- Activation ----\n\n /**\n * Called when the connector is activated after OAuth is complete.\n *\n * Connectors receive the authorization in addition to the activating actor.\n * When this runs, `this.userId` is already populated with the installing\n * user's ID.\n *\n * Default implementation does nothing. Override for custom setup.\n *\n * @param context - The activation context\n * @param context.auth - The completed OAuth authorization\n * @param context.actor - The actor who activated the connector\n */\n // @ts-ignore - Connector.activate() has a Connector-specific context type.\n activate(context: { auth?: Authorization; actor?: Actor }): Promise<void> {\n return Promise.resolve();\n }\n}\n\n/** @deprecated Use `Connector` instead. */\nexport { Connector as Source };\n";
8
+ export default "import { type Actor, type ActorId, type Contact, type DeliveryError, type Link, type NewLinkWithNotes, type Note, type Thread, type Uuid } from \"./plot\";\nimport type { ScheduleContactStatus } from \"./schedule\";\nimport {\n type AuthProvider,\n type AuthToken,\n type Authorization,\n type Channel,\n type LinkTypeConfig,\n type SyncContext,\n} from \"./tools/integrations\";\nimport { Twist } from \"./twist\";\n\n/**\n * Declares how a connector's platform handles emoji reactions.\n *\n * Drives Plot UI behavior (e.g. the picker filters the available\n * reactions on notes whose primary connector declares `fixed`) and\n * outbound dispatch (Plot won't try to push an emoji the platform\n * can't accept).\n *\n * Variants:\n * - `open-unicode`: Platform accepts any Unicode emoji. `customEmoji`\n * indicates whether the platform additionally supports workspace\n * custom emoji (Slack, Google Chat).\n * - `unicode-subset`: Platform accepts Unicode but only a finite set.\n * `subset` lists the allowed emoji (omit for \"currently full Unicode\n * per docs, future-proofed for shrinkage\").\n * - `fixed`: Platform only accepts a fixed set (e.g. LinkedIn\n * Messaging's 7-reaction set). `allowed` lists every supported emoji.\n */\nexport type ReactionCapabilities =\n | { mode: \"open-unicode\"; customEmoji?: \"workspace\" | \"none\" }\n | { mode: \"unicode-subset\"; subset?: readonly string[] }\n | { mode: \"fixed\"; allowed: readonly string[] };\n\n/**\n * Result returned from {@link Connector.onNoteCreated} and\n * {@link Connector.onNoteUpdated} to report what the external system now\n * has stored for the note.\n *\n * The runtime hashes `externalContent` and stores it as the note's sync\n * baseline. On the next sync-in, if the incoming content hashes to the\n * same value, the runtime knows the external side hasn't changed and\n * preserves Plot's (possibly formatted) content. When the external side\n * is edited, the hash diverges and the runtime overwrites Plot's content\n * with the new external version.\n *\n * Omitting `externalContent` skips baseline tracking — the next sync-in\n * will overwrite Plot's content (previous behavior). Always provide it\n * when the write-back's return value reflects what the external system\n * actually stored (often lossy plain-text), so the round-trip does not\n * clobber the original Plot markdown.\n *\n * The hash covers only the content string — the runtime intentionally\n * does not include a content-type in the hash, so write-back and sync-in\n * do not have to agree on a content-type label for the same underlying\n * bytes. Return exactly the string your connector's sync-in path will\n * emit as `NewNote.content` for this note on the next re-ingest.\n *\n * For back-compat, `onNoteCreated` may also return a plain string, which\n * is treated as `{ key }` with no baseline.\n */\nexport type NoteWriteBackResult = {\n /**\n * External system identifier assigned to this note. Set as the note's\n * `key` for future upsert matching. Required when the runtime does not\n * already know the key (i.e., from `onNoteCreated`); ignored from\n * `onNoteUpdated` when the key was already established on create.\n */\n key?: string;\n /**\n * The content string as the external system now stores it, post-write.\n * For systems whose write-back returns a representation of what was\n * actually stored (e.g. Google Drive comment `content` after a create),\n * pass that verbatim. For systems that only accept plain text, this\n * will often be a lossy plain-text version of the Plot markdown — that\n * is exactly the point: storing the lossy form as baseline lets the\n * next sync-in recognize it and skip overwriting the richer Plot\n * version.\n *\n * Must exactly match the string your connector's sync-in path emits as\n * `NewNote.content` for this note on re-ingest.\n */\n externalContent?: string;\n /**\n * Reports that the outbound send / write-back for this note FAILED and\n * could not be recovered (after the connector's own retries). The runtime\n * records it on the note — surfacing a \"Failed to send\" affordance (Retry /\n * Discard) to the user — and marks the thread unread.\n *\n * - object → record the failure.\n * - `null` → clear a previously-recorded failure (e.g. a successful retry).\n * - omitted (`undefined`) → leave any existing delivery state untouched.\n *\n * A successful write-back (any result without a `deliveryError`) also clears\n * a previously-recorded failure, so connectors usually only need to SET this\n * on failure.\n *\n * Prefer RETURNING this over throwing for expected, user-visible failures\n * (rejected recipient, message too large, quota exhausted): a thrown error\n * pages error tracking, whereas a returned `deliveryError` does not. Reserve\n * throwing for genuinely unexpected errors. Connectors that simply throw on a\n * failed write-back still get a generic \"Failed to send\" surfaced by the\n * runtime, just without a specific reason.\n */\n deliveryError?: DeliveryError | null;\n};\n\n/**\n * A Plot contact pre-resolved to its platform account ID, ready for use\n * in a messaging dispatch.\n *\n * Populated by the runtime for link types with `compose.targets: \"contacts\"` before\n * `onCreateLink` is called. The connector should use `externalAccountId`\n * directly to address the recipient on the platform (e.g. Slack user ID,\n * LinkedIn URN, Gmail address) without performing its own contact lookup.\n */\nexport type ResolvedRecipient = {\n /** Plot contact UUID */\n id: Uuid;\n /** Display name, or null if not set */\n name: string | null;\n /** Platform-specific account identifier pre-resolved at dispatch time (e.g. Slack `U…`, LinkedIn URN, Gmail email address) */\n externalAccountId: string;\n /**\n * The contact's role on the originating thread, resolved from\n * `thread.contact_meta` against the link type's `contactRoles` (e.g.\n * `\"to\"` / `\"cc\"` / `\"bcc\"` for Gmail). `null` when the contact had no\n * explicit role entry — connectors should treat `null` as the link\n * type's default role (the `contactRoles` entry marked `default: true`).\n *\n * Connectors that distinguish roles MUST honor this when addressing the\n * recipient — e.g. Gmail must place `\"cc\"`/`\"bcc\"` recipients in the\n * Cc/Bcc headers, never the To header, so BCC recipients are not\n * exposed to the other recipients. Connectors that don't distinguish\n * roles (Slack, Linear) can ignore it.\n */\n role: string | null;\n};\n\n/**\n * Fields captured in Plot when a user initiates creation of a new external\n * item via a connector's `onCreateLink` hook.\n *\n * Thread-agnostic on purpose — connectors do not receive the Plot thread.\n * The platform attaches the returned `NewLinkWithNotes` to the originating\n * thread once `onCreateLink` resolves.\n */\nexport type CreateLinkDraft = {\n /** The channel (account + resource) the new item belongs to. */\n channelId: string;\n /** Link type identifier, matches a `LinkTypeConfig.type`. */\n type: string;\n /**\n * Status the user selected. Matches a `statuses[].status` for `type`,\n * or null for status-less link types (the parent linkType declares no\n * `statuses` and no `compose.status`).\n */\n status: string | null;\n /** Title of the originating Plot thread (post AI title generation). */\n title: string;\n /** Markdown content of the thread's first note, or null if none. */\n noteContent: string | null;\n /**\n * Contacts attached to the originating Plot thread, excluding the\n * creating user. Use these as recipients (email, chat DM members, etc.)\n * when the external item is a message or invite. An empty list means\n * the user did not add anyone to the thread.\n *\n * For link types with `compose.targets: \"contacts\"`, prefer `recipients` over\n * re-resolving contacts yourself: the runtime pre-resolves each contact\n * to its platform account ID (`externalAccountId`) and populates\n * `recipients` before `onCreateLink` is called.\n */\n contacts: Actor[];\n /**\n * Pre-resolved recipients for link types whose `compose.targets` is\n * `\"contacts\"` or `\"addresses\"`.\n *\n * Only populated for those link types; otherwise undefined. Each entry contains the Plot\n * contact UUID, the platform-specific account ID\n * (`externalAccountId`) the connector should use to address the\n * recipient without performing its own lookup, and the contact's\n * `role` on the thread (e.g. `\"to\"` / `\"cc\"` / `\"bcc\"`) resolved from\n * `thread.contact_meta`. For `\"addresses\"` link types, contacts without\n * a connection-scoped row fall back to `contact.email`.\n */\n recipients?: ResolvedRecipient[];\n /**\n * Free-form addresses the user typed into the picker (no Plot contact\n * row). Only populated for link types with `compose.targets: \"addresses\"`; otherwise\n * undefined. Connectors should append these alongside `recipients`\n * when constructing the recipient list (e.g. `To:` header for Gmail).\n */\n inviteEmails?: string[];\n};\n\n/** An optional OAuth scope group the user can toggle at connect time. */\nexport type OptionalScopeGroup = {\n /** Stable id used to track the user's selection. */\n id: string;\n /** Value-forward switch label, e.g. \"Add names to events using contacts\". */\n label: string;\n /** Optional secondary line shown under the label. */\n description?: string;\n /** The OAuth scope strings this group grants. */\n scopes: string[];\n /** Whether the group is requested by default (switch on). */\n default: boolean;\n};\n\n/**\n * Structured scope declaration. `required` scopes must be granted — auth fails\n * and re-prompts if any is declined. `optional` groups are requested by default\n * but auth still succeeds if the user declines them; the connector should detect\n * the absence via the granted `token.scopes` and degrade gracefully.\n */\nexport type ScopeConfig = {\n required: string[];\n optional?: OptionalScopeGroup[];\n};\n\n/**\n * Per-instance product metadata for combined (multi-product) connectors — one\n * ordinary `Connector` that bundles several user-facing products (e.g. the\n * combined Google connector covering Mail, Calendar, Tasks, and Contacts) under\n * a single OAuth grant and one charge.\n *\n * The app's combined-connection setup/status UX renders one row per entry. Each\n * product maps to exactly one optional scope group: `scopeGroupId` MUST equal an\n * {@link OptionalScopeGroup.id} declared in the connector's {@link ScopeConfig}\n * `optional` groups, so the API can derive per-product enablement\n * (`granted | scope-missing | no-channels | locally-off`) from the connection's\n * granted scopes plus its enabled channels.\n *\n * Plain (single-product) connectors leave {@link Connector.products} undefined;\n * the API then omits the `products`/`productStatus` fields and the app falls\n * back to the standard per-connector flow.\n */\nexport type ProductInfo = {\n /** Stable product id. Also the channel-id namespace prefix (`\"<key>:<rawId>\"`). */\n key: string;\n /** Setup/status row title (e.g. \"Gmail\"). */\n label: string;\n /** Short summary shown under the label on the setup/status row. */\n description: string;\n /** Icon URL rendered on the row. */\n icon: string;\n /** Matches an {@link OptionalScopeGroup.id} in this connector's scopes. */\n scopeGroupId: string;\n};\n\n/**\n * Base class for connectors — twists that sync data from external services.\n *\n * Connectors declare a single OAuth provider and scopes, and implement channel\n * lifecycle methods for discovering and syncing external resources. They save\n * data directly via `integrations.saveLink()` instead of using the Plot tool.\n *\n * @example\n * ```typescript\n * class LinearConnector extends Connector<LinearConnector> {\n * readonly provider = AuthProvider.Linear;\n * readonly scopes = [\"read\", \"write\"];\n * readonly linkTypes = [{\n * type: \"issue\",\n * label: \"Issue\",\n * statuses: [\n * { status: \"open\", label: \"Open\", icon: \"todo\" },\n * { status: \"done\", label: \"Done\", icon: \"done\", done: true },\n * ],\n * }];\n *\n * build(build: ToolBuilder) {\n * return {\n * integrations: build(Integrations),\n * };\n * }\n *\n * async getChannels(auth: Authorization, token: AuthToken): Promise<Channel[]> {\n * const teams = await this.listTeams(token);\n * return teams.map(t => ({ id: t.id, title: t.name }));\n * }\n *\n * async onChannelEnabled(channel: Channel) {\n * const issues = await this.fetchIssues(channel.id);\n * for (const issue of issues) {\n * await this.tools.integrations.saveLink(issue);\n * }\n * }\n *\n * async onChannelDisabled(channel: Channel) {\n * // Clean up webhooks, sync state, etc.\n * }\n * }\n * ```\n */\nexport abstract class Connector<TSelf> extends Twist<TSelf> {\n /**\n * Static marker to identify Connector subclasses without instanceof checks\n * across worker boundaries.\n */\n static readonly isConnector = true;\n\n // ---- Identity (abstract — every connector must declare) ----\n\n /** The OAuth provider this connector authenticates with. */\n readonly provider?: AuthProvider;\n\n /** OAuth scopes to request for this connector — a flat list (all required), or\n * a {@link ScopeConfig} declaring required + optional scope groups. */\n readonly scopes?: string[] | ScopeConfig;\n\n /**\n * Plain-language bullets describing what access connecting this service\n * grants the user — shown on the connect screen regardless of auth mechanism\n * (OAuth, API key, or hosted). For OAuth connectors it also previews what the\n * provider's consent screen will request. These are justifications for what\n * Plot accesses, not a one-to-one mapping of scope strings.\n */\n readonly access?: string[];\n\n // ---- Auth model ----\n\n /**\n * When true, one credential is shared across all users in the workspace,\n * entered once by the installer. When false (default), each user provides\n * their own credential.\n *\n * Applies to both OAuth and key-based connectors:\n * - Shared OAuth: e.g. Slack bot token (workspace-level)\n * - Shared key: e.g. Attio workspace API key\n * - Individual OAuth: e.g. Google Calendar (per-user)\n * - Individual key: e.g. Fellow (per-user API key)\n */\n readonly shared?: boolean;\n\n /**\n * The Options field name that contains the authentication key (e.g. \"apiKey\").\n * Must reference a `secure: true` field in the Options schema.\n *\n * When set, this connector uses key-based auth instead of OAuth.\n * For individual connectors (`shared` is false), this field is stored\n * per-user rather than in shared config.\n */\n readonly keyOption?: string;\n\n // ---- Optional metadata ----\n\n /**\n * When true, this connector has a single implicit channel.\n * `getChannels()` must return exactly one Channel.\n * The UI will show channel config inline instead of a channel list.\n */\n readonly singleChannel?: boolean;\n\n /**\n * The user-facing noun for this connector's channels — what each\n * {@link Channel} returned by {@link getChannels} actually represents in the\n * external service. Many connectors map \"channels\" onto a domain concept\n * (folders, projects, calendars, labels, spaces, repositories, …), so the\n * generic word \"channel\" reads as jargon. Set this and the UI substitutes it\n * everywhere it would otherwise say \"channel(s)\" — e.g. the per-connection\n * toggle becomes \"Sync new folders\" / \"When a new folder is added, …\".\n *\n * Provide lowercase nouns (the UI capitalizes where needed):\n * `{ singular: \"folder\", plural: \"folders\" }`. Defaults to\n * `{ singular: \"channel\", plural: \"channels\" }` when omitted.\n */\n readonly channelNoun?: { singular: string; plural: string };\n\n /**\n * Whether the per-connection \"Sync new channels\" preference starts ON for\n * newly added connections of this connector. Defaults to `false` (opt-in).\n *\n * Set `true` for connectors that select **all** of their channels by default\n * (i.e. {@link getChannels} returns no channels marked\n * `enabledByDefault: false`). If syncing every channel is the intended\n * default, then channels discovered later should also sync automatically.\n * Leave `false`/omitted for selective connectors that exclude some channels\n * by default (e.g. Gmail syncs only Inbox/Sent, Google Calendar only\n * owner calendars) — for those, a newly discovered channel is just as\n * uncertain and should wait for the user to opt in.\n *\n * Only affects the **default** for new connections; the user's explicit\n * toggle always wins, and existing connections keep their stored preference.\n */\n readonly autoEnableNewChannelsByDefault?: boolean;\n\n /**\n * Whether this connector supports the platform's sequential auto-threading —\n * folding a conversation that arrives as a run of separate top-level messages\n * into a single thread. Set `true` for conversational connectors (chat,\n * messaging) that mark eligible links with {@link NewLink.autoThread}. The UI\n * shows a per-connection \"Group related messages into conversations\" toggle\n * only for connectors that declare this.\n *\n * Leave undefined/false for connectors whose items are not conversational\n * (calendars, issue trackers, file storage) — marking a link does nothing\n * unless the connection both declares support and the user opted in.\n */\n readonly autoThreading?: boolean;\n\n /**\n * Whether the per-connection auto-threading preference starts ON for newly\n * added connections of this connector. Defaults to `false` (opt-in) — the\n * least-surprise default, since a wrong fold is irreversible. Only meaningful\n * when {@link autoThreading} is `true`. The user's explicit toggle always\n * wins, and existing connections keep their stored preference.\n */\n readonly autoThreadingByDefault?: boolean;\n\n /**\n * Registry of link types this connector creates (e.g., issue, event, message).\n * Used for display in the UI (icons, labels, statuses).\n */\n readonly linkTypes?: LinkTypeConfig[];\n\n /**\n * Declares how this connector's platform handles emoji reactions.\n * Used to filter the reaction picker for notes whose primary connector\n * is this one, and to guard outbound dispatch from sending emoji the\n * platform can't accept.\n *\n * Leave undefined for connectors whose platform has no concept of\n * reactions (calendar, file storage, issue trackers without reactions).\n */\n readonly reactionCapabilities?: ReactionCapabilities;\n\n /**\n * When true, this connector's effective link types are computed dynamically\n * from its enabled channels' per-channel link types (each channel carries the\n * link types for whatever product/resource it represents), rather than the\n * static union of all declared providers' link types. Lets one connection\n * surface different link types depending on what the user has enabled — e.g.\n * a combined Google connection shows calendar/event link types (and thus the\n * agenda) only when a calendar channel is enabled.\n *\n * Defaults to false (static link types — the behavior for every connector\n * that doesn't set this). Requires the connector to attach per-channel\n * `linkTypes` on the channels returned by `getChannels`.\n */\n readonly dynamicLinkTypes?: boolean;\n\n /**\n * Per-instance product metadata for combined (multi-product) connectors —\n * one connection bundling several user-facing products under a single OAuth\n * grant (e.g. the combined Google connector: Mail, Calendar, Tasks,\n * Contacts).\n *\n * Each {@link ProductInfo.scopeGroupId} must match an\n * {@link OptionalScopeGroup.id} declared in this connector's {@link scopes}\n * so the API can derive per-product enablement from granted scopes + enabled\n * channels.\n *\n * Leave undefined for plain (single-product) connectors — the API then omits\n * the `products`/`productStatus` response fields and the app uses the\n * standard per-connector flow.\n */\n readonly products?: ProductInfo[];\n\n /**\n * When true, this connector is mentioned by default on replies to threads it created.\n * When false (default), this connector cannot be mentioned at all.\n *\n * Set this to true for connectors with bidirectional sync (e.g., issue trackers,\n * messaging) where user replies should be written back to the external service.\n */\n static readonly handleReplies?: boolean;\n\n // ---- Account identity (abstract — every connector must implement) ----\n\n /**\n * Returns a human-readable name for the connected account.\n * Shown in the connections list and edit modal to identify this connection.\n *\n * For OAuth connectors, this is typically the workspace or organization name\n * (e.g., \"Acme Corp\" for a Linear workspace). For API key connectors, this\n * could be the workspace name from the external service.\n *\n * Override this in your connector to return a meaningful account name.\n *\n * @param auth - The authorization (null for no-provider connectors)\n * @param token - The access token (null for no-provider connectors)\n * @returns Promise resolving to the account display name\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n getAccountName(\n auth: Authorization | null,\n token: AuthToken | null\n ): Promise<string | null> {\n return Promise.resolve(null);\n }\n\n // ---- Channel lifecycle (abstract — every connector must implement) ----\n\n /**\n * Returns available channels for the authorized actor.\n * Called after OAuth is complete, during the setup/edit modal.\n *\n * @param auth - The completed authorization with provider and actor info\n * @param token - The access token for making API calls\n * @returns Promise resolving to available channels for the user to select\n */\n abstract getChannels(\n auth: Authorization | null,\n token: AuthToken | null\n ): Promise<Channel[]>;\n\n /**\n * Called when a channel resource is enabled for syncing.\n *\n * The framework dispatches this in three cases:\n * 1. **Initial enable** — user toggled the channel on for the first time.\n * 2. **Auto-enable** — `setChannels` discovered a new channel on a\n * connection with `auto_enable_new_channels` set.\n * 3. **Recovery after re-auth** — the user re-authorized a previously-\n * broken connection. The framework calls `onChannelEnabled` for every\n * channel that was already enabled at the time of re-auth, with\n * `context.recovering = true`. See {@link SyncContext.recovering}.\n *\n * Implementations should be **idempotent and overwrite stored state**:\n * the same channel may receive multiple `onChannelEnabled` calls across\n * its lifetime. Use unconditional `this.set()` writes rather than\n * coalesce/skip-if-present logic so a recovery dispatch wipes stale\n * cursors and state from the prior session.\n *\n * **Sync state tracking is automatic.** The framework stamps the\n * connection as \"syncing\" when it dispatches this method and clears\n * that state when:\n * - the connector calls `tools.integrations.channelSyncCompleted(id)`\n * once the initial backfill is done, OR\n * - this method throws an unhandled exception (auto-cleared so the UI\n * doesn't get stuck in \"syncing\" forever).\n *\n * **IMPORTANT: This method runs inline in the HTTP request handler.**\n * Any long-running work (webhook setup, API calls, sync) MUST be queued\n * as a separate task via `this.runTask()`, not executed inline. Blocking\n * here causes the client to spin waiting for the response.\n *\n * Only lightweight operations should appear directly in this method:\n * `this.set()`, `this.get()`, `this.callback()`, and `this.runTask()`.\n *\n * @example\n * ```typescript\n * async onChannelEnabled(channel: Channel, context?: SyncContext): Promise<void> {\n * // Recovery: drop stale cursors so the next sync re-walks history.\n * if (context?.recovering) {\n * await this.clear(`last_sync_token_${channel.id}`);\n * }\n *\n * await this.set(`sync_state_${channel.id}`, { channelId: channel.id });\n *\n * // Queue sync as a task — do NOT use this.run() or call sync methods inline\n * const syncCallback = await this.callback(this.syncBatch, 1, \"full\", channel.id, true);\n * await this.runTask(syncCallback);\n *\n * // Queue webhook setup as a task — do NOT call setupWebhook() inline\n * const webhookCallback = await this.callback(this.setupWebhook, channel.id);\n * await this.runTask(webhookCallback);\n * }\n * ```\n *\n * @param channel - The channel that was enabled\n * @param context - Optional sync context (plan-based hints, recovery flag)\n */\n abstract onChannelEnabled(channel: Channel, context?: SyncContext): Promise<void>;\n\n /**\n * Called when a channel resource is disabled.\n * Should stop sync, clean up webhooks, and remove state.\n *\n * @param channel - The channel that was disabled\n */\n abstract onChannelDisabled(channel: Channel): Promise<void>;\n\n // ---- Write-back hooks (optional, default no-ops) ----\n\n /**\n * Called when a link created by this connector is updated by the user.\n * Override to write back changes to the external service\n * (e.g., changing issue status in Linear when marked done in Plot).\n *\n * @param link - The updated link\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onLinkUpdated(link: Link): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a user creates a thread in Plot that should create a new\n * item in this connector's external system.\n *\n * A connector opts in to Plot-initiated creation by declaring a\n * `compose` block on the relevant `LinkTypeConfig` (see\n * {@link ComposeConfig}). When a user picks \"Create new <type>\" from the\n * Add link modal and the thread is synced, the runtime calls this method\n * with the draft fields.\n *\n * Implementations should create the item in the external service and\n * return a `NewLinkWithNotes` describing the created item. The platform\n * attaches the returned link to the originating thread — do not call\n * `integrations.saveLink` yourself.\n *\n * Returning `null` aborts creation silently (the thread is still saved\n * without a link).\n *\n * @param draft - The fields captured in Plot for the new item.\n * @returns The link to attach, or null to abort creation.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onCreateLink(draft: CreateLinkDraft): Promise<NewLinkWithNotes | null> {\n return Promise.resolve(null);\n }\n\n /**\n * Called when a note is created on a thread owned by this connector.\n * Override to write back comments to the external service\n * (e.g., adding a comment to a Linear issue).\n *\n * Returning a string or {@link NoteWriteBackResult} links the Plot note\n * to its external counterpart. A plain string sets the note's `key`.\n * A `NoteWriteBackResult` additionally sets a sync baseline (via\n * `externalContent`) so the next sync-in can recognize the round-tripped\n * content and preserve Plot's formatted version. See\n * {@link NoteWriteBackResult} for details.\n *\n * @param note - The created note\n * @param thread - The thread the note belongs to (includes thread.meta with connector-specific data)\n * @returns Optional note key or NoteWriteBackResult for external dedup + baseline tracking\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onNoteCreated(note: Note, thread: Thread): Promise<string | NoteWriteBackResult | void> {\n return Promise.resolve();\n }\n\n /**\n * Resolve a `fileRef` action's bytes for download. Called when a user opens\n * an attachment in Plot. Return either a redirect URL (preferred for sources\n * that issue signed URLs, like Linear S3 or Slack permalink_public) or a\n * streamed body (required when bytes are only reachable through an\n * authenticated API call, like Gmail attachments.get).\n *\n * @param ref Opaque value the connector previously emitted on a fileRef action.\n * @returns Either `{ redirectUrl }` or `{ body, mimeType, fileName? }`.\n * @throws If the source is unavailable, the connection is broken, or `ref` is invalid.\n *\n * If not overridden, fileRef actions on this connector's notes will return 410 Gone.\n */\n async downloadAttachment(\n ref: string,\n ): Promise<\n | { redirectUrl: string }\n | { body: ReadableStream | Uint8Array; mimeType: string; fileName?: string }\n > {\n throw new Error(\n `downloadAttachment not implemented for ${this.constructor.name} (ref=${ref})`,\n );\n }\n\n /**\n * Called when a note on a thread owned by this connector is updated.\n * Override to write back changes to the external service\n * (e.g., syncing reaction tags as emoji reactions, or editing a comment\n * whose content changed in Plot).\n *\n * Return a {@link NoteWriteBackResult} with `externalContent` to update\n * the sync baseline after a successful write-back, so the next sync-in\n * recognizes the external version as already-seen and preserves Plot's\n * content.\n *\n * @param note - The updated note (includes current tags)\n * @param thread - The thread the note belongs to (includes thread.meta with connector-specific data)\n * @returns Optional NoteWriteBackResult for baseline tracking\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onNoteUpdated(note: Note, thread: Thread): Promise<NoteWriteBackResult | void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a user reads or unreads a thread owned by this connector.\n * Override to write back read status to the external service\n * (e.g., marking an email as read in Gmail).\n *\n * @param thread - The thread that was read/unread (includes thread.meta with connector-specific data)\n * @param actor - The user who performed the action\n * @param unread - false when marked as read, true when marked as unread\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onThreadRead(thread: Thread, actor: Actor, unread: boolean): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a user changes the **thread-level sharing** of a thread owned\n * by this connector — adding or removing a contact, or (for connectors with\n * roles) changing a contact's role. Override on connectors whose external\n * source can reflect that membership change, e.g. a group DM / multi-party\n * chat (`LinkTypeConfig.sharingModel: \"thread\"`) or an email's To/Cc/Bcc\n * recipients (`sharingModel: \"message\"`). Connectors backed by an immutable\n * roster (most group DMs today) or by channel-level membership\n * (`sharingModel: \"channel\"`) leave this as the default no-op.\n *\n * `role`/`from`/`to` are **null** for connectors without roles (group DMs\n * have no roles); they carry a `contactRoles` id only for connectors that\n * declare roles (e.g. email `to`/`cc`/`bcc`).\n *\n * The dispatch fires after Plot has persisted the change. A connector may\n * reflect it actively (e.g. add/remove a participant on the external chat)\n * or passively on the next outbound note (e.g. building To/Cc/Bcc headers\n * from the current `thread.contacts` × `thread.contactMeta`) — this callback\n * is not the right place to send a standalone notification.\n *\n * @param thread - The thread whose contacts changed\n * @param changes - The added/removed contacts and any role transitions on existing contacts\n */\n /* eslint-disable @typescript-eslint/no-unused-vars */\n onContactsChanged(\n thread: Thread,\n changes: {\n added: Array<{ contact: Contact; role: string | null }>;\n removed: Array<{ contact: Contact; role: string | null }>;\n changed: Array<{ contact: Contact; from: string | null; to: string | null }>;\n },\n ): Promise<void> {\n return Promise.resolve();\n }\n /* eslint-enable @typescript-eslint/no-unused-vars */\n\n /**\n * Called when a user marks or unmarks a thread as todo.\n * Override to sync todo status to the external service\n * (e.g., starring an email in Gmail when marked as todo).\n *\n * @param thread - The thread (includes thread.meta with connector-specific data)\n * @param actor - The user who changed the todo status\n * @param todo - true when marked as todo, false when done or removed\n * @param options - Additional context\n * @param options.date - The todo date (when todo=true)\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onThreadToDo(thread: Thread, actor: Actor, todo: boolean, options: { date?: Date }): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a schedule contact's RSVP status changes on a thread owned by this connector.\n * Override to sync RSVP changes back to the external calendar.\n *\n * @param thread - The thread (includes thread.meta with connector-specific data)\n * @param scheduleId - The schedule ID\n * @param contactId - The contact whose status changed\n * @param status - The new RSVP status ('attend', 'skip', or null)\n * @param actor - The user who changed the status\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onScheduleContactUpdated(thread: Thread, scheduleId: string, contactId: ActorId, status: ScheduleContactStatus | null, actor: Actor): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a user adds or removes a single emoji reaction on a note\n * (one event per `(note, actor, emoji)` state transition).\n *\n * Dispatch is routed to the reacting user's own connector instance via\n * `twist_instance_for_actor` on `note_reaction.actor_id`, so this method\n * already runs under the reactor's auth. Fetch the API client with the\n * connector's normal token-fetch path (`this.tools.integrations.get(...)`)\n * and the external write — e.g. Slack `reactions.add` — will be attributed\n * to the correct user. No `actAs` step required.\n *\n * If the reacting user has no connection of this type, no dispatch fires\n * for that reaction (it stays in Plot only).\n *\n * Override to sync per-actor reactions back to the external system.\n *\n * @param note - The note that was reacted on (partial; `id`, `key`, `content` populated)\n * @param thread - The thread the note belongs to (partial; `id`, `title`, `archived`, `meta` populated)\n * @param actor - The contact who added/removed the reaction\n * @param emoji - The emoji (Unicode grapheme or `provider:workspace/name` custom-emoji ref)\n * @param added - `true` if the reaction is now present, `false` if it was removed\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n onNoteReactionChanged(note: Note, thread: Thread, actor: Actor, emoji: string, added: boolean): Promise<void> {\n return Promise.resolve();\n }\n\n // ---- Activation ----\n\n /**\n * Called when the connector is activated after OAuth is complete.\n *\n * Connectors receive the authorization in addition to the activating actor.\n * When this runs, `this.userId` is already populated with the installing\n * user's ID.\n *\n * Default implementation does nothing. Override for custom setup.\n *\n * @param context - The activation context\n * @param context.auth - The completed OAuth authorization\n * @param context.actor - The actor who activated the connector\n */\n // @ts-ignore - Connector.activate() has a Connector-specific context type.\n activate(context: { auth?: Authorization; actor?: Actor }): Promise<void> {\n return Promise.resolve();\n }\n}\n\n/** @deprecated Use `Connector` instead. */\nexport { Connector as Source };\n";
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Render Plot Markdown note content to HTML, for connectors that send the
3
+ * note out to a system whose native format is HTML email (Gmail, Outlook
4
+ * Mail). Kept separate from {@link markdownToPlainText} so connectors that
5
+ * only need the plain-text path don't pull the Markdown parser into their
6
+ * bundle (`sideEffects: false` lets the unused module tree-shake away).
7
+ */
8
+ import { marked } from "marked";
9
+
10
+ /**
11
+ * Convert Markdown to an HTML fragment suitable for an email body.
12
+ *
13
+ * - Plot mentions `[Name](#@UUID)` render as plain `@Name` text rather than a
14
+ * broken link to the internal `#@UUID` href.
15
+ * - GitHub-flavoured Markdown is enabled, and single newlines become `<br>`
16
+ * (`breaks: true`) so a message reads the way the author wrote it — the same
17
+ * convention chat-style products (Slack, GitHub comments) use.
18
+ *
19
+ * Returns an HTML fragment (e.g. `<p>…</p>`), not a full document; the caller
20
+ * wraps it for its transport (a `text/html` MIME part, a Graph `body`, etc.).
21
+ * Empty/blank input yields an empty string.
22
+ */
23
+ export function markdownToHtml(markdown: string | null | undefined): string {
24
+ if (!markdown || markdown.trim() === "") return "";
25
+
26
+ // Render mentions as "@Name" text before parsing so marked doesn't emit an
27
+ // anchor pointing at the internal "#@UUID" href.
28
+ const withMentions = markdown.replace(
29
+ /\[([^\]]+)\]\(#@[^)]+\)/g,
30
+ (_m, name: string) => `@${name}`
31
+ );
32
+
33
+ const html = marked.parse(withMentions, {
34
+ async: false,
35
+ gfm: true,
36
+ breaks: true,
37
+ });
38
+
39
+ return (html as string).trim();
40
+ }