The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
refactor(chat): extract delivery, reaction, and setup boundaries (#16024)
Dotta64bd6e9e0721
diff --git a/doc/plans/2026-10-12-chat-channel-delivery-boundaries-refactor.md b/doc/plans/2026-10-12-chat-channel-delivery-boundaries-refactor.mdnew file mode 100644index 0000000000..01a3fb22ef--- /dev/null+++ b/doc/plans/2026-10-12-chat-channel-delivery-boundaries-refactor.md@@ -0,0 +1,100 @@+# Chat channel callback and delivery boundaries, batch four++Base: 4b766b872993045a2e787404f0475503683e5ded. Batch three (#15995, #15996, #15999, #16001, #16002)+is merged. The service starts at 26,461 lines / 1,046,711 bytes.+This batch may create up to ten stacked PRs. Merging the new batch is separate work.++| Order / boundary | Destination | Approx. moved / net lines | Contract and state | Risks and existing verification |+| --- | --- | --- | --- | --- |+| 1. Slack callback verification | `slack/callback-verification.ts` | 250 / 230 | Pure signature/workspace/URL inspection plus signed URL verification; explicit vault lookup, URL getter, scheduling and registration callbacks | Preserve signing-secret-only setup, original request, TLS/proxy evidence and workspace checks. Signed verification and callback health cases before/after. |+| 2. Discord Gateway events | `discord/gateway-events.ts` | 200 / 185 | Runtime fence and lease-owner predicates, endpoint lookup and lifecycle callback; original per-runtime event queue and sequence | Preserve stale-owner fencing, event order, transient guild recovery and terminal revocation. Gateway lifecycle cases before/after. |+| 3. Discord root threads | `discord/root-threads.ts` | 500 / 460 | Credential lease, current principal authority, runtime, message admission and conversation drain callbacks | Preserve uncertain thread creation, restart reconciliation, no duplicate starter and pause/credential serialization. Root-thread public-service cases. |+| 4. Receipt reactions | `receipt-reactions.ts` and Slack error classifier beside Slack messages | 545 / 500 | Durable reaction claim/transport/settlement with runtime and credential fences; no scheduling owner moves | Preserve retries, legacy GitHub receipts, terminal-removal supersession and same-attempt settlement. Receipt recovery cases before/after. |+| 5. Inbound reactions | `reactions.ts` | 800 / 740 | Conversation lookup/locks, reaction admission and deferred replay together; current principal/runtime callbacks | Preserve exact event dedupe, completed generation links, bounded replay age and no task wakeup. Reaction race/restart/authorization cases. |+| 6. Inbound attachments | `inbound-attachments.ts` | 600 / 550 | Existing storage and issue service, retained source authorization and live options; return same attachment results | Preserve size limits, source authority around I/O, omissions and text delivery. Provider attachment/restart/stale-authority cases. |+| 7. Outbound attachments | `outbound-attachments.ts`; provider Markdown wrappers beside provider messages | 245 / 220 | Metadata validation and bounded integrity-checked hydration; existing storage object. Keep public hydration export compatible | Preserve stream cleanup, deadlines, byte/digest checks and retry classification. Hydration and publication attachment cases. |+| 8. Provider effects | `provider-effects.ts` | 950 / 850 | Durable reply claim, authorization, transport and settlement; endpoint/runtime/credential/principal callbacks | Preserve uncertain-delivery quarantine, credential fence and transaction ordering. Native callback, task-control and reply recovery cases. Put Telegram-only authority under `telegram/` if its contract is narrow. |+| 9. Conversation and activity reads | `activity.ts` | 540 / 520 | Endpoint lookup and read-only Teams conflict projection; return existing API models | Preserve company/endpoint joins, mixed-source cursor ties, replay eligibility and read-only GETs. Activity, file receipt projection and conversation-state cases. |+| 10. Setup probes | `setup-probes.ts` | 280 / 250 | Credential lease, current identity/principal authority, provider fetch, endpoint projection and live activation hook | Preserve real-message requirement, generation and linked-user activation. Setup-test, reconnect and authorization cases. |++Each slice must earn its place after reading its complete path and callers.+Reassess before implementation; stop short of ten if the remaining contracts are+not cohesive. Keep provider-specific code in channel folders and common durable+workflows in the shared chat-channels directory.++Receiver lease ownership stays shared: the existing Discord-named owner is also+used by Photon. Shared lifecycle/application admission, queue-drain ownership,+worker scheduling, and the largest action/message handlers remain in the service.+Do not hide their dependencies in a mutable context object. Preserve live option+hooks, runtime-map identity, partial-failure cleanup, and initialization order.++Run relevant existing public-service tests before and after each mechanical move.+Compare moved declarations and remaining statements with normalized syntax, then+run server types, module boundaries and whitespace checks. Finish local verification and a fresh+5/5 review before opening the next draft PR. GitHub runner-selection jobs remained+queued without steps for over 25 minutes in this batch. To continue the authorized+stack, publish drafts in review order while tracking CI as pending; CI remains a+merge gate. Run cumulative repository gates at handoff.+Retain failures and skipped/unrun coverage even when an isolated retry passes.+Use fixture-backed assembled service/database tests; do not claim live provider+execution. Remap LOC/bytes and the remaining orchestration after the batch.++## Slice 1: Slack callback verification++- Service: 26,461 lines / 1,046,711 bytes → 26,201 lines / 1,035,260 bytes.+- Destination: 299 lines / 13,038 bytes. Eight declarations move without body+ changes. Three existing setup types move unchanged into `runtime-types.ts`.+- The verification factory initializes after Slack registration. It receives the+ same registration object, credential resolver, live URL getter and scheduler.+ Signature/workspace/URL helpers remain callable by shared webhook orchestration.+- Nine public-service cases passed before and after on the updated master base.+ Server typecheck, module boundaries, whitespace and normalized syntax parity+ passed. Coverage includes signed URL verification, account notification,+ workspace rejection, callback surfaces, TLS termination and Cloud host evidence.+- Next: Discord Gateway event sequencing and health transitions. Keep shared+ receiver lease ownership and runtime-map lifetime in the service.++## Batch outcome++All ten candidates produced cohesive boundaries. Shared receiver ownership, queue+management and worker scheduling remain in the service. The only intentional+control-wiring change is deferred access to `stageProviderEffect` from identity+link construction; typecheck and integration tests caught the initial early read.++| Slice | Service lines after | Primary module lines | Before/after cases |+| --- | ---: | ---: | ---: |+| 1. Slack signature, workspace and callback url verification | 26,233 | 300 | 9 |+| 2. Discord gateway event sequencing and endpoint health transitions | 26,029 | 253 | 7 |+| 3. Discord root-thread admission, provider creation and durable recovery | 25,527 | 570 | 4 |+| 4. Durable receipt reaction claims, transport, retries and settlement | 24,975 | 586 | 7 |+| 5. Inbound reaction conversation lookup, admission and deferred replay | 24,160 | 891 | 21 |+| 6. Inbound attachment authorization, bounded ingestion, registration and omissions | 23,565 | 674 | 39 |+| 7. Outbound attachment metadata validation and bounded integrity-checked hydration | 23,298 | 294 | 22 |+| 8. Durable provider reply staging, authorization, transport and recovery | 22,331 | 957 | 24 |+| 9. Conversation summaries and paginated activity projections | 21,741 | 616 | 16 |+| 10. Setup message detection and credential-fenced round-trip qualification | 21,460 | 353 | 7 |++After rebasing on master `8e7b5db822`, the service shrank from+**26,493 lines / 1,048,769 bytes** to **21,460 lines /+862,284 bytes** (5,033 fewer lines, about 19%). Normalized syntax comparison+checks all 69 moved declarations/types and every remaining original statement.+Server types, targeted tests, module boundaries and whitespace checks are the+per-slice gates. Cumulative repository gates and remote reviews are recorded in+the PR descriptions as they complete.++Orchestration measurement: the service function has 150 nested functions+(19,399 lines) and 67 state/wiring statements (459 lines), versus 191 functions+(23,829 lines) and 54 statements (425 lines) at the start. Imports take 400 lines.+The remaining large paths are `processMessage` (2,166), `handleAction` (1,074),+`configureWithCredentialLease` (868), `processSelectedPublication` (729),+`handleModalSubmit` (708), `handleWebhook` (685), and lifecycle processing (657).++A future pass should inspect publication admission/transport/settlement as one+workflow, then inbound delivery authorization and drain ownership. Those cuts+need explicit ownership contracts; avoid separating individual checks from their+transactions merely to reduce the remaining line count.++The rebase preserves the merged managed Slack setup flow, including its shared+`isProvisionedSlackSetup` predicate in the extracted callback verification+module. A fresh syntax audit compares all moved declarations and retained+statement ordering with this updated master.diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.tsindex e107728079..6a302b30fd 100644--- a/server/src/services/chat-channels.ts+++ b/server/src/services/chat-channels.ts@@ -1,6 +1,22 @@import { slackTestMessageService } from "./connectors/slack/test-message.js";import type { SlackSetupOptions } from "./connectors/slack/setup/registration.js";import { isProvisionedSlackSetup } from "@paperclipai/shared";+import { createSetupProbes } from "./chat-channels/setup-probes.js";+import { createChatActivity, publicationSummary } from "./chat-channels/activity.js";+import { fileTransferProjectionColumns } from "./chat-channels/microsoft-teams/file-transfer-projection.js";+import { createProviderEffects, providerEffectPayload, type ProviderEffectTarget, type ProviderEffectPayload } from "./chat-channels/provider-effects.js";+import { createTelegramCallbackNoticeAuthority } from "./chat-channels/telegram/callback-notices.js";+import { createOutboundAttachments, isOutboundAttachmentHydrationError, isOutboundAttachmentValidationError } from "./chat-channels/outbound-attachments.js";+export { hydrateOutboundAttachment } from "./chat-channels/outbound-attachments.js";+import { discordMarkdownAttachment } from "./chat-channels/discord/messages.js";+import { telegramMarkdownAttachment } from "./chat-channels/telegram/messages.js";+import { createInboundAttachments } from "./chat-channels/inbound-attachments.js";+import { createInboundReactions } from "./chat-channels/reactions.js";+import { slackThreadChannelId } from "./chat-channels/slack/messages.js";+import { createReceiptReactions } from "./chat-channels/receipt-reactions.js";+import { createDiscordRootThreads } from "./chat-channels/discord/root-threads.js";+import { createDiscordGatewayEvents } from "./chat-channels/discord/gateway-events.js";+import { createSlackCallbackVerification, slackRequestSignatureIsValid, slackRequestWorkspaceId, canonicalCallbackUrl, slackCallbackMatchesPublicUrl, inspectSlackCallback } from "./chat-channels/slack/callback-verification.js";import { createTeamsFileAuthority } from "./chat-channels/microsoft-teams/file-transfer-authority.js";import { createPhotonEvents } from "./chat-channels/imessage-photon/events.js";import { createTelegramPublicationDrafts } from "./chat-channels/telegram/publication-drafts.js";@@ -8,10 +24,10 @@ import { createSlackFileReceipts } from "./chat-channels/slack/file-receipts.js"import { createSlackSessionStatus } from "./chat-channels/slack/session-status.js";import { createDiscordCommands } from "./chat-channels/discord/commands.js";import { createSlackTaskStart, slackSlashTaskRecoveryPayload, slackTaskStarterThreadId } from "./chat-channels/slack/task-start.js";-import { createGitHubWebhookIngress, GITHUB_RECOVERY_STATE_KEY, type GitHubIngressStageResult } from "./chat-channels/github/webhook-ingress.js";+import { createGitHubWebhookIngress, type GitHubIngressStageResult } from "./chat-channels/github/webhook-ingress.js";import { createSlackSessionStop } from "./chat-channels/slack/session-stop.js";import { createTelegramMaintenance } from "./chat-channels/telegram/maintenance.js";-import type { EndpointRow, DbTransaction, DbOrTransaction, RuntimeContext, LifecycleRuntimeFence, InboundRuntimeContext } from "./chat-channels/runtime-types.js";+import type { EndpointRow, DbTransaction, DbOrTransaction, RuntimeContext, LifecycleRuntimeFence, InboundRuntimeContext, SlackCallbackSurface, InternalSetupState } from "./chat-channels/runtime-types.js";import { createChatFailedRunRetry } from "./chat-channels/failed-run-retry.js";import { createChatPublicationReplacement } from "./chat-channels/publication-replacement.js";import { createChatIdentityLinks } from "./chat-channels/identity-links.js";@@ -51,7 +67,7 @@ import {type GitHubLifecycleEvent,githubLifecycleEventFromRequest,} from "./chat-channels/github/messages.js";-import { dueChatAction, nextChatActionAt, SLACK_COMMAND_POST_STALE_MS, SLACK_COMMAND_EXPLICIT_RETRY_STALE_MS, PROVIDER_EFFECT_STALE_MS } from "./chat-action-work.js";+import { dueChatAction, nextChatActionAt, SLACK_COMMAND_POST_STALE_MS, SLACK_COMMAND_EXPLICIT_RETRY_STALE_MS } from "./chat-action-work.js";import type { ScheduledChatAction } from "./chat-work-notifications.js";import { notifyChatDeliveryWork, notifyChatPublicationWork, notifyChatEndpointWork, notifyChatActionWork, notifyChatVerificationWork } from "./chat-work-notifications.js";import { syncSpekoVoiceTools } from "./voice/speko-agent-tools.js";@@ -64,9 +80,7 @@ import type { ChatEndpointRuntime } from "./voice/voice-runtime.js";import { parseMarkdown } from "chat";import { githubPublicAttachmentsFromMessage } from "./chat-github-attachments.js";import {- receiptReactionPayload,stageReceiptReactionRemovals,- type ReceiptReactionPayload,} from "./chat-receipt-reactions.js";import { fastResponseService, enqueueFastResponse, fastResponseSourceCurrent, fastResponseTurnQueued } from "./fast-responses.js";import { fastResponseRequests } from "@paperclipai/db";@@ -89,7 +103,7 @@ import { registerSlackTaskAuthority, slackRunOrigin } from "./connectors/slack-aimport { buildChatCommunicationGuidance } from "./chat-communication-guidance.js";function githubPolicyRecord(value: unknown): Record<string, unknown> { return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {}; }-import { githubChatManagementService } from "./chat-github-management.js";+import { githubReviewCheckService } from "./chat-github-checks.js";import {githubAutomaticReviewEvent,@@ -112,12 +126,12 @@ import { githubAppJwt } from "./chat-github-client.js";import { resumeExternalConversation } from "./slack-conversation-state.js";import { settleExternalConversation } from "./slack-conversation-lifecycle.js";import { runtimeCanonicalOrigin } from "./cloud-runtime-identity.js";-import { takePhotonCompanion } from "./photon/attachments.js";+import { writePhotonCheckpoint } from "./photon/receiver.js";import { PhotonState } from "./photon/state.js";-import { HEIF_CONTENT_TYPES, photonHeifPreview, validatePhotonImage } from "./photon/media.js";-import { projectSafeChatPublicationText } from "./chat-publication-projection.js";++import { nativePhotonInteraction, publishPhotonPrompt, type PhotonPromptReceipt, type PhotonInteractionBinding } from "./photon/interactions.js";@@ -139,7 +153,6 @@ import {desc,eq,gt,- gte,inArray,isNotNull,isNull,@@ -205,7 +218,6 @@ import type {ChatEndpointSetupState,ChatProvider,ChatPublicationBatchStatus,- ChatPublicationSummary,ConfigureChatEndpointInput,CreateChatEndpointInput,ExternalChannelBindingSummary,@@ -222,10 +234,8 @@ import {} from "@paperclipai/shared";import {formatAttachmentSize,- isAllowedContentType,MAX_ATTACHMENT_BYTES,normalizeContentType,- normalizeUploadAttachmentContentType,} from "../attachment-types.js";import { isUniqueViolation } from "../db-errors.js";import {@@ -239,24 +249,17 @@ import {import { projectTeamsFilePublication } from "./chat-teams-file-publication.js";import type { TeamsFileConsentEvent } from "./chat-teams-file-consent.js";import {- chatFileTransferResolutionActions,projectChatFileTransfer,projectChatPublicationBatch,} from "./chat-publication-batches.js";import { telegramAttachmentForUpload } from "./chat-telegram-photo.js";import {- parseTelegramCallbackReceipt,readTelegramCallbackProvenance,telegramCallbackThreadId,TELEGRAM_PRIVATE_ACTION_UNAVAILABLE,- type TelegramCallbackReceipt,} from "./chat-telegram-ephemeral.js";-import {- hasTelegramMediaProvenance,- identifyTelegramMedia,- telegramMediaNeedsIdentification,-} from "./chat-telegram-media-intake.js";+import { normalizeTelegramRichMessage } from "./chat-telegram-rich-intake.js";import {isTelegramDraftStopped,@@ -265,10 +268,7 @@ import {import { parseChatWebhookPublicBaseUrl } from "../chat-webhook-public-url.js";-import {- parseGitHubReceiptIdentity,- type GitHubReceiptIdentity,-} from "./chat-github-receipt-reactions.js";+import {badRequest,HttpError,@@ -281,14 +281,12 @@ import { logger } from "../middleware/logger.js";import { redactSensitiveText } from "../redaction.js";import type { StorageService } from "../storage/types.js";import {- DiscordAdapterCompatibilityError,type ChatSdkCallbackEvent,type ChatSdkMessageCallbackEvent,type ChatSdkMessageUpdatedCallbackEvent,type ChatSdkProvider,type ChatSdkRuntime,type DiscordGatewayCallbackEvent,- type DiscordRootMentionAdmissionEvent,type ResolvedChatSdkProviderConfig,type SlackFileUploadAcceptedReceipt,} from "./chat-sdk-runtime.js";@@ -322,10 +320,7 @@ import {requestGitHubAppWebhookRedelivery,} from "./chat-github-webhook-config.js";import {- GITHUB_ATTACHMENT_BATCH_TIMEOUT_MS,- GitHubAttachmentUnavailableError,githubAttachmentLimitOmissions,- prepareGitHubPublicAttachment,restoreGitHubAttachmentLimitOmissions,} from "./chat-github-attachments.js";import { getExternalChannelBindingSummary } from "./chat-channel-binding.js";@@ -383,9 +378,7 @@ import {normalizeMicrosoftTeamsCredentialIds,} from "./chat-teams-credentials.js";import {- isTeamsInlineImageContentType,prepareTeamsInlineImage,- TEAMS_INLINE_IMAGE_MAX_BYTES,} from "./chat-teams-inline-images.js";import {shouldStreamSafePublicationText,@@ -419,44 +412,11 @@ import type {MessageDeletedEvent,ModalResponse,ModalSubmitEvent,- ReactionEvent,SlashCommandEvent,Thread,} from "chat";import { Actions, Button, Card, CardText, LinkButton } from "chat";-// Only these closed fields may reach Activity or a delivery-batch response.-// The resolution predicate yields one boolean, never the private envelope.-const fileTransferProjectionColumns = {- publicationId: chatTeamsFileTransfers.publicationId,- phase: chatTeamsFileTransfers.phase,- version: chatTeamsFileTransfers.version,- filename: chatTeamsFileTransfers.filename,- expiresAt: chatTeamsFileTransfers.expiresAt,- consentMessageId: chatTeamsFileTransfers.consentMessageId,- responseActivityId: chatTeamsFileTransfers.responseActivityId,- fileInfoMessageId: chatTeamsFileTransfers.fileInfoMessageId,- operatorConfirmed: sql<boolean>`- coalesce(${chatTeamsFileTransfers.privateState}#>>'{resolution,schema}', '') = 'paperclip.teams.file-resolution.v1'- and coalesce(${chatTeamsFileTransfers.privateState}#>>'{resolution,action}', '') = 'mark_delivered'- and coalesce(${chatTeamsFileTransfers.privateState}#>>'{resolution,fromPhase}', '') = 'file_info_unknown'- `,-};--function publicationSummary(- row: typeof chatPublications.$inferSelect,-): ChatPublicationSummary {- return {- id: row.id,- state: row.state,- providerUrl: row.providerUrl,- attempts: row.attempts,- redactedError: row.redactedError,- nextAttemptAt: row.nextAttemptAt?.toISOString() ?? null,- publishedAt: row.publishedAt?.toISOString() ?? null,- };-}-const PROVIDER_LABELS: Record<ChatProvider, string> = {speko: "Speko","imessage-photon": "iMessage Photon",@@ -494,207 +454,6 @@ function publicationPrecedes();}-function slackRequestSignatureIsValid(- request: Request,- body: string,- signingSecret: string,-): boolean {- const timestamp = request.headers.get("x-slack-request-timestamp");- const signature = request.headers.get("x-slack-signature");- if (!timestamp || !signature) return false;- const timestampSeconds = Number(timestamp);- if (- !Number.isFinite(timestampSeconds) ||- Math.abs(Math.floor(Date.now() / 1000) - timestampSeconds) > 300- )- return false;- const expected = `v0=${createHmac("sha256", signingSecret).update(`v0:${timestamp}:${body}`).digest("hex")}`;- try {- return timingSafeEqual(Buffer.from(signature), Buffer.from(expected));- } catch {- return false;- }-}--function slackRequestWorkspaceId(- body: string,- contentType: string,-): string | null {- let payload: unknown;- try {- if (contentType.includes("application/json")) {- payload = JSON.parse(body);- } else {- const form = new URLSearchParams(body);- const interactivePayload = form.get("payload");- payload = interactivePayload- ? JSON.parse(interactivePayload)- : Object.fromEntries(form.entries());- }- } catch {- return null;- }- if (!payload || typeof payload !== "object") return null;- const record = payload as Record<string, unknown>;- const nestedId = (value: unknown): string | null => {- if (!value || typeof value !== "object") return null;- const id = (value as Record<string, unknown>).id;- return typeof id === "string" && id.length > 0 ? id : null;- };- const stringField = (key: string): string | null => {- const value = record[key];- return typeof value === "string" && value.length > 0 ? value : null;- };- const authorization = Array.isArray(record.authorizations)- ? record.authorizations.find(- (value): value is Record<string, unknown> =>- Boolean(value) && typeof value === "object",- )- : null;- const authorizationField = (key: string): string | null => {- const value = authorization?.[key];- return typeof value === "string" && value.length > 0 ? value : null;- };-- // A Grid event may carry both an enterprise id and the concrete workspace- // id. The bot identity is verified against auth.test's team_id, so prefer a- // team id and use the enterprise id only when Slack omitted team context.- return (- stringField("team_id") ??- nestedId(record.team) ??- authorizationField("team_id") ??- stringField("enterprise_id") ??- nestedId(record.enterprise) ??- authorizationField("enterprise_id")- );-}--function canonicalCallbackUrl(value: string): string | null {- try {- const url = new URL(value);- if (url.protocol !== "https:" && url.protocol !== "http:") return null;- url.hostname = url.hostname.replace(/\.$/, "");- url.username = "";- url.password = "";- url.search = "";- url.hash = "";- return url.toString();- } catch {- return null;- }-}--// TLS terminates at a reverse proxy in many self-hosted deployments. The-// transport scheme is not evidence of URL drift; authority and path still are.-// This is diagnostic only: it does not trust forwarded headers or change auth.-function slackCallbackMatchesPublicUrl(observed: string, current: string): boolean {- const canonical = canonicalCallbackUrl(observed);- if (canonical === current) return true;- if (!canonical) return false;- const observedUrl = new URL(canonical);- const currentUrl = new URL(current);- return observedUrl.protocol === "http:"- && currentUrl.protocol === "https:"- && observedUrl.host === currentUrl.host- && observedUrl.pathname === currentUrl.pathname;-}--type SlackCallbackInspection = {- surface: SlackCallbackSurface;- url: string;- isUrlVerification: boolean;-};--// Cloud records the public request host in dedicated headers so provider edges-// cannot replace it with their upstream host. Only use callback-health evidence on a-// claimed Cloud instance, after provider authentication succeeded. It must not-// change the Request passed to the adapter, signature verification, routing,-// board identity, or the configured URL used to generate callbacks.-function slackCallbackObservationUrl(request: Request): string | null {- const directUrl = canonicalCallbackUrl(request.url);- if (!directUrl || !runtimeCanonicalOrigin()) return directUrl;- const hasCloudEvidence = request.headers.has("x-paperclip-cloud-forwarded-host");- const host = request.headers.get(hasCloudEvidence ? "x-paperclip-cloud-forwarded-host" : "x-forwarded-host")?.trim();- const protocol = request.headers.get(hasCloudEvidence ? "x-paperclip-cloud-forwarded-proto" : "x-forwarded-proto")?.trim();- if (!host || /[\s/@\\?#,]/.test(host) || (protocol !== "https" && protocol !== "http")) return directUrl;- try {- const origin = new URL(`${protocol}://${host}`);- // Accept one authority only, never credentials, paths, queries, or lists.- if (!origin.host || origin.username || origin.password || origin.pathname !== "/" || origin.search || origin.hash) return directUrl;- const observed = new URL(directUrl);- observed.protocol = origin.protocol;- observed.host = origin.host;- observed.port = origin.port;- return canonicalCallbackUrl(observed.toString());- } catch {- return directUrl;- }-}--async function inspectSlackCallback(- request: Request,-): Promise<SlackCallbackInspection | null> {- const url = slackCallbackObservationUrl(request);- if (!url) return null;- const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";- let body: string;- try {- body = await request.text();- } catch {- return null;- }- if (contentType.includes("application/json")) {- try {- const payload = JSON.parse(body) as {- type?: unknown;- challenge?: unknown;- };- const isUrlVerification =- payload.type === "url_verification" &&- typeof payload.challenge === "string" &&- payload.challenge.length > 0;- if (isUrlVerification || payload.type === "event_callback") {- return {- surface: "events",- url,- isUrlVerification,- };- }- } catch {- return null;- }- return null;- }-- const form = new URLSearchParams(body);- if (form.get("command")) {- return { surface: "slashCommands", url, isUrlVerification: false };- }- const interactivePayload = form.get("payload");- if (!interactivePayload) return null;- try {- const payload = JSON.parse(interactivePayload) as { type?: unknown };- if (- typeof payload.type === "string" &&- [- "block_actions",- "block_suggestion",- "dialog_submission",- "message_action",- "shortcut",- "view_closed",- "view_submission",- "workflow_step_edit",- ].includes(payload.type)- ) {- return { surface: "interactivity", url, isUrlVerification: false };- }- } catch {- return null;- }- return null;-}-const CAPABILITIES: Record<ChatProvider, ChatAdapterCapabilities> = {speko: { threads: false, directMessages: true, nativeStreaming: false, messageEdits: false, messageDeletes: false, reactions: false, files: false, cards: false, actions: false, modals: false, slashCommands: false, ephemeralMessages: false, proactiveDirectMessages: false },"imessage-photon": { threads: false, directMessages: true, nativeStreaming: false, messageEdits: true, messageDeletes: false, reactions: false, files: true, cards: false, actions: true, modals: false, slashCommands: false, ephemeralMessages: false, proactiveDirectMessages: false },@@ -841,13 +600,6 @@ const SUPPLIED_CREDENTIAL_KEYS: Record<ChatProvider, readonly string[]> = {const MAX_ERROR_TEXT = 2_000;const DELIVERY_PROCESSING_STALE_MS = 60_000;-// Reactions can beat the transaction that persists a just-sent provider-// message link. Keep that narrow gap durable, but never retain an unbound-// reaction indefinitely or let it enter the ordinary inbound-message FIFO.-const REACTION_LINK_RETRY_DELAY_MS = 250;-const REACTION_LINK_MAX_DELAY_MS = 5_000;-const REACTION_LINK_MAX_ATTEMPTS = 20;-const REACTION_LINK_MAX_AGE_MS = 2 * 60_000;// A Discord root mention is durably staged before the adapter creates its// provider thread. Give the bounded provider retry loop ample time to finish;// if the process disappears, the delivery worker verifies that thread over@@ -887,17 +639,6 @@ const INGRESS_REORDER_WINDOW_MS: Partial<Record<ChatProvider, number>> = {telegram: 750,};type ResourceRow = typeof chatEndpointResources.$inferSelect;-type SlackCallbackSurface = keyof ChatEndpointCallbackSurfaces;-type SlackCallbackObservation = { url: string; observedAt: string };-type InternalSetupState = ChatEndpointSetupState & {- photonIntakeAfter?: string;- runtimeGeneration?: number;- /** Binds pre-install URL verification to the signing secret later configured. */- slackVerificationSigningFingerprint?: string;- slackCallbackSurfaces?: Partial<- Record<SlackCallbackSurface, SlackCallbackObservation>- >;-};type VerifiedProviderIdentity = {githubOwnerType?: "personal" | "organization";githubOwnerLogin?: string;@@ -1054,130 +795,6 @@ type LiveInboundMessage = {thread: Thread;trigger: ChatSdkMessageCallbackEvent["trigger"];};-type ProviderEffectTarget = {- post: Thread["post"];- postEphemeral?: Thread["postEphemeral"];-};-type ProviderEffectPayload = {- version: 1;- effect: "thread_message" | "ephemeral_message" | "telegram_callback_notice";- telegramCallback?: TelegramCallbackReceipt;- telegramAuthorizationSha256?: string;- authorizationMode?: "principal" | "safe_notice";- threadId: string;- userId?: string;- text: string;- fallbackText?: string;- settleDelivery: boolean;- completeConversationId?: string;- resourceId?: string;- runtimeGeneration: number;- credentialFingerprint: string;-};--function isSlackReceiptReactionAlreadyApplied(error: unknown): boolean {- const pending: Array<{ depth: number; value: unknown }> = [- { depth: 0, value: error },- ];- const seen = new Set<object>();- while (pending.length > 0) {- const current = pending.shift();- if (- !current ||- current.depth > 4 ||- !current.value ||- typeof current.value !== "object" ||- seen.has(current.value)- ) {- continue;- }- seen.add(current.value);- const record = current.value as {- cause?: unknown;- code?: unknown;- data?: { error?: unknown };- original?: unknown;- originalError?: unknown;- };- if (- record.code === "already_reacted" ||- record.data?.error === "already_reacted"- ) {- return true;- }- for (const value of [record.cause, record.original, record.originalError]) {- pending.push({ depth: current.depth + 1, value });- }- }- return false;-}--function providerEffectPayload(- payload: Record<string, unknown>,-): ProviderEffectPayload | null {- if (- payload.version !== 1 ||- (payload.effect !== "thread_message" &&- payload.effect !== "ephemeral_message" &&- payload.effect !== "telegram_callback_notice") ||- typeof payload.threadId !== "string" ||- !payload.threadId ||- typeof payload.text !== "string" ||- !payload.text ||- typeof payload.settleDelivery !== "boolean" ||- typeof payload.runtimeGeneration !== "number" ||- !Number.isSafeInteger(payload.runtimeGeneration) ||- typeof payload.credentialFingerprint !== "string"- ) {- return null;- }- if (- payload.effect === "ephemeral_message" &&- (typeof payload.userId !== "string" || !payload.userId)- ) {- return null;- }- for (const key of [- "authorizationMode",- "userId",- "fallbackText",- "completeConversationId",- "resourceId",- ] as const) {- const value = payload[key];- if (value !== undefined && (typeof value !== "string" || !value)) {- return null;- }- }- if (- payload.authorizationMode !== undefined &&- payload.authorizationMode !== "principal" &&- payload.authorizationMode !== "safe_notice"- ) {- return null;- }- if (payload.effect === "telegram_callback_notice") {- const receipt = parseTelegramCallbackReceipt(payload.telegramCallback);- if (- !receipt ||- payload.authorizationMode !== "safe_notice" ||- payload.text !== TELEGRAM_PRIVATE_ACTION_UNAVAILABLE ||- payload.threadId !== telegramCallbackThreadId(receipt) ||- payload.userId !== receipt.receiverUserId ||- payload.settleDelivery !== false ||- payload.fallbackText !== undefined ||- payload.completeConversationId !== undefined ||- typeof payload.telegramAuthorizationSha256 !== "string" ||- !/^[a-f0-9]{64}$/.test(payload.telegramAuthorizationSha256)- )- return null;- } else if (- payload.telegramCallback !== undefined ||- payload.telegramAuthorizationSha256 !== undefined- )- return null;- return payload as ProviderEffectPayload;-}export interface ChatChannelServiceOptions {/**@@ -1489,15 +1106,6 @@ function safeTitle(text: string, fallback: string): string {return (line || fallback).slice(0, 160);}-function slackThreadChannelId(threadId: string): string | null {- if (!threadId.startsWith("slack:")) return null;- const channelAndThread = threadId.slice("slack:".length);- const separator = channelAndThread.indexOf(":");- const channelId =- separator === -1 ? channelAndThread : channelAndThread.slice(0, separator);- return channelId || null;-}-function actionThreadMatchesConversation(provider: ChatProvider,actionThreadId: string,@@ -1514,24 +1122,6 @@ function actionThreadMatchesConversation();}-function slackTaskStartActivityStatus(action: {- status: string;- updatedAt: Date;-}): string {- const age = Date.now() - action.updatedAt.getTime();- if (action.status === "validating" && age >= SLACK_COMMAND_POST_STALE_MS) {- return "queued";- }- if (- (action.status === "received" && age >= SLACK_COMMAND_POST_STALE_MS) ||- (action.status === "resolving" &&- age >= SLACK_COMMAND_EXPLICIT_RETRY_STALE_MS)- ) {- return "delivery_unknown";- }- return action.status;-}-function sanitizeFilename(value: string | undefined): string | null {if (!value) return null;const leaf = value.replaceAll("\\", "/").split("/").pop()?.trim();@@ -1821,163 +1411,6 @@ export function createChatSdkStatePersistence(db: Db): ChatSdkStatePersistence {};}-const OUTBOUND_ATTACHMENT_STORAGE_TIMEOUT_MS = 10_000;--class OutboundAttachmentHydrationError extends Error {- readonly code = "CHAT_ATTACHMENT_HYDRATION_FAILED";-- constructor(message: string, cause?: unknown) {- super(message, cause === undefined ? undefined : { cause });- this.name = "OutboundAttachmentHydrationError";- }-}--class OutboundAttachmentValidationError extends Error {- readonly code = "CHAT_ATTACHMENT_VALIDATION_FAILED";-- constructor(message: string) {- super(message);- this.name = "OutboundAttachmentValidationError";- }-}--function isOutboundAttachmentHydrationError(- error: unknown,-): error is OutboundAttachmentHydrationError {- return error instanceof OutboundAttachmentHydrationError;-}--function isOutboundAttachmentValidationError(- error: unknown,-): error is OutboundAttachmentValidationError {- return error instanceof OutboundAttachmentValidationError;-}--/**- * Read one already-authorized attachment before any provider transport starts.- * The database digest, rather than mutable object-store metadata, is the- * integrity boundary. Both acquisition and streaming are bounded so a stuck- * storage backend cannot hold the publication lane indefinitely.- */-export async function hydrateOutboundAttachment(input: {- storage: StorageService;- companyId: string;- objectKey: string;- byteSize: number;- sha256: string;- filename: string;- mimeType: string;- timeoutMs?: number;-}): Promise<FileUpload> {- const timeoutMs =- typeof input.timeoutMs === "number" &&- Number.isFinite(input.timeoutMs) &&- input.timeoutMs > 0- ? input.timeoutMs- : OUTBOUND_ATTACHMENT_STORAGE_TIMEOUT_MS;- if (- !Number.isSafeInteger(input.byteSize) ||- input.byteSize <= 0 ||- input.byteSize > MAX_ATTACHMENT_BYTES ||- !/^[0-9a-f]{64}$/iu.test(input.sha256)- ) {- throw new OutboundAttachmentHydrationError(- "Chat publication attachment metadata is invalid",- );- }- const acquisitionTimeoutError = new OutboundAttachmentHydrationError(- "Chat publication attachment storage read timed out",- );- let acquisitionTimedOut = false;- let rejectAcquisition!: (error: Error) => void;- const acquisitionTimeout = new Promise<never>((_resolve, reject) => {- rejectAcquisition = reject;- });- const acquisitionTimer = setTimeout(() => {- acquisitionTimedOut = true;- rejectAcquisition(acquisitionTimeoutError);- }, timeoutMs);- acquisitionTimer.unref?.();- const objectPromise = Promise.resolve()- .then(() => input.storage.getObject(input.companyId, input.objectKey))- .then((object) => {- if (acquisitionTimedOut) object.stream.destroy();- return object;- })- .catch((error) => {- throw isOutboundAttachmentHydrationError(error)- ? error- : new OutboundAttachmentHydrationError(- "Chat publication attachment storage read failed",- error,- );- });- let object: Awaited<ReturnType<StorageService["getObject"]>>;- try {- object = await Promise.race([objectPromise, acquisitionTimeout]);- } finally {- clearTimeout(acquisitionTimer);- }-- if (- object.contentLength !== undefined &&- object.contentLength !== input.byteSize- ) {- object.stream.destroy();- throw new OutboundAttachmentHydrationError(- "Chat publication attachment size changed after registration",- );- }-- const streamTimeoutError = new OutboundAttachmentHydrationError(- "Chat publication attachment storage read timed out",- );- const streamTimer = setTimeout(() => {- object.stream.destroy(streamTimeoutError);- }, timeoutMs);- streamTimer.unref?.();- const chunks: Buffer[] = [];- const digest = createHash("sha256");- let bytes = 0;- try {- for await (const chunk of object.stream) {- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);- bytes += buffer.length;- if (bytes > input.byteSize || bytes > MAX_ATTACHMENT_BYTES) {- object.stream.destroy();- throw new OutboundAttachmentHydrationError(- "Chat publication attachment exceeded its streaming byte limit",- );- }- digest.update(buffer);- chunks.push(buffer);- }- } catch (error) {- throw isOutboundAttachmentHydrationError(error)- ? error- : new OutboundAttachmentHydrationError(- "Chat publication attachment storage read failed",- error,- );- } finally {- clearTimeout(streamTimer);- }-- const actualDigest = digest.digest("hex");- if (bytes !== input.byteSize || actualDigest !== input.sha256.toLowerCase()) {- if (!object.stream.destroyed) object.stream.destroy();- throw new OutboundAttachmentHydrationError(- "Chat publication attachment integrity changed after registration",- );- }-- return {- data: Buffer.concat(chunks, bytes),- filename: input.filename,- mimeType: input.mimeType,- };-}-export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {const runtime = options.runtime ?? createChatRuntime();const githubManualMessages = new WeakMap<object, { policy: GitHubReviewPolicy; revision: number; event: "mention" | "comment" }>();@@ -2009,7 +1442,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {// An explicit webhook ingress remains separate from board/identity links.const getPublicBaseUrl = () => runtimeCanonicalOrigin() ?? configuredPublicBaseUrl;const { listPrincipals, createLinkIntent, previewIdentityLink, requestIdentityAccess, confirmIdentityLink, revokeLink } = createChatIdentityLinks(db, {- endpointRecord, getPublicBaseUrl, stageProviderEffect, scheduleProviderEffect,+ endpointRecord, getPublicBaseUrl, stageProviderEffect: (...args) => stageProviderEffect(...args), scheduleProviderEffect,confirmationRuntimeFor: async (endpoint) => runtimeContexts.get((await runtimeFor(endpoint)) as object),});// Task links must validate the original configured URL before normalization@@ -2459,67 +1892,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {);}- async function addReceiptReaction(input: {- deliveryId: string;- endpoint: EndpointRow;- message: Message;- runtimeContext?: LifecycleRuntimeFence;- thread: Thread;- }): Promise<void> {- // GitHub acknowledges through one editable response comment. Continue to- // drain legacy eyes removals, but never create new eyes for these requests.- if (input.endpoint.provider === "github") return;- const record = await endpointRecord(input.endpoint.id);- if (!record) return;- // A live SDK object remains bound to the credentials that authenticated- // its callback. Preserve that original fence rather than sampling the- // endpoint again after a rotation and accidentally blessing an obsolete- // adapter with the new generation.- const context = input.runtimeContext ?? runtimeContextForRecord(record);- const [inserted] = await db.transaction(async (tx) => {- await notifyChatActionWork(tx, "receipt_reaction");- return tx- .insert(chatActions)- .values({- companyId: input.endpoint.companyId,- endpointId: input.endpoint.id,- deliveryId: input.deliveryId,- kind: "receipt_reaction",- providerActionId: `receipt_reaction:${input.deliveryId}`,- payload: {- version: 1,- operation: "add",- threadId: input.thread.id,- messageId: input.message.id,- reaction: "eyes",- runtimeGeneration: context.generation,- credentialFingerprint: context.credentialFingerprint,- } satisfies ReceiptReactionPayload,- status: "received",- })- .onConflictDoNothing()- .returning({ id: chatActions.id });- });- const actionId =- inserted?.id ??- (await db- .select({ id: chatActions.id })- .from(chatActions)- .where(- and(- eq(chatActions.endpointId, input.endpoint.id),- eq(- chatActions.providerActionId,- `receipt_reaction:${input.deliveryId}`,- ),- ),- )- .then((rows) => rows[0]?.id ?? null));- if (!actionId) return;- await options.receiptReactionTransportBarrier?.();- await processReceiptReaction(actionId);- }-function conversationDrainKey(endpointId: string, threadId: string) {return `${endpointId}:${createHash("sha256").update(durableExternalThreadIdentity(threadId)).digest("hex")}`;}@@ -2588,506 +1960,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {.then((rows) => rows[0] ?? null);}- async function processReceiptReaction(actionId: string): Promise<void> {- const initialAction = await db- .select({ endpointId: chatActions.endpointId })- .from(chatActions)- .where(- and(- eq(chatActions.id, actionId),- eq(chatActions.kind, "receipt_reaction"),- ),- )- .then((rows) => rows[0] ?? null);- if (!initialAction) return;- const initialEndpoint = await endpointRecord(initialAction.endpointId);- if (!initialEndpoint) return;- // Receipt reactions are GitHub repository mutations too. Serialize their- // final runtime-fence check and provider call with reconnect, secret- // rotation, pause, and removal so credentials cannot become obsolete- // between authorization and transport.- await withCredentialMutationLease(initialEndpoint.endpoint, (lease) =>- processReceiptReactionWithCredentialLease(actionId, lease),- );- }-- async function processReceiptReactionWithCredentialLease(- actionId: string,- credentialLease: CredentialMutationLeaseGuard,- ): Promise<void> {- let action = await db- .select()- .from(chatActions)- .where(- and(- eq(chatActions.id, actionId),- eq(chatActions.kind, "receipt_reaction"),- ),- )- .then((rows) => rows[0] ?? null);- if (!action || ["processed", "cancelled"].includes(action.status)) return;- const payload = receiptReactionPayload(action.payload);- if (!payload) {- await db.transaction(async (tx) => {- await notifyChatActionWork(tx, "receipt_reaction");- return tx- .update(chatActions)- .set({- status: "failed",- result: {- code: "receipt_reaction_payload_invalid",- retryable: false,- },- updatedAt: new Date(),- })- .where(eq(chatActions.id, action.id));- });- return;- }- if (payload.operation === "add" && action.deliveryId) {- const terminalRemoval = await db- .select({ id: chatActions.id })- .from(chatActions)- .where(- and(- eq(chatActions.endpointId, action.endpointId),- eq(- chatActions.providerActionId,- `receipt_reaction_remove:${action.deliveryId}`,- ),- ),- )- .then((rows) => rows[0] ?? null);- if (terminalRemoval) {- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- await notifyChatActionWork(tx, "receipt_reaction");- await tx- .update(chatActions)- .set({- status: "cancelled",- result: {- ...(typeof action!.result?.attempts === "number"- ? { attempts: action!.result.attempts }- : {}),- code: "receipt_reaction_superseded_by_terminal_publication",- },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, action!.id),- eq(chatActions.status, action!.status),- ),- );- await credentialLease.assertOwned(tx);- });- return;- }- }- if (action.status === "processing") {- if (action.updatedAt > new Date(Date.now() - PROVIDER_EFFECT_STALE_MS))- return;- // Adding or removing the same reaction is idempotent. A worker- // interruption can be retried safely without an ambiguous- // duplicate-message boundary.- await db.transaction(async (tx) => {- await notifyChatActionWork(tx, "receipt_reaction");- return tx- .update(chatActions)- .set({- status: "failed",- result: {- ...(action.result ?? {}),- retryable: true,- retryAt: new Date().toISOString(),- },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, action.id),- eq(chatActions.status, "processing"),- eq(chatActions.updatedAt, action.updatedAt),- ),- );- });- action = await db- .select()- .from(chatActions)- .where(eq(chatActions.id, action.id))- .then((rows) => rows[0] ?? null);- if (!action) return;- }- if (action.status === "failed") {- if (action.result?.retryable !== true) return;- const retryAt =- typeof action.result.retryAt === "string"- ? new Date(action.result.retryAt)- : null;- if (retryAt && retryAt > new Date()) return;- } else if (action.status !== "received") {- return;- }- const attempt =- (typeof action.result?.attempts === "number" ? action.result.attempts : 0) +- 1;- const retainedGitHubReceipt = parseGitHubReceiptIdentity(- action.result?.githubReceipt,- );- const [claimed] = await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- await notifyChatActionWork(tx, "receipt_reaction");- const rows = await tx- .update(chatActions)- .set({- status: "processing",- result: {- attempts: attempt,- ...(retainedGitHubReceipt- ? { githubReceipt: retainedGitHubReceipt }- : {}),- },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, action!.id),- eq(chatActions.status, action!.status),- ),- )- .returning();- await credentialLease.assertOwned(tx);- return rows;- });- if (!claimed) return;-- let reactionProvider: ChatProvider | null = null;- let githubReceipt: GitHubReceiptIdentity | null = retainedGitHubReceipt;- try {- const record = await endpointRecord(action.endpointId);- if (- !record ||- !["verifying", "active"].includes(record.endpoint.status) ||- runtimeGeneration(record.endpoint.setup) !== payload.runtimeGeneration ||- credentialFingerprint(record.credentialSecretRefs) !==- payload.credentialFingerprint- ) {- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- await notifyChatActionWork(tx, "receipt_reaction");- await tx- .update(chatActions)- .set({- status: "cancelled",- result: {- attempts: attempt,- code: "receipt_reaction_runtime_superseded",- },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, action!.id),- eq(chatActions.status, "processing"),- sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,- ),- );- await credentialLease.assertOwned(tx);- });- return;- }- reactionProvider = record.endpoint.provider;- // Resolve the adapter only after acquiring the credential lease and- // proving the action's durable generation/fingerprint is still current.- // Never reuse the live callback's adapter: it may hold an installation- // token minted by a superseded private key.- const endpointRuntime = await runtimeFor(record.endpoint);- const adapter = endpointRuntime.thread(payload.threadId).adapter;- await credentialLease.assertOwned();- if (record.endpoint.provider === "slack") {- await endpointRuntime.applySlackReceiptReaction(payload, fetchImpl);- } else if (record.endpoint.provider === "github") {- const assertCurrent = async () => {- await credentialLease.assertOwned();- const [current] = await db- .select({ endpoint: chatEndpoints, connection: toolConnections })- .from(chatEndpoints)- .innerJoin(- toolConnections,- and(- eq(toolConnections.id, chatEndpoints.connectionId),- eq(toolConnections.companyId, chatEndpoints.companyId),- ),- )- .where(- and(- eq(chatEndpoints.id, action!.endpointId),- eq(chatEndpoints.companyId, action!.companyId),- ),- )- .limit(1);- if (- !current ||- !["active", "verifying"].includes(current.endpoint.status) ||- !current.connection.enabled ||- current.connection.status !== "active" ||- runtimeGeneration(current.endpoint.setup) !==- payload.runtimeGeneration ||- credentialFingerprint(current.connection.credentialSecretRefs) !==- payload.credentialFingerprint ||- runtime.get(action!.endpointId) !== endpointRuntime- )- throw new Error("GitHub receipt authority is no longer current");- };- const applied = await endpointRuntime.applyGitHubReceiptReaction(- { ...payload, ...(githubReceipt ? { githubReceipt } : {}) },- assertCurrent,- fetchImpl,- );- githubReceipt = parseGitHubReceiptIdentity(applied);- if (- !githubReceipt ||- (payload.operation === "add" && !githubReceipt.reactionId)- )- throw new Error("GitHub receipt identity was not confirmed");- } else if (payload.operation === "remove") {- await adapter.removeReaction(- payload.threadId,- payload.messageId,- payload.reaction,- );- } else {- await adapter.addReaction(- payload.threadId,- payload.messageId,- payload.reaction,- );- }- // The provider may already have accepted the idempotent reaction. Fence- // the local success receipt so a reclaimed lease cannot report success- // for an obsolete runtime.- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- await notifyChatActionWork(tx, "receipt_reaction");- const processed = await tx- .update(chatActions)- .set({- status: "processed",- result: {- attempts: attempt,- ...(githubReceipt ? { githubReceipt } : {}),- },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, action.id),- eq(chatActions.status, "processing"),- sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,- ),- )- .returning({ id: chatActions.id });- if (!processed.length) {- throw new Error(- "Receipt-reaction ownership changed before success settlement",- );- }- if (action.deliveryId) {- await tx- .update(chatDeliveries)- .set({ redactedError: null, updatedAt: new Date() })- .where(- and(- eq(chatDeliveries.id, action.deliveryId),- eq(chatDeliveries.state, "processed"),- like(chatDeliveries.redactedError, "Receipt reaction %"),- ),- );- }- await credentialLease.assertOwned(tx);- });- } catch (error) {- if (- payload.operation === "add" &&- reactionProvider === "slack" &&- isSlackReceiptReactionAlreadyApplied(error)- ) {- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- await notifyChatActionWork(tx, "receipt_reaction");- const processed = await tx- .update(chatActions)- .set({- status: "processed",- result: {- attempts: attempt,- code: "receipt_reaction_already_applied",- },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, action!.id),- eq(chatActions.status, "processing"),- sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,- ),- )- .returning({ id: chatActions.id });- if (!processed.length) {- throw new Error(- "Receipt-reaction ownership changed before idempotent settlement",- );- }- if (action.deliveryId) {- await tx- .update(chatDeliveries)- .set({ redactedError: null, updatedAt: new Date() })- .where(- and(- eq(chatDeliveries.id, action.deliveryId),- eq(chatDeliveries.state, "processed"),- like(chatDeliveries.redactedError, "Receipt reaction %"),- ),- );- }- await credentialLease.assertOwned(tx);- });- return;- }- const disposition = classifyChatPublicationError(error, attempt);- const retryable =- disposition.kind === "retry" ||- (disposition.kind === "delivery_unknown" && attempt < 3);- const retryAfterMs =- disposition.kind === "retry"- ? disposition.retryAfterMs- : 100 * 2 ** Math.max(0, attempt - 1);- const operationLabel =- payload.operation === "remove" ? " reaction removal" : " reaction";- const diagnostic =- `Receipt${operationLabel} ${retryable ? "deferred" : "failed"} after ${attempt} attempt${attempt === 1 ? "" : "s"} (${disposition.kind}): ${redactError(error)}`.slice(- 0,- MAX_ERROR_TEXT,- );- const retryAt = retryable- ? new Date(Date.now() + retryAfterMs).toISOString()- : null;- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- await notifyChatActionWork(tx, "receipt_reaction");- const [failed] = await tx- .update(chatActions)- .set({- status: "failed",- result: {- attempts: attempt,- ...(githubReceipt ? { githubReceipt } : {}),- code:- payload.operation === "remove"- ? `receipt_reaction_removal_${disposition.kind}`- : `receipt_reaction_${disposition.kind}`,- redactedError: diagnostic,- retryable,- retryAt,- },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, action.id),- eq(chatActions.status, "processing"),- sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,- ),- )- .returning({ id: chatActions.id });- if (failed && action.deliveryId) {- await tx- .update(chatDeliveries)- .set({ redactedError: diagnostic, updatedAt: new Date() })- .where(- and(- eq(chatDeliveries.id, action.deliveryId),- eq(chatDeliveries.state, "processed"),- ),- );- }- await credentialLease.assertOwned(tx);- });- logger.warn(- {- endpointId: action.endpointId,- deliveryId: action.deliveryId,- attempts: attempt,- disposition: disposition.kind,- operation: payload.operation,- retryAt,- },- "external chat receipt reaction deferred",- );- }- }-- async function processPendingReceiptReactions(- limit = 25,- onlyActionId?: string,- ) {- const actions = await db.select({ id: chatActions.id }).from(chatActions)- .where(and(dueChatAction("receipt_reaction"), onlyActionId ? eq(chatActions.id, onlyActionId) : undefined))- .orderBy(asc(chatActions.createdAt)).limit(limit);- for (const action of actions) await processReceiptReaction(action.id);- return actions.length;- }-- async function stageProviderEffect(- database: DbOrTransaction,- input: {- endpoint: EndpointRow;- deliveryId?: string | null;- conversationId?: string | null;- principalId?: string | null;- providerActionId: string;- payload: Omit<- ProviderEffectPayload,- "runtimeGeneration" | "credentialFingerprint"- >;- runtimeContext: LifecycleRuntimeFence;- },- ) {- await notifyChatActionWork(database, "provider_effect");- const [inserted] = await database- .insert(chatActions)- .values({- companyId: input.endpoint.companyId,- endpointId: input.endpoint.id,- deliveryId: input.deliveryId ?? null,- conversationId: input.conversationId ?? null,- principalId: input.principalId ?? null,- kind: "provider_effect",- providerActionId: input.providerActionId,- payload: {- ...input.payload,- runtimeGeneration: input.runtimeContext.generation,- credentialFingerprint: input.runtimeContext.credentialFingerprint,- },- status: "received",- })- .onConflictDoNothing()- .returning();- if (inserted) return inserted;- return database- .select()- .from(chatActions)- .where(- and(- eq(chatActions.endpointId, input.endpoint.id),- eq(chatActions.providerActionId, input.providerActionId),- eq(chatActions.kind, "provider_effect"),- ),- )- .then((rows) => rows[0] ?? null);- }-async function stageAuthorizedTaskControlPublication(tx: DbOrTransaction,input: {@@ -3145,2482 +2017,1453 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {return publication;}- function providerEffectDisposition(- error: unknown,- attempt: number,- providerEffectCompleted: boolean,+ function scheduleProviderEffect(+ actionId: string,+ liveTarget?: ProviderEffectTarget,) {- if (!providerEffectCompleted)- return classifyChatPublicationError(error, attempt);- return {- kind: "delivery_unknown" as const,- reason:- "Provider effect completed, but Paperclip could not confirm its durable result",- };- }-- async function finalizeProviderEffectFailure(input: {- action: typeof chatActions.$inferSelect;- endpoint: EndpointRow;- payload: ProviderEffectPayload;- disposition: ReturnType<typeof providerEffectDisposition>;- attempt: number;- }): Promise<boolean> {- const failure = redactSensitiveText(input.disposition.reason).slice(- 0,- MAX_ERROR_TEXT,- );- const retryable = input.disposition.kind === "retry";- const retryAt =- input.disposition.kind === "retry"- ? new Date(Date.now() + input.disposition.retryAfterMs)- : null;- let invalidateCurrentRuntime = false;- const finalized = await db.transaction(async (tx) => {- // Admission locks the endpoint before its delivery. Keep that order- // when failure settlement also needs to change endpoint/resource health.- const currentEndpoint =- input.disposition.kind === "endpoint_attention" ||- input.disposition.kind === "resource_unavailable"- ? await runtimeCallbackEndpoint(- tx,- input.endpoint.id,- {- generation: input.payload.runtimeGeneration,- credentialFingerprint: input.payload.credentialFingerprint,- },- ["verifying", "active"],- )- : null;- await notifyChatActionWork(tx, "provider_effect");- const [ownedAction] = await tx- .update(chatActions)- .set({- status:- input.disposition.kind === "delivery_unknown"- ? "delivery_unknown"- : "failed",- result: {- code: `provider_effect_${input.disposition.kind}`,- attempts: input.attempt,- redactedError: failure,- retryable,- retryAt: retryAt?.toISOString() ?? null,- },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, input.action.id),- eq(chatActions.status, "processing"),- sql`(${chatActions.result}->>'attempts')::int = ${input.attempt}`,- ),- )- .returning({ id: chatActions.id });- if (!ownedAction) return false;- if (input.payload.settleDelivery && input.action.deliveryId) {- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- state: retryable ? "retry" : "failed",- nextAttemptAt: retryAt,- redactedError:- input.disposition.kind === "delivery_unknown"- ? `Provider response is unconfirmed: ${failure}`.slice(- 0,- MAX_ERROR_TEXT,- )- : failure,- updatedAt: new Date(),- })- .where(- and(- eq(chatDeliveries.id, input.action.deliveryId),- eq(chatDeliveries.state, "processing"),- ),- );- }- if (input.disposition.kind === "endpoint_attention" && currentEndpoint) {- await tx- .update(chatEndpoints)- .set({- status: "attention",- healthMessage: "Provider credentials or permissions need attention",- lastError: failure,- updatedAt: new Date(),- })- .where(eq(chatEndpoints.id, currentEndpoint.id));- await tx- .update(toolConnections)- .set({- status: "disabled",- enabled: false,- healthStatus: "degraded",- healthMessage: "Provider credentials or permissions need attention",- lastError: failure,- healthCheckedAt: new Date(),- updatedAt: new Date(),- })- .where(eq(toolConnections.id, currentEndpoint.connectionId));- invalidateCurrentRuntime = true;- } else if (- input.disposition.kind === "resource_unavailable" &&- input.payload.resourceId &&- currentEndpoint- ) {- await tx- .update(chatEndpointResources)- .set({ availability: "unavailable", updatedAt: new Date() })- .where(- and(- eq(chatEndpointResources.id, input.payload.resourceId),- eq(chatEndpointResources.endpointId, currentEndpoint.id),- ),- );- }- return true;- });- if (finalized && invalidateCurrentRuntime) {- await invalidateRuntime(input.endpoint.id).catch(() => undefined);- }- return finalized;- }-- async function quarantineStaleProviderEffect(- action: typeof chatActions.$inferSelect,- ) {- const payload = providerEffectPayload(action.payload);- const failure =- "Provider delivery could not be confirmed after the worker stopped. The effect will not be replayed automatically.";- await db.transaction(async (tx) => {- await notifyChatActionWork(tx, "provider_effect");- const [quarantined] = await tx- .update(chatActions)- .set({- status: "delivery_unknown",- result: {- code: "provider_effect_delivery_unknown",- redactedError: failure,- retryable: false,- },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, action.id),- eq(chatActions.status, "processing"),- eq(chatActions.updatedAt, action.updatedAt),- sql`(${chatActions.result}->>'attempts')::int = ${- typeof action.result?.attempts === "number"- ? action.result.attempts- : -1- }`,- lte(- chatActions.updatedAt,- new Date(Date.now() - PROVIDER_EFFECT_STALE_MS),- ),- ),- )- .returning({ id: chatActions.id });- if (quarantined && payload?.settleDelivery && action.deliveryId) {- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- state: "failed",- nextAttemptAt: null,- redactedError: failure,- updatedAt: new Date(),- })- .where(- and(- eq(chatDeliveries.id, action.deliveryId),- eq(chatDeliveries.state, "processing"),- ),- );- }+ scheduleMessageProcessing(async () => {+ await processProviderEffect(actionId, liveTarget);});}- function providerEffectThreadResourceId(- provider: ChatProvider,- threadId: string,- ): string | null {- if (provider === "slack") {- return (- slackThreadChannelId(threadId) ??- (!threadId.includes(":") ? threadId : null)- );- }- if (provider === "telegram") {- return /^telegram:([^:]+)/.exec(threadId)?.[1] ?? null;- }- if (provider === "github") {- return /^github:([^:]+)/.exec(threadId)?.[1]?.toLowerCase() ?? null;- }- if (provider === "discord") {- return /^discord:[^:]+:([^:]+)/.exec(threadId)?.[1] ?? null;- }- const conversationId = teamsConversationId(threadId);- return conversationId ? baseTeamsConversationId(conversationId) : null;- }-- // This is permission to return one fixed, neutral callback denial, not- // permission to execute the denied action or publish to the conversation.- // Retain the initial identity-policy snapshot so queued notices cannot cross- // a subsequent actor/link/reach change. No provider I/O occurs under locks.- async function lockTelegramCallbackNoticeAuthority(+ async function runtimeCallbackEndpoint(tx: DbTransaction,- endpoint: EndpointRow,- receipt: TelegramCallbackReceipt,- principalId: string | null,- ): Promise<string | null> {- if (- endpoint.provider !== "telegram" ||- endpoint.status !== "active" ||- endpoint.companyId !== receipt.companyId ||- endpoint.id !== receipt.endpointId ||- endpoint.botExternalId !== receipt.botUserId ||- !endpoint.providerAccountId ||- !principalId ||- Date.now() < receipt.receivedAtMs ||- Date.now() >= receipt.deadlineAtMs- )- return null;- const resource =- receipt.chatType === "private"- ? null- : await tx- .select()- .from(chatEndpointResources)- .where(- and(- eq(chatEndpointResources.companyId, endpoint.companyId),- eq(chatEndpointResources.endpointId, endpoint.id),- eq(chatEndpointResources.providerResourceId, receipt.chatId),- ),- )- .for("update")- .then((rows) => rows[0] ?? null);+ endpointId: string,+ context: LifecycleRuntimeFence,+ allowedStatuses: EndpointRow["status"][],+ ): Promise<EndpointRow | null> {+ const endpoint = await tx+ .select()+ .from(chatEndpoints)+ .where(eq(chatEndpoints.id, endpointId))+ // Serialize endpoint mutations without taking the stronger row lock+ // that conflicts with the Chat SDK state table's endpoint foreign-key+ // check. FOR UPDATE can self-deadlock an SDK-state write performed by a+ // provider callback on another pooled connection.+ .for("no key update")+ .then((rows) => rows[0] ?? null);if (- receipt.chatType === "private"- ? !endpoint.allowDirectMessages- : !resource || !nonDirectDestinationAllowed(endpoint, resource)+ !endpoint ||+ !allowedStatuses.includes(endpoint.status) ||+ runtimeGeneration(endpoint.setup) !== context.generation)return null;- const principal = await tx- .select()- .from(chatExternalPrincipals)- .where(- and(- eq(chatExternalPrincipals.companyId, endpoint.companyId),- eq(chatExternalPrincipals.provider, endpoint.provider),- eq(- chatExternalPrincipals.providerAccountId,- endpoint.providerAccountId,- ),- eq(chatExternalPrincipals.id, principalId),- eq(chatExternalPrincipals.externalId, receipt.receiverUserId),- ),- )- .for("update")- .then((rows) => rows[0] ?? null);- if (!principal || principal.kind !== "user" || principal.isBot) return null;- const authorization = await lockCurrentPrincipalAuthorization(- tx,- endpoint,- principal.id,- );- const link = await tx- .select({- status: chatIdentityLinks.status,- userId: chatIdentityLinks.paperclipUserId,- })- .from(chatIdentityLinks)+ const refs = await tx+ .select({ refs: toolConnections.credentialSecretRefs })+ .from(toolConnections).where(and(- eq(chatIdentityLinks.companyId, endpoint.companyId),- eq(chatIdentityLinks.endpointId, endpoint.id),- eq(chatIdentityLinks.principalId, principal.id),+ eq(toolConnections.companyId, endpoint.companyId),+ eq(toolConnections.id, endpoint.connectionId),),)- .then((rows) => rows[0] ?? null);- return createHash("sha256")- .update(- JSON.stringify([- endpoint.companyId,- endpoint.id,- receipt.botUserId,- resource?.id ?? null,- principal.id,- principal.externalId,- link,- authorization,- endpoint.allowUnlinkedPeople,- endpoint.sponsorUserId,- ]),- )- .digest("hex");+ .then((rows) => rows[0]?.refs ?? []);+ if (credentialFingerprint(refs) !== context.credentialFingerprint) {+ return null;+ }+ const runtimeContext = context as RuntimeContext;+ if (+ leasedChatProvider(endpoint.provider) &&+ runtimeContext.discordGatewayOwned === true &&+ runtimeContext.endpointRuntime !== undefined &&+ !discordGatewayRuntimeIsCurrent(endpointId, runtimeContext)+ ) {+ return null;+ }+ return endpoint;}- async function lockCurrentProviderEffectAuthorization(- tx: DbTransaction,- action: typeof chatActions.$inferSelect,- endpoint: EndpointRow,- payload: ProviderEffectPayload,- ): Promise<boolean> {- if (payload.effect === "telegram_callback_notice") {- const receipt = parseTelegramCallbackReceipt(payload.telegramCallback);- if (!receipt || !action.deliveryId) return false;- const delivery = await tx- .select()- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.id, action.deliveryId),- eq(chatDeliveries.companyId, action.companyId),- eq(chatDeliveries.endpointId, action.endpointId),- eq(chatDeliveries.state, "filtered"),- ),- )- .for("update")- .then((rows) => rows[0] ?? null);- const retained =- delivery &&- parseTelegramCallbackReceipt(delivery.normalizedEvent.telegramCallback);- if (- !delivery ||- delivery.principalId !== action.principalId ||- retained?.sourceSha256 !== receipt.sourceSha256 ||- delivery.normalizedEvent.telegramAuthorizationSha256 !==- payload.telegramAuthorizationSha256- )- return false;- return (- (await lockTelegramCallbackNoticeAuthority(- tx,- endpoint,- receipt,- action.principalId,- )) === payload.telegramAuthorizationSha256- );+ async function runtimeCallbackRecord(+ endpointId: string,+ context: RuntimeContext,+ allowedStatuses: EndpointRow["status"][],+ ) {+ const record = await endpointRecord(endpointId);+ if (+ record && leasedChatProvider(record.endpoint.provider) &&+ !(await ensureDiscordGatewayRuntimeIsCurrent(endpointId, context))+ ) {+ return null;}- const conversation = action.conversationId- ? await tx- .select()- .from(chatConversations)- .where(- and(- eq(chatConversations.companyId, endpoint.companyId),- eq(chatConversations.endpointId, endpoint.id),- eq(chatConversations.id, action.conversationId),- inArray(chatConversations.state, ["active", "waiting"]),- ),- )- .for("update")- .then((rows) => rows[0] ?? null)- : null;- if (action.conversationId && !conversation) return false;- const inferredResourceId = providerEffectThreadResourceId(- endpoint.provider,- payload.threadId,- );- const resource = await tx- .select()- .from(chatEndpointResources)- .where(- and(- eq(chatEndpointResources.companyId, endpoint.companyId),- eq(chatEndpointResources.endpointId, endpoint.id),- payload.resourceId || conversation?.resourceId- ? eq(- chatEndpointResources.id,- payload.resourceId ?? conversation!.resourceId!,- )- : inferredResourceId- ? eq(chatEndpointResources.providerResourceId, inferredResourceId)- : sql`false`,- ),- )- .for("update")- .then((rows) => rows[0] ?? null);- const slackChannelId =- endpoint.provider === "slack"- ? slackThreadChannelId(payload.threadId)- : null;- const isDirectMessage =- conversation?.isDirectMessage === true ||- resource?.type === "direct_message" ||- Boolean(slackChannelId && /^D[A-Z0-9]+$/i.test(slackChannelId));- const destinationAllowed = isDirectMessage- ? endpoint.allowDirectMessages- : nonDirectDestinationAllowed(endpoint, resource);- if (payload.authorizationMode === "safe_notice") return true;- if (!destinationAllowed) return false;- if (!action.principalId) return false;+ return record &&+ allowedStatuses.includes(record.endpoint.status) &&+ runtimeGeneration(record.endpoint.setup) === context.generation &&+ credentialFingerprint(record.credentialSecretRefs) ===+ context.credentialFingerprint &&+ runtime.get(endpointId) === context.endpointRuntime &&+ (!leasedChatProvider(record.endpoint.provider) ||+ discordGatewayRuntimeIsCurrent(endpointId, context))+ ? record+ : null;+ }++ async function recordCurrentMicrosoftTeamsRoute(+ endpoint: EndpointRow,+ context: InboundRuntimeContext | undefined,+ threadId: string,+ raw: unknown,+ recordAcceptedActivity = true,+ ): Promise<void> {+ if (endpoint.provider !== "microsoft-teams" || !context?.endpointRuntime) {+ return;+ }+ const serviceUrl = microsoftTeamsServiceUrl(raw);+ if (!serviceUrl) return;+ await db.transaction(async (tx) => {+ const current = await runtimeCallbackEndpoint(tx, endpoint.id, context, [+ "verifying",+ "active",+ ]);+ if (!current || runtime.get(endpoint.id) !== context.endpointRuntime) {+ return;+ }+ await context.endpointRuntime.recordMicrosoftTeamsRoute(+ threadId,+ serviceUrl,+ recordAcceptedActivity ? raw : undefined,+ );+ });+ }++ function discordGatewayRuntimeIsCurrent(+ endpointId: string,+ context: RuntimeContext,+ ): boolean {+ const ownership = discordGatewayOwnerships.get(endpointId);return (- await lockCurrentPrincipalAuthorization(tx, endpoint, action.principalId)- ).allowed;+ ownership !== undefined &&+ !ownership.stopping &&+ ownership.context === context &&+ ownership.expiresAt.getTime() > Date.now() &&+ context.discordGatewayOwned === true &&+ context.endpointRuntime !== undefined &&+ runtime.get(endpointId) === context.endpointRuntime+ );}- async function cancelUnauthorizedProviderEffect(- tx: DbTransaction,- action: typeof chatActions.$inferSelect,- attempt: number,- ): Promise<boolean> {- await notifyChatActionWork(tx, "provider_effect");- const [cancelled] = await tx- .update(chatActions)- .set({- status: "cancelled",- result: {- attempts: attempt,- code: "provider_effect_no_longer_authorized",- },- updatedAt: new Date(),+ function serializeEndpoint(+ row: Awaited<ReturnType<typeof endpointRecord>>,+ ): ChatEndpoint {+ if (!row) throw notFound("Chat endpoint not found");+ const endpoint = row.endpoint;+ return {+ id: endpoint.id,+ companyId: endpoint.companyId,+ connectionId: endpoint.connectionId,+ publicationMode: endpoint.publicationMode,+ externalExecutionPolicy: endpoint.externalExecutionPolicy,+ provider: endpoint.provider,+ publicId: endpoint.publicId,+ status: endpoint.status,+ deploymentMode: endpoint.deploymentMode,+ assignedAgentId: endpoint.assignedAgentId,+ assignedAgentName: row.assignedAgentName,+ sponsorUserId: endpoint.sponsorUserId,+ providerAccountId: endpoint.providerAccountId,+ providerAccountLabel: endpoint.providerAccountLabel,+ botExternalId: endpoint.botExternalId,+ botUsername: endpoint.botUsername,+ botLabel: endpoint.botDisplayName ?? row.assignedAgentName,+ botAvatarUrl: endpoint.botAvatarUrl,+ communicationInstructions: endpoint.communicationInstructions,+ ...(endpoint.provider === "imessage-photon" && endpoint.botExternalId ? { photonAllocation: endpoint.botExternalId.startsWith("photon-project:") ? "shared" as const : "dedicated" as const } : {}),+ allowDirectMessages: endpoint.allowDirectMessages,+ requireAtMention: endpoint.requireAtMention,+ allowGroupChats: endpoint.allowGroupChats,+ allowUnlinkedPeople: endpoint.allowUnlinkedPeople,+ replyMode: "subscribed",+ capabilities: endpoint.capabilities,+ setup: {+ ...providerSetupState(+ endpoint,+ getWebhookPublicBaseUrl(),+ row.assignedAgentName,+ ),+ ...(endpoint.provider === "github"+ ? {+ webhookSecretConfigured: row.credentialSecretRefs.some(+ (ref) => ref.configPath === "credentials.webhookSecret",+ ),+ }+ : endpoint.provider === "speko" ? {+ webhookSecretConfigured: row.credentialSecretRefs.some(+ (ref) => ref.configPath === "credentials.signingSecret",+ ),+ } : {}),+ },+ healthMessage: endpoint.healthMessage,+ lastError: endpoint.lastError,+ lastActivityAt: iso(endpoint.lastEventAt),+ lastPublicationAt: iso(endpoint.lastPublicationAt),+ activatedAt: iso(endpoint.activatedAt),+ createdAt: endpoint.createdAt.toISOString(),+ updatedAt: endpoint.updatedAt.toISOString(),+ };+ }++ async function list(companyId: string) {+ const rows = await db+ .select({+ endpoint: chatEndpoints,+ assignedAgentName: agents.name,+ connectionName: toolConnections.name,+ applicationId: toolConnections.applicationId,+ credentialSecretRefs: toolConnections.credentialSecretRefs,})+ .from(chatEndpoints)+ .innerJoin(+ agents,+ and(+ eq(agents.id, chatEndpoints.assignedAgentId),+ eq(agents.companyId, chatEndpoints.companyId),+ ),+ )+ .innerJoin(+ toolConnections,+ and(+ eq(toolConnections.id, chatEndpoints.connectionId),+ eq(toolConnections.companyId, chatEndpoints.companyId),+ ),+ ).where(and(- eq(chatActions.id, action.id),- eq(chatActions.status, "processing"),- sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,+ eq(chatEndpoints.companyId, companyId),+ ne(chatEndpoints.status, "archived"),),)- .returning({ id: chatActions.id });- if (!cancelled) return false;- if (action.deliveryId) {- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- state: "filtered",- processedAt: new Date(),- nextAttemptAt: null,- redactedError:- "Provider reply was suppressed because current chat authorization changed",- updatedAt: new Date(),- })- .where(- and(- eq(chatDeliveries.id, action.deliveryId),- eq(chatDeliveries.state, "processing"),- ),- );+ .orderBy(desc(chatEndpoints.updatedAt));+ return rows.map((row) => serializeEndpoint(row));+ }++ async function get(endpointId: string) {+ const result = serializeEndpoint(await endpointRecord(endpointId));+ if (result.provider === "slack") {+ const [registration] = await db.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, endpointId));+ result.setup.slackRegistration = registration ? slackRegistrationProjection(registration) : undefined;+ const publicOrigin = getPublicBaseUrl();+ result.setup.slackOAuthCallbackUri = publicOrigin ? `${publicOrigin}/api/chat-slack/oauth/callback` : null;}- return true;+ return result;}- async function processProviderEffect(- actionId: string,- liveTarget?: ProviderEffectTarget,- ): Promise<"processed" | "pending" | "failed" | "delivery_unknown"> {- const initial = await db- .select()- .from(chatActions)+ async function create(+ companyId: string,+ input: CreateChatEndpointInput,+ actorUserId?: string | null,+ ) {+ if ((input.provider as string) === "agentmail") throw badRequest("Use the email inbox setup API for AgentMail");+ if ((input.slackApp || input.slackSetupMethod) && input.provider !== "slack") throw unprocessable("Slack app details only apply to Slack connections");+ if (input.slackSetupMethod === "managed" && slackRegistration.managerGrants.defaultMethod() !== "managed") throw conflict("Managed Slack setup is unavailable");+ const agent = await db+ .select({ id: agents.id, name: agents.name, status: agents.status })+ .from(agents).where(and(- eq(chatActions.id, actionId),- eq(chatActions.kind, "provider_effect"),+ eq(agents.companyId, companyId),+ eq(agents.id, input.assignedAgentId),),).then((rows) => rows[0] ?? null);- if (!initial) return "failed";- const initialEndpoint = await endpointRecord(initial.endpointId);- if (!initialEndpoint) return "failed";-- const processClaimedEffect = async () => {- let action = await db- .select()- .from(chatActions)- .where(eq(chatActions.id, actionId))- .then((rows) => rows[0] ?? null);- if (!action) return "failed";- const payload = providerEffectPayload(action.payload);- if (!payload) {- await db.transaction(async (tx) => {- await notifyChatActionWork(tx, "provider_effect");- return tx- .update(chatActions)- .set({- status: "failed",- result: { code: "provider_effect_payload_invalid" },- updatedAt: new Date(),- })- .where(eq(chatActions.id, action.id));- });- return "failed";- }- if (action.status === "processed") return "processed";- if (action.status === "delivery_unknown") return "delivery_unknown";- if (action.status === "processing") {- if (action.updatedAt > new Date(Date.now() - PROVIDER_EFFECT_STALE_MS))- return "pending";- await quarantineStaleProviderEffect(action);- return "delivery_unknown";- }- if (action.status === "failed") {- if (action.result?.retryable !== true) return "failed";- const retryAt =- typeof action.result.retryAt === "string"- ? new Date(action.result.retryAt)- : null;- if (retryAt && retryAt > new Date()) return "pending";- } else if (action.status !== "received") {- return "failed";- }+ if (!agent)+ throw unprocessable("The selected agent does not belong to this company");+ if (!isAgentStatusInvokable(agent.status)) {+ throw unprocessable(+ "The selected agent must be active before it can be connected to chat",+ {+ code: "chat_agent_not_invokable",+ },+ );+ }- const attempt =- (typeof action.result?.attempts === "number"- ? action.result.attempts- : 0) + 1;- const record = await endpointRecord(action.endpointId);- let providerEffectCompleted = false;- try {- if (!record) {- throw Object.assign(- new Error("Chat endpoint is unavailable for this provider effect"),- { code: "CHAT_PROVIDER_PRETRANSPORT_REJECTED" },- );- }- return await withCredentialMutationLease(- record.endpoint,- async (credentialLease) => {- const claim = await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- const currentAction = await tx- .select()- .from(chatActions)- .where(- and(- eq(chatActions.id, action!.id),- eq(chatActions.kind, "provider_effect"),- eq(chatActions.status, action!.status),- ),- )- .for("update")- .then((rows) => rows[0] ?? null);- if (!currentAction) return null;- const currentEndpoint = await runtimeCallbackEndpoint(- tx,- currentAction.endpointId,- {- generation: payload.runtimeGeneration,- credentialFingerprint: payload.credentialFingerprint,- },- ["verifying", "active"],- );- const authorized = currentEndpoint- ? await lockCurrentProviderEffectAuthorization(- tx,- currentAction,- currentEndpoint,- payload,- )- : false;- await notifyChatActionWork(tx, "provider_effect");- const [transportClaim] = await tx- .update(chatActions)- .set({- status: "processing",- result: { attempts: attempt },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, currentAction.id),- eq(chatActions.status, currentAction.status),- ),- )- .returning();- if (!transportClaim) return null;- if (!currentEndpoint || !authorized) {- const cancelled = await cancelUnauthorizedProviderEffect(- tx,- transportClaim,- attempt,- );- if (!cancelled) {- throw new Error(- "Provider effect ownership changed before authorization cancellation",- );- }- return { outcome: "cancelled" as const };- }- await credentialLease.assertOwned(tx);- return {- action: transportClaim,- endpoint: currentEndpoint,- outcome: "claimed" as const,- };- });- if (!claim) return "pending";- if (claim.outcome === "cancelled") return "failed";- action = claim.action;-- // `processing` is the durable, single-owner transport claim and- // authorization linearization point. Its transaction has committed- // before provider I/O begins. The renewable credential lease keeps- // runtime identity stable without holding database row locks.- let sent: { id: string; threadId: string } | null = null;- if (payload.effect === "telegram_callback_notice") {- sent = await (- await runtimeFor(claim.endpoint)- ).sendTelegramCallbackNotice(- payload.telegramCallback!,- payload.text,- );- } else {- const target =- liveTarget ??- (await runtimeFor(claim.endpoint)).thread(payload.threadId);- if (payload.effect === "ephemeral_message") {- if (!target.postEphemeral) {- if (!payload.fallbackText) {- throw Object.assign(- new Error("Provider does not support ephemeral messages"),- { code: "CHAT_PROVIDER_PRETRANSPORT_REJECTED" },- );- }- sent = await target.post(payload.fallbackText);- } else {- try {- sent = await target.postEphemeral(- payload.userId!,- payload.text,- { fallbackToDM: false },- );- } catch (error) {- if (- !payload.fallbackText ||- classifyChatPublicationError(error, attempt).kind !==- "failed"- ) {- throw error;- }- }- if (!sent && payload.fallbackText) {- sent = await target.post(payload.fallbackText);- }- }- } else if (claim.endpoint.provider === "imessage-photon") {- const adapter = (await runtimeFor(claim.endpoint)).getProviderAdapter();- if (!(adapter instanceof PhotonChatAdapter)) throw new Error("Photon runtime unavailable");- const receipt = await adapter.publish(payload.threadId, `effect:${action.id}`, projectSafeChatPublicationText(payload.text), {- assertCurrent: async () => { await credentialLease.assertOwned(); },- });- sent = { id: receipt.id, threadId: payload.threadId };- } else {- sent = await target.post(payload.text);- }- }- if (!sent) {- throw Object.assign(- new Error("Provider did not accept the message"),- { code: "CHAT_PROVIDER_PRETRANSPORT_REJECTED" },- );- }- providerEffectCompleted = true;- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- // A duplicate webhook holds the endpoint while waiting for the- // delivery's unique-index entry. Lock this endpoint first too,- // before settling the action/conversation/delivery, so neither- // transaction can wait on a row already held by the other.- const currentEndpoint = await runtimeCallbackEndpoint(- tx,- claim.endpoint.id,- {- generation: payload.runtimeGeneration,- credentialFingerprint: payload.credentialFingerprint,- },- ["verifying", "active"],- );- await notifyChatActionWork(tx, "provider_effect");- const [completed] = await tx- .update(chatActions)- .set({- status: "processed",- result: {- attempts: attempt,- providerMessageId: sent.id,- threadId: sent.threadId,- ...(payload.effect === "telegram_callback_notice"- ? {- code:- payload.telegramCallback?.chatType === "private"- ? "telegram_private_api_accepted"- : "telegram_ephemeral_api_accepted",- }- : {}),- },- updatedAt: new Date(),- })- .where(- and(- eq(chatActions.id, action!.id),- eq(chatActions.status, "processing"),- sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,- ),- )- .returning({ id: chatActions.id });- if (!completed) {- throw new Error(- "Provider effect ownership changed before commit",- );- }- if (payload.completeConversationId) {- await tx- .update(chatConversations)- .set({ state: "completed", updatedAt: new Date() })- .where(- and(- eq(chatConversations.id, payload.completeConversationId),- eq(chatConversations.endpointId, claim.endpoint.id),- inArray(chatConversations.state, ["active", "waiting"]),- ),- );- }- if (payload.settleDelivery && action!.deliveryId) {- await notifyChatDeliveryWork(tx);- const [settled] = await tx- .update(chatDeliveries)- .set({- state: "processed",- processedAt: new Date(),- nextAttemptAt: null,- redactedError: null,- updatedAt: new Date(),- })- .where(- and(- eq(chatDeliveries.id, action!.deliveryId),- eq(chatDeliveries.state, "processing"),- ),- )- .returning({ id: chatDeliveries.id });- if (!settled) {- throw new Error(- "Provider effect delivery ownership changed before commit",- );- }- }- if (currentEndpoint) {- await tx- .update(chatEndpoints)- .set({ lastEventAt: new Date(), updatedAt: new Date() })- .where(eq(chatEndpoints.id, currentEndpoint.id));- }- await credentialLease.assertOwned(tx);- });- return "processed";- },- );- } catch (error) {- const disposition = providerEffectDisposition(- error,- attempt,- providerEffectCompleted,- );- try {- await finalizeProviderEffectFailure({- action,- endpoint: record?.endpoint ?? initialEndpoint.endpoint,- payload,- disposition,- attempt,- });- } catch (finalizationError) {- if (disposition.kind === "delivery_unknown") {- throw Object.assign(- new Error(- "Provider effect is ambiguous and its durable quarantine failed",- { cause: finalizationError },- ),- { code: "CHAT_PROVIDER_EFFECT_AMBIGUOUS" },- );- }- throw finalizationError;+ const endpointId = randomUUID();+ const publicId = randomBytes(32).toString("base64url");+ const applicationId = input.applicationId ?? randomUUID();+ const connectionId = randomUUID();+ const suffix = endpointId.slice(0, 8);+ const name = (+ input.name?.trim() || `${PROVIDER_LABELS[input.provider]} — ${agent.name}`+ ).slice(0, 145);+ await db.transaction(async (tx) => {+ if (input.applicationId) {+ const application = await tx+ .select({+ id: toolApplications.id,+ applicationKey: toolApplications.applicationKey,+ metadata: toolApplications.metadata,+ status: toolApplications.status,+ })+ .from(toolApplications)+ .where(+ and(+ eq(toolApplications.companyId, companyId),+ eq(toolApplications.id, input.applicationId),+ ),+ )+ .then((rows) => rows[0] ?? null);+ if (!application) throw notFound("App not found");+ const sourceTemplateKey =+ typeof application.metadata.sourceTemplateKey === "string"+ ? application.metadata.sourceTemplateKey+ : null;+ if (+ application.status === "archived" ||+ (application.applicationKey !== input.provider &&+ sourceTemplateKey !== input.provider)+ ) {+ throw unprocessable(+ `The selected App is not the ${PROVIDER_LABELS[input.provider]} connector`,+ );}- throw error;+ } else {+ await tx.insert(toolApplications).values({+ id: applicationId,+ companyId,+ applicationKey: `chat:${input.provider}:${endpointId}`,+ name: `${name} ${suffix}`,+ description: `People talk to ${agent.name} through ${PROVIDER_LABELS[input.provider]}.`,+ type: "chat",+ status: "draft",+ metadata: { sourceTemplateKey: input.provider, purpose: "channel" },+ ownerUserId: actorUserId ?? null,+ });}- };- return processClaimedEffect();- }-- function scheduleProviderEffect(- actionId: string,- liveTarget?: ProviderEffectTarget,- ) {- scheduleMessageProcessing(async () => {- await processProviderEffect(actionId, liveTarget);+ await tx.insert(toolConnections).values({+ id: connectionId,+ companyId,+ applicationId,+ name,+ uid: `chat-${input.provider}-${endpointId}`,+ connectionKind: "managed",+ connectionPurpose: "channel",+ ownership: "customer",+ transport: input.provider === "speko" ? "voice" : "chat_sdk",+ authKind: "api_key",+ credentialPolicy: "shared",+ status: "draft",+ enabled: false,+ config: { provider: input.provider },+ transportConfig: {},+ createdByUserId: actorUserId ?? null,+ });+ await tx.insert(chatEndpoints).values({+ id: endpointId,+ companyId,+ connectionId,+ provider: input.provider,+ publicId,+ assignedAgentId: agent.id,+ sponsorUserId: actorUserId ?? null,+ // Group chat is a broad Teams reach grant rather than a discovered+ // destination toggle. Keep it closed until the operator explicitly+ // enables that surface, even when this process is running against a+ // database created before the column default was hardened.+ requireAtMention: input.provider === "slack",+ allowGroupChats: !["microsoft-teams", "speko"].includes(input.provider),+ allowUnlinkedPeople: !["slack", "imessage-photon", "speko"].includes(input.provider),+ capabilities: CAPABILITIES[input.provider],+ setup: {+ step: "provider_setup",+ ...(input.provider === "slack"+ ? { slackApp: input.slackApp ?? defaultSlackAppConfiguration(agent.name),+ command: (input.slackApp ?? defaultSlackAppConfiguration(agent.name)).command, slackSetupMethod: input.slackSetupMethod ?? slackRegistration.managerGrants.defaultMethod() }+ : {}),+ },+ });});+ await logActivity(db, {+ companyId,+ actorType: "user",+ actorId: actorUserId ?? "board",+ action: "chat_endpoint.created",+ entityType: "tool_connection",+ entityId: connectionId,+ details: {+ endpointId,+ provider: input.provider,+ assignedAgentId: agent.id,+ },+ });+ return get(endpointId);}- async function processPendingProviderEffects(limit = 25) {- const now = new Date();- const staleBefore = new Date(now.getTime() - PROVIDER_EFFECT_STALE_MS);- const actions = await db- .select()- .from(chatActions)- .where(dueChatAction("provider_effect", now.getTime()))- .orderBy(asc(chatActions.createdAt))- .limit(limit);- for (const action of actions) {- if (action.status === "processing" && action.updatedAt <= staleBefore) {- await quarantineStaleProviderEffect(action);- continue;- }- try {- await processProviderEffect(action.id);- } catch (error) {- logger.warn(- {- endpointId: action.endpointId,- actionId: action.id,- error: redactError(error),- },- "chat provider effect reconciliation failed",- );- }- }- return actions.length;- }-- async function runtimeCallbackEndpoint(- tx: DbTransaction,+ async function update(endpointId: string,- context: LifecycleRuntimeFence,- allowedStatuses: EndpointRow["status"][],- ): Promise<EndpointRow | null> {- const endpoint = await tx- .select()- .from(chatEndpoints)- .where(eq(chatEndpoints.id, endpointId))- // Serialize endpoint mutations without taking the stronger row lock- // that conflicts with the Chat SDK state table's endpoint foreign-key- // check. FOR UPDATE can self-deadlock an SDK-state write performed by a- // provider callback on another pooled connection.- .for("no key update")- .then((rows) => rows[0] ?? null);- if (- !endpoint ||- !allowedStatuses.includes(endpoint.status) ||- runtimeGeneration(endpoint.setup) !== context.generation- )- return null;- const refs = await tx- .select({ refs: toolConnections.credentialSecretRefs })- .from(toolConnections)- .where(- and(- eq(toolConnections.companyId, endpoint.companyId),- eq(toolConnections.id, endpoint.connectionId),- ),- )- .then((rows) => rows[0]?.refs ?? []);- if (credentialFingerprint(refs) !== context.credentialFingerprint) {- return null;- }- const runtimeContext = context as RuntimeContext;- if (- leasedChatProvider(endpoint.provider) &&- runtimeContext.discordGatewayOwned === true &&- runtimeContext.endpointRuntime !== undefined &&- !discordGatewayRuntimeIsCurrent(endpointId, runtimeContext)- ) {- return null;- }- return endpoint;- }-- async function runtimeCallbackRecord(- endpointId: string,- context: RuntimeContext,- allowedStatuses: EndpointRow["status"][],+ input: UpdateChatEndpointInput,+ actorUserId?: string | null,) {- const record = await endpointRecord(endpointId);- if (- record && leasedChatProvider(record.endpoint.provider) &&- !(await ensureDiscordGatewayRuntimeIsCurrent(endpointId, context))- ) {- return null;- }- return record &&- allowedStatuses.includes(record.endpoint.status) &&- runtimeGeneration(record.endpoint.setup) === context.generation &&- credentialFingerprint(record.credentialSecretRefs) ===- context.credentialFingerprint &&- runtime.get(endpointId) === context.endpointRuntime &&- (!leasedChatProvider(record.endpoint.provider) ||- discordGatewayRuntimeIsCurrent(endpointId, context))- ? record- : null;+ const initial = await endpointRecord(endpointId);+ if (!initial) throw notFound("Chat endpoint not found");+ if (initial.endpoint.provider === "agentmail") throw badRequest("Use the email inbox API for AgentMail");+ await withCredentialMutationLease(+ initial.endpoint,+ async (credentialLease) => {+ // Reach changes share the provider-transport lane with publications.+ // Once a disable returns, no send that sampled the previous grant can+ // still begin or finish behind it.+ const existing = await endpointRecord(endpointId);+ if (!existing) throw notFound("Chat endpoint not found");+ const values: Partial<typeof chatEndpoints.$inferInsert> = {+ updatedAt: new Date(),+ };+ if (input.communicationInstructions !== undefined) {+ if (existing.endpoint.provider !== "slack") {+ throw unprocessable("Communication instructions are currently supported for Slack connections");+ }+ values.communicationInstructions = input.communicationInstructions;+ }+ if (input.slackSetupMethod === "managed" && slackRegistration.managerGrants.defaultMethod() !== "managed") throw conflict("Managed Slack setup is unavailable");+ if (input.slackSetupMethod && (existing.endpoint.provider !== "slack" || existing.endpoint.botExternalId || existing.endpoint.status !== "draft")) {+ throw conflict("Setup method can only change before connecting the app");+ }+ if (input.slackApp || input.slackSetupMethod) {+ const [registration] = await db.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, endpointId));+ if (registration && (registration.managerGrantId || registration.status !== "failed")) {+ if (registration.managerGrantId || input.slackSetupMethod === "managed" || input.slackApp || input.slackSetupMethod === "automatic") throw conflict("Slack app details are locked after creation starts");+ // Manual recovery fences pending authorization under the same credential lease.+ await slackRegistration.cleanup(endpointId, credentialLease);+ }+ }+ if (input.slackSetupMethod) {+ values.setup = { ...existing.endpoint.setup, slackSetupMethod: input.slackSetupMethod };+ }+ if (input.slackApp) {+ if (existing.endpoint.provider !== "slack") {+ throw unprocessable("Slack app details only apply to Slack connections");+ }+ if (existing.endpoint.status !== "draft" || existing.endpoint.botExternalId) {+ throw conflict("Slack app details can only be edited before connecting the app");+ }+ values.setup = {+ ...(values.setup ?? existing.endpoint.setup),+ slackApp: input.slackApp,+ command: input.slackApp.command,+ };+ }+ if (input.allowDirectMessages !== undefined)+ values.allowDirectMessages = input.allowDirectMessages;+ if (input.requireAtMention !== undefined) {+ if (existing.endpoint.provider !== "slack")+ throw unprocessable("Require at-mention only applies to Slack connections");+ values.requireAtMention = input.requireAtMention;+ }+ if (input.allowGroupChats && existing.endpoint.provider === "imessage-photon" && (!existing.endpoint.botExternalId || existing.endpoint.botExternalId.startsWith("photon-project:")))+ throw unprocessable("Photon shared channels support direct messages only; groups require a dedicated channel");+ if (input.allowGroupChats !== undefined)+ values.allowGroupChats = input.allowGroupChats;+ if (input.allowUnlinkedPeople !== undefined)+ values.allowUnlinkedPeople = input.allowUnlinkedPeople;+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ await tx+ .update(chatEndpoints)+ .set(values)+ .where(eq(chatEndpoints.id, endpointId));+ await logActivity(tx as unknown as Db, {+ companyId: existing.endpoint.companyId,+ actorType: "user",+ actorId: actorUserId ?? "board",+ action: "chat_endpoint.updated",+ entityType: "tool_connection",+ entityId: existing.endpoint.connectionId,+ details: { endpointId, fields: Object.keys(input) },+ });+ await credentialLease.assertOwned(tx);+ });+ },+ );+ return get(endpointId);}- async function recordCurrentMicrosoftTeamsRoute(+ async function normalizedCredentials(endpoint: EndpointRow,- context: InboundRuntimeContext | undefined,- threadId: string,- raw: unknown,- recordAcceptedActivity = true,- ): Promise<void> {- if (endpoint.provider !== "microsoft-teams" || !context?.endpointRuntime) {- return;- }- const serviceUrl = microsoftTeamsServiceUrl(raw);- if (!serviceUrl) return;- await db.transaction(async (tx) => {- const current = await runtimeCallbackEndpoint(tx, endpoint.id, context, [- "verifying",- "active",- ]);- if (!current || runtime.get(endpoint.id) !== context.endpointRuntime) {- return;- }- await context.endpointRuntime.recordMicrosoftTeamsRoute(- threadId,- serviceUrl,- recordAcceptedActivity ? raw : undefined,- );- });- }-- function discordGatewayRuntimeIsCurrent(- endpointId: string,- context: RuntimeContext,- ): boolean {- const ownership = discordGatewayOwnerships.get(endpointId);- return (- ownership !== undefined &&- !ownership.stopping &&- ownership.context === context &&- ownership.expiresAt.getTime() > Date.now() &&- context.discordGatewayOwned === true &&- context.endpointRuntime !== undefined &&- runtime.get(endpointId) === context.endpointRuntime+ supplied: Record<string, string> | undefined,+ ) {+ const values = await resolveCredentials(endpoint).catch(+ () => ({}) as Record<string, string>,);- }-- function discordGatewayFailureDetail(- event: DiscordGatewayCallbackEvent["event"],- ): string {- if (event.type === "guild_removed") {- return "Discord bot was removed from the configured server";- }- if (event.type === "guild_unavailable") {- return "Discord server is temporarily unavailable; reconnecting";+ for (const [key, rawValue] of Object.entries(supplied ?? {})) {+ if (typeof rawValue === "string" && rawValue.trim())+ values[key] = key === "privateKey" ? rawValue : rawValue.trim();}- if (event.type === "disconnected") {- return `Discord Gateway disconnected${event.code === undefined ? "" : ` (code ${event.code})`}; reconnecting`;+ if (endpoint.provider === "telegram" && !values.webhookSecret) {+ values.webhookSecret = randomBytes(32).toString("hex");}- if (event.type === "failure") {- const code = event.error.code ?? event.error.status;- return `Discord Gateway failed${code === undefined ? "" : ` (${String(code).slice(0, 64)})`}; ${event.fatal ? "credentials or privileged intents need attention" : "reconnecting"}`;+ const required =+ endpoint.provider === "github"+ ? ["appId", "privateKey", "webhookSecret"]+ : REQUIRED_CREDENTIALS[endpoint.provider];+ const missing = required.filter((key) => !values[key]);+ if (missing.length > 0) {+ throw unprocessable(+ `Missing required ${PROVIDER_LABELS[endpoint.provider]} credentials: ${missing.join(", ")}`,+ );}- return "Discord Gateway connection needs attention";- }-- function handleDiscordGatewayEvent(- callback: DiscordGatewayCallbackEvent,- context: RuntimeContext,- ): Promise<void> {- const pending = (context.discordGatewayEventQueue ?? Promise.resolve())- .catch(() => undefined)- .then(() => processDiscordGatewayEvent(callback, context));- context.discordGatewayEventQueue = pending;- return pending;+ return endpoint.provider === "microsoft-teams"+ ? normalizeMicrosoftTeamsCredentialIds(values)+ : values;}- async function processDiscordGatewayEvent(- callback: DiscordGatewayCallbackEvent,- context: RuntimeContext,- ): Promise<void> {- if (- !(await ensureDiscordGatewayRuntimeIsCurrent(- callback.endpointId,- context,- ))- )- return;- if (callback.sequence <= (context.discordGatewaySequence ?? 0)) return;- context.discordGatewaySequence = callback.sequence;- await options.discordGatewayEventBarrier?.(callback);- const record = await runtimeCallbackRecord(callback.endpointId, context, [- "verifying",- "active",- "attention",- ]);- if (!record || record.endpoint.provider !== "discord") return;- const event = callback.event;- if (event.type === "channel_removed") {- await applyProviderLifecycleEffect(- record.endpoint,- {- kind: "resource",- provider: "discord",- providerEventId: `gateway:channel_removed:${event.channelId}`,- providerResourceId: event.channelId,- resourceType: "channel",- label: event.label?.trim() || event.channelId,- availability: "removed",- metadata: { source: "discord_gateway" },+ async function verifyCredentials(+ provider: ChatProvider,+ credentials: Record<string, string>,+ ): Promise<VerifiedProviderIdentity> {+ if (provider === "imessage-photon") {+ const inspection = await inspectPhotonCredentials(credentials.projectId, credentials.projectSecret);+ if (inspection.allocation !== (credentials.allocation ?? "dedicated")) throw unprocessable("Photon allocation changed; inspect the project again");+ if (inspection.allocation === "shared") {+ if (!inspection.eligible) throw unprocessable("Photon shared project is unavailable");+ return { providerAccountId: inspection.projectId, providerAccountLabel: inspection.projectName, botExternalId: photonSharedIdentity(inspection.projectId), botUsername: null, botLabel: `${inspection.projectName} (DM only)` };+ }+ const line = inspection.lines.find((candidate) => candidate.lineId === credentials.lineId && candidate.eligible);+ if (!line || !inspection.eligible) throw unprocessable("Select an eligible dedicated Photon line");+ return { providerAccountId: inspection.projectId, providerAccountLabel: inspection.projectName, botExternalId: line.phoneNumber, botUsername: line.phoneNumber, botLabel: line.phoneNumber };+ }+ if (provider === "slack") {+ const response = await fetchImpl("https://slack.com/api/auth.test", {+ method: "POST",+ signal: AbortSignal.timeout(PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS),+ headers: {+ authorization: `Bearer ${credentials.botToken}`,+ "content-type": "application/x-www-form-urlencoded",},- context,+ body: "",+ });+ const result = (await response.json()) as {+ ok?: boolean;+ error?: string;+ team_id?: string;+ team?: string;+ user_id?: string;+ user?: string;+ };+ if (!response.ok || !result.ok)+ throw unprocessable(+ `Slack rejected the bot token: ${result.error ?? response.status}`,+ );+ const grantedScopes = new Set(+ (response.headers.get("x-oauth-scopes") ?? "")+ .split(",")+ .map((scope) => scope.trim())+ .filter(Boolean),);- return;- }-- await db.transaction(async (tx) => {- const current = await runtimeCallbackEndpoint(- tx,- callback.endpointId,- context,- ["verifying", "active", "attention"],+ const missingScopes = REQUIRED_SLACK_BOT_SCOPES.filter(+ (scope) => !grantedScopes.has(scope),);- if (- !current ||- current.provider !== "discord" ||- !discordGatewayRuntimeIsCurrent(callback.endpointId, context)- ) {- return;- }- const now = new Date();- if (event.type === "connecting") {- await tx- .update(chatEndpoints)- .set({- healthMessage: "Discord Gateway connecting",- lastError: null,- lastEventAt: now,- updatedAt: now,- })- .where(eq(chatEndpoints.id, current.id));- await tx- .update(toolConnections)- .set({- healthStatus: "unchecked",- healthMessage: "Discord Gateway connecting",- lastError: null,- healthCheckedAt: now,- updatedAt: now,- })- .where(eq(toolConnections.id, current.connectionId));- return;- }- if (event.type === "ready" || event.type === "guild_available") {- const gatewayOwnedAttention =- current.status === "attention" &&- current.healthMessage?.startsWith("Discord ") === true;- if (current.status === "attention" && !gatewayOwnedAttention) return;- const status =- current.setup.step === "complete" ? "active" : "verifying";- if (status !== current.status) await notifyChatEndpointWork(tx);- await tx- .update(chatEndpoints)- .set({- status,- healthMessage:- status === "active"- ? "Connected"- : "Waiting for a test conversation",- lastError: null,- lastEventAt: now,- updatedAt: now,- })- .where(eq(chatEndpoints.id, current.id));- await tx- .update(toolConnections)- .set({- status: "active",- enabled: true,- healthStatus: "healthy",- healthMessage: "Connected",- lastError: null,- healthCheckedAt: now,- updatedAt: now,- })- .where(eq(toolConnections.id, current.connectionId));- return;+ if (missingScopes.length > 0) {+ throw unprocessable(+ `Slack app is missing required bot scopes: ${missingScopes.join(", ")}`,+ {+ code: "chat_provider_permissions_missing",+ provider: "slack",+ missingScopes,+ },+ );}-- const detail = discordGatewayFailureDetail(event);- const transientGuildOutage = event.type === "guild_unavailable";- const terminal =- event.type === "guild_removed" ||- ((event.type === "failure" || event.type === "disconnected") &&- event.fatal);- await tx- .update(chatEndpoints)- .set({- status: transientGuildOutage- ? current.status- : event.type === "guild_removed"- ? "revoked"- : "attention",- healthMessage: detail,- lastError: detail,- lastEventAt: now,- ...(terminal- ? {- setup: {- ...current.setup,- runtimeGeneration: runtimeGeneration(current.setup) + 1,- } as InternalSetupState,- }- : {}),- updatedAt: now,- })- .where(eq(chatEndpoints.id, current.id));- await tx- .update(toolConnections)- .set({- status: terminal ? "disabled" : "active",- enabled: !terminal,- healthStatus: event.type === "guild_removed" ? "failed" : "degraded",- healthMessage: detail,- lastError: detail,- healthCheckedAt: now,- updatedAt: now,- })- .where(eq(toolConnections.id, current.connectionId));- if (event.type === "guild_removed") {- await tx- .update(chatEndpointResources)- .set({ availability: "unavailable", updatedAt: now })- .where(- and(- eq(chatEndpointResources.companyId, current.companyId),- eq(chatEndpointResources.endpointId, current.id),- ),- );- await tx- .update(chatConversations)- .set({ state: "unavailable", updatedAt: now })- .where(- and(- eq(chatConversations.companyId, current.companyId),- eq(chatConversations.endpointId, current.id),- inArray(chatConversations.state, ["active", "waiting"]),- ),- );+ return {+ providerAccountId: result.team_id,+ providerAccountLabel: result.team,+ botExternalId: result.user_id,+ botUsername: result.user,+ botLabel: result.user,+ };+ }+ if (provider === "discord") {+ const identity = await verifyDiscordBot({+ applicationId: credentials.applicationId,+ botToken: credentials.botToken,+ fetch: fetchImpl,+ guildId: credentials.guildId,+ }).catch((error) => {+ throw unprocessable(redactError(error), {+ code: "chat_provider_permissions_missing",+ provider: "discord",+ });+ });+ return identity;+ }+ if (provider === "telegram") {+ const response = await fetchImpl(+ `https://api.telegram.org/bot${encodeURIComponent(credentials.botToken)}/getMe`,+ { signal: AbortSignal.timeout(PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS) },+ );+ const result = (await response.json()) as {+ ok?: boolean;+ description?: string;+ result?: { id?: number; username?: string; first_name?: string };+ };+ if (!response.ok || !result.ok)+ throw unprocessable(+ `Telegram rejected the bot token: ${result.description ?? response.status}`,+ );+ return {+ providerAccountId: String(result.result?.id ?? ""),+ botExternalId: String(result.result?.id ?? ""),+ botUsername: result.result?.username,+ botLabel: result.result?.first_name,+ };+ }+ if (provider === "github") {+ const token = githubAppJwt(credentials.appId, credentials.privateKey);+ const response = await fetchImpl("https://api.github.com/app", {+ signal: AbortSignal.timeout(PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS),+ headers: {+ accept: "application/vnd.github+json",+ authorization: `Bearer ${token}`,+ "x-github-api-version": "2022-11-28",+ },+ });+ const result = (await response.json()) as {+ id?: number;+ login?: string;+ slug?: string;+ name?: string;+ message?: string;+ owner?: { login?: string; type?: string };+ permissions?: Record<string, string>;+ events?: string[];+ };+ if (!response.ok)+ throw unprocessable(+ `GitHub rejected the app credentials: ${result.message ?? response.status}`,+ );+ const missingPermissions = Object.entries(REQUIRED_GITHUB_PERMISSIONS)+ .filter(+ ([permission, access]) => result.permissions?.[permission] !== access,+ )+ .map(([permission]) => permission);+ const excessivePermissions = Object.keys(result.permissions ?? {}).filter(+ (permission) => !(permission in REQUIRED_GITHUB_PERMISSIONS) && !((permission === "contents" && result.permissions?.contents === "read") || (permission === "checks" && result.permissions?.checks === "write")),+ );+ const configuredEvents = new Set(result.events ?? []);+ const missingEvents = REQUIRED_GITHUB_EVENTS.filter(+ (event) => !configuredEvents.has(event),+ );+ const allowedEvents = new Set<string>([+ ...REQUIRED_GITHUB_EVENTS,+ ...UNAVOIDABLE_GITHUB_EVENTS,+ "pull_request",+ "pull_request_review",+ "issues",+ ]);+ const excessiveEvents = [...configuredEvents].filter(+ (event) => !allowedEvents.has(event),+ );+ if (+ missingPermissions.length > 0 ||+ excessivePermissions.length > 0 ||+ missingEvents.length > 0 ||+ excessiveEvents.length > 0+ ) {+ throw unprocessable(+ [+ missingPermissions.length > 0+ ? `GitHub App needs the documented minimum access for: ${missingPermissions.join(", ")}`+ : null,+ excessivePermissions.length > 0+ ? `GitHub App has broader permissions than Paperclip needs: ${excessivePermissions.join(", ")}`+ : null,+ missingEvents.length > 0+ ? `GitHub App must subscribe to: ${missingEvents.join(", ")}`+ : null,+ excessiveEvents.length > 0+ ? `GitHub App subscribes to broader events than Paperclip needs: ${excessiveEvents.join(", ")}`+ : null,+ ]+ .filter(Boolean)+ .join(". "),+ {+ code: "chat_provider_permissions_missing",+ provider: "github",+ missingPermissions,+ excessivePermissions,+ missingEvents,+ excessiveEvents,+ },+ );}+ return {+ githubOwnerType: result.owner?.type === "Organization" ? "organization" : result.owner?.type === "User" ? "personal" : undefined,+ githubOwnerLogin: result.owner?.login,+ providerAccountId: result.owner?.login,+ providerAccountLabel: result.owner?.login ?? result.name,+ // The App registration id is the stable, immutable endpoint identity.+ // The adapter discovers the separate bot-user id while initializing.+ botExternalId:+ typeof result.id === "number" && Number.isFinite(result.id)+ ? String(result.id)+ : undefined,+ botUsername: result.slug ? `${result.slug}[bot]` : undefined,+ botLabel: result.name ?? result.slug,+ };+ }+ if (provider === "speko") {+ if (!/^whsec_[A-Za-z0-9+/]{43}=$/.test(credentials.signingSecret ?? "")) throw unprocessable("Speko requires a Standard Webhooks signing secret");+ const identity = await createSpekoProvider(credentials.apiKey, fetchImpl).verifyAgent(credentials.agentId);+ return { providerAccountId: identity.organizationId, providerAccountLabel: "Speko workspace", botExternalId: identity.id, botLabel: identity.name };+ }+ const teamsCredentials = normalizeMicrosoftTeamsCredentialIds(credentials);+ const body = new URLSearchParams({+ client_id: teamsCredentials.clientId,+ client_secret: teamsCredentials.clientSecret,+ grant_type: "client_credentials",+ scope: "https://api.botframework.com/.default",});+ const response = await fetchImpl(+ `https://login.microsoftonline.com/${encodeURIComponent(teamsCredentials.tenantId)}/oauth2/v2.0/token`,+ {+ method: "POST",+ signal: AbortSignal.timeout(PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS),+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body,+ },+ );+ const result = (await response.json()) as {+ access_token?: string;+ error_description?: string;+ };+ if (!response.ok || !result.access_token)+ throw unprocessable(+ `Microsoft rejected the app credentials: ${result.error_description ?? response.status}`,+ );+ return {+ providerAccountId: teamsCredentials.tenantId,+ providerAccountLabel: teamsCredentials.tenantId,+ botExternalId: teamsCredentials.clientId,+ };}- function serializeEndpoint(- row: Awaited<ReturnType<typeof endpointRecord>>,- ): ChatEndpoint {- if (!row) throw notFound("Chat endpoint not found");- const endpoint = row.endpoint;- return {- id: endpoint.id,- companyId: endpoint.companyId,- connectionId: endpoint.connectionId,- publicationMode: endpoint.publicationMode,- externalExecutionPolicy: endpoint.externalExecutionPolicy,- provider: endpoint.provider,- publicId: endpoint.publicId,- status: endpoint.status,- deploymentMode: endpoint.deploymentMode,- assignedAgentId: endpoint.assignedAgentId,- assignedAgentName: row.assignedAgentName,- sponsorUserId: endpoint.sponsorUserId,- providerAccountId: endpoint.providerAccountId,- providerAccountLabel: endpoint.providerAccountLabel,- botExternalId: endpoint.botExternalId,- botUsername: endpoint.botUsername,- botLabel: endpoint.botDisplayName ?? row.assignedAgentName,- botAvatarUrl: endpoint.botAvatarUrl,- communicationInstructions: endpoint.communicationInstructions,- ...(endpoint.provider === "imessage-photon" && endpoint.botExternalId ? { photonAllocation: endpoint.botExternalId.startsWith("photon-project:") ? "shared" as const : "dedicated" as const } : {}),- allowDirectMessages: endpoint.allowDirectMessages,- requireAtMention: endpoint.requireAtMention,- allowGroupChats: endpoint.allowGroupChats,- allowUnlinkedPeople: endpoint.allowUnlinkedPeople,- replyMode: "subscribed",- capabilities: endpoint.capabilities,- setup: {- ...providerSetupState(- endpoint,- getWebhookPublicBaseUrl(),- row.assignedAgentName,- ),- ...(endpoint.provider === "github"- ? {- webhookSecretConfigured: row.credentialSecretRefs.some(- (ref) => ref.configPath === "credentials.webhookSecret",- ),- }- : endpoint.provider === "speko" ? {- webhookSecretConfigured: row.credentialSecretRefs.some(- (ref) => ref.configPath === "credentials.signingSecret",- ),- } : {}),- },- healthMessage: endpoint.healthMessage,- lastError: endpoint.lastError,- lastActivityAt: iso(endpoint.lastEventAt),- lastPublicationAt: iso(endpoint.lastPublicationAt),- activatedAt: iso(endpoint.activatedAt),- createdAt: endpoint.createdAt.toISOString(),- updatedAt: endpoint.updatedAt.toISOString(),- };+ function nativeBotIdentityKey(+ provider: ChatProvider,+ identity: VerifiedProviderIdentity,+ ): string | null {+ const account = identity.providerAccountId?.trim().toLowerCase();+ const bot = identity.botExternalId?.trim().toLowerCase();+ if (provider === "github" || provider === "discord") {+ if (bot) return `${provider}:app:${bot}`;+ return null;+ }+ if (!account || !bot) return null;+ return `${provider}:${account}:${bot}`;}- async function list(companyId: string) {- const rows = await db+ function providerUsesGlobalApplicationIdentity(+ provider: ChatProvider,+ ): boolean {+ return (+ provider === "github" ||+ provider === "discord" ||+ provider === "microsoft-teams" || provider === "imessage-photon"+ );+ }++ function nativeBotIdentityMatches(+ provider: ChatProvider,+ current: VerifiedProviderIdentity,+ incoming: VerifiedProviderIdentity,+ ): boolean {+ const currentKey = nativeBotIdentityKey(provider, current);+ return (+ currentKey !== null &&+ currentKey === nativeBotIdentityKey(provider, incoming)+ );+ }++ function legacyGitHubLabelsMatchVerifiedCredentials(+ current: VerifiedProviderIdentity,+ verified: VerifiedProviderIdentity,+ ): boolean {+ return (+ !current.botExternalId &&+ Boolean(verified.botExternalId) &&+ current.providerAccountId?.trim().toLowerCase() ===+ verified.providerAccountId?.trim().toLowerCase() &&+ current.botUsername?.trim().toLowerCase() ===+ verified.botUsername?.trim().toLowerCase()+ );+ }++ async function assertNativeBotIdentityAvailable(+ endpoint: EndpointRow,+ identity: VerifiedProviderIdentity,+ ): Promise<void> {+ const key = nativeBotIdentityKey(endpoint.provider, identity);+ if (!key) {+ throw unprocessable(+ `${PROVIDER_LABELS[endpoint.provider]} did not return a stable native bot identity`,+ );+ }+ const candidates = await db.select({- endpoint: chatEndpoints,- assignedAgentName: agents.name,- connectionName: toolConnections.name,- applicationId: toolConnections.applicationId,- credentialSecretRefs: toolConnections.credentialSecretRefs,+ id: chatEndpoints.id,+ companyId: chatEndpoints.companyId,+ assignedAgentId: chatEndpoints.assignedAgentId,+ providerAccountId: chatEndpoints.providerAccountId,+ botExternalId: chatEndpoints.botExternalId,+ botUsername: chatEndpoints.botUsername,}).from(chatEndpoints)- .innerJoin(- agents,- and(- eq(agents.id, chatEndpoints.assignedAgentId),- eq(agents.companyId, chatEndpoints.companyId),- ),- )- .innerJoin(- toolConnections,- and(- eq(toolConnections.id, chatEndpoints.connectionId),- eq(toolConnections.companyId, chatEndpoints.companyId),- ),- ).where(and(- eq(chatEndpoints.companyId, companyId),- ne(chatEndpoints.status, "archived"),+ providerUsesGlobalApplicationIdentity(endpoint.provider)+ ? undefined+ : eq(chatEndpoints.companyId, endpoint.companyId),+ eq(chatEndpoints.provider, endpoint.provider),+ ne(chatEndpoints.id, endpoint.id),+ endpoint.provider === "imessage-photon" ? ne(chatEndpoints.status, "archived") : inArray(chatEndpoints.status, [+ "verifying",+ "active",+ "paused",+ "attention",+ ]),),- )- .orderBy(desc(chatEndpoints.updatedAt));- return rows.map((row) => serializeEndpoint(row));+ );+ const conflictEndpoint = candidates.find((candidate) => {+ if (!providerUsesGlobalApplicationIdentity(endpoint.provider)) {+ return nativeBotIdentityKey(endpoint.provider, candidate) === key;+ }+ const candidateAppId = candidate.botExternalId?.trim().toLowerCase();+ const incomingAppId = identity.botExternalId?.trim().toLowerCase();+ if (candidateAppId && incomingAppId)+ return candidateAppId === incomingAppId;+ return (+ candidate.providerAccountId?.trim().toLowerCase() ===+ identity.providerAccountId?.trim().toLowerCase() &&+ candidate.botUsername?.trim().toLowerCase() ===+ identity.botUsername?.trim().toLowerCase()+ );+ });+ if (conflictEndpoint) {+ throw conflict(+ `This ${PROVIDER_LABELS[endpoint.provider]} bot already represents another Paperclip agent connection`,+ conflictEndpoint.companyId === endpoint.companyId+ ? {+ code: "chat_bot_identity_in_use",+ endpointId: conflictEndpoint.id,+ assignedAgentId: conflictEndpoint.assignedAgentId,+ }+ : { code: "chat_bot_identity_in_use" },+ );+ }}- async function get(endpointId: string) {- const result = serializeEndpoint(await endpointRecord(endpointId));- if (result.provider === "slack") {- const [registration] = await db.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, endpointId));- result.setup.slackRegistration = registration ? slackRegistrationProjection(registration) : undefined;- const publicOrigin = getPublicBaseUrl();- result.setup.slackOAuthCallbackUri = publicOrigin ? `${publicOrigin}/api/chat-slack/oauth/callback` : null;- }- return result;+ function isNativeBotIdentityUniqueViolation(error: unknown): boolean {+ return (+ isUniqueViolation(error, "chat_endpoints_photon_number_uq") ||+ isUniqueViolation(error, "chat_endpoints_live_bot_external_uq") ||+ isUniqueViolation(error, "chat_endpoints_live_discord_bot_external_uq") ||+ isUniqueViolation(+ error,+ "chat_endpoints_live_global_app_bot_external_uq",+ ) ||+ isUniqueViolation(error, "chat_endpoints_live_bot_username_uq")+ );}- async function create(- companyId: string,- input: CreateChatEndpointInput,+ function nativeBotIdentityConflict(provider: ChatProvider) {+ return conflict(+ `This ${PROVIDER_LABELS[provider]} bot already represents another Paperclip agent connection`,+ { code: "chat_bot_identity_in_use" },+ );+ }++ async function persistCredentials(+ endpoint: EndpointRow,+ credentials: Record<string, string>,+ credentialLease: CredentialMutationLeaseGuard,actorUserId?: string | null,) {- if ((input.provider as string) === "agentmail") throw badRequest("Use the email inbox setup API for AgentMail");- if ((input.slackApp || input.slackSetupMethod) && input.provider !== "slack") throw unprocessable("Slack app details only apply to Slack connections");- if (input.slackSetupMethod === "managed" && slackRegistration.managerGrants.defaultMethod() !== "managed") throw conflict("Managed Slack setup is unavailable");- const agent = await db- .select({ id: agents.id, name: agents.name, status: agents.status })- .from(agents)+ await credentialLease.assertOwned();+ const previousRefs = await db+ .select({ refs: toolConnections.credentialSecretRefs })+ .from(toolConnections).where(and(- eq(agents.companyId, companyId),- eq(agents.id, input.assignedAgentId),+ eq(toolConnections.companyId, endpoint.companyId),+ eq(toolConnections.id, endpoint.connectionId),),)- .then((rows) => rows[0] ?? null);- if (!agent)- throw unprocessable("The selected agent does not belong to this company");- if (!isAgentStatusInvokable(agent.status)) {- throw unprocessable(- "The selected agent must be active before it can be connected to chat",- {- code: "chat_agent_not_invokable",- },- );- }-- const endpointId = randomUUID();- const publicId = randomBytes(32).toString("base64url");- const applicationId = input.applicationId ?? randomUUID();- const connectionId = randomUUID();- const suffix = endpointId.slice(0, 8);- const name = (- input.name?.trim() || `${PROVIDER_LABELS[input.provider]} — ${agent.name}`- ).slice(0, 145);- await db.transaction(async (tx) => {- if (input.applicationId) {- const application = await tx- .select({- id: toolApplications.id,- applicationKey: toolApplications.applicationKey,- metadata: toolApplications.metadata,- status: toolApplications.status,- })- .from(toolApplications)- .where(- and(- eq(toolApplications.companyId, companyId),- eq(toolApplications.id, input.applicationId),- ),- )- .then((rows) => rows[0] ?? null);- if (!application) throw notFound("App not found");- const sourceTemplateKey =- typeof application.metadata.sourceTemplateKey === "string"- ? application.metadata.sourceTemplateKey- : null;+ .then((rows) => rows[0]?.refs ?? []);+ const refs: ToolCredentialSecretRef[] = [];+ try {+ for (const [key, value] of Object.entries(credentials)) {+ if (endpoint.provider === "imessage-photon" && key !== "projectSecret") continue;+ await credentialLease.assertOwned();+ const suffix = randomUUID();+ const secret = await secrets.create(+ endpoint.companyId,+ {+ name: `chat.${endpoint.provider}.${endpoint.id.slice(0, 8)}.${key}.${suffix.slice(0, 8)}`,+ key: `CHAT_${endpoint.provider.replaceAll("-", "_")}_${endpoint.id.replaceAll("-", "_")}_${key}_${suffix}`.toUpperCase(),+ provider: "local_encrypted",+ managedMode: "paperclip_managed",+ value,+ description: `${PROVIDER_LABELS[endpoint.provider]} channel credential for endpoint ${endpoint.id}`,+ },+ { userId: actorUserId ?? undefined },+ );+ refs.push({+ secretId: secret.id,+ versionSelector: "latest",+ configPath: `credentials.${key}`,+ required: true,+ label: key,+ projectionClass: "unclassified",+ });+ await credentialLease.assertOwned();+ }+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ const current = await tx+ .select({ refs: toolConnections.credentialSecretRefs })+ .from(toolConnections)+ .where(+ and(+ eq(toolConnections.companyId, endpoint.companyId),+ eq(toolConnections.id, endpoint.connectionId),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ if (!current) throw notFound("Chat connection not found");if (- application.status === "archived" ||- (application.applicationKey !== input.provider &&- sourceTemplateKey !== input.provider)+ credentialFingerprint(current.refs) !==+ credentialFingerprint(previousRefs)) {- throw unprocessable(- `The selected App is not the ${PROVIDER_LABELS[input.provider]} connector`,+ throw conflict("Chat credentials changed during rotation", {+ code: "chat_endpoint_credentials_changed",+ });+ }+ await tx+ .delete(companySecretBindings)+ .where(+ and(+ eq(companySecretBindings.companyId, endpoint.companyId),+ eq(companySecretBindings.targetType, "tool_connection"),+ eq(companySecretBindings.targetId, endpoint.connectionId),+ ),+ );+ if (refs.length > 0) {+ await tx.insert(companySecretBindings).values(+ refs.map((ref) => ({+ companyId: endpoint.companyId,+ secretId: ref.secretId,+ targetType: "tool_connection",+ targetId: endpoint.connectionId,+ configPath: ref.configPath,+ versionSelector: String(ref.versionSelector ?? "latest"),+ required: ref.required,+ label: ref.label ?? null,+ projectionClass: ref.projectionClass ?? "unclassified",+ projectionAllowlistKey: ref.projectionAllowlistKey ?? null,+ })),);}- } else {- await tx.insert(toolApplications).values({- id: applicationId,- companyId,- applicationKey: `chat:${input.provider}:${endpointId}`,- name: `${name} ${suffix}`,- description: `People talk to ${agent.name} through ${PROVIDER_LABELS[input.provider]}.`,- type: "chat",- status: "draft",- metadata: { sourceTemplateKey: input.provider, purpose: "channel" },- ownerUserId: actorUserId ?? null,- });- }- await tx.insert(toolConnections).values({- id: connectionId,- companyId,- applicationId,- name,- uid: `chat-${input.provider}-${endpointId}`,- connectionKind: "managed",- connectionPurpose: "channel",- ownership: "customer",- transport: input.provider === "speko" ? "voice" : "chat_sdk",- authKind: "api_key",- credentialPolicy: "shared",- status: "draft",- enabled: false,- config: { provider: input.provider },- transportConfig: {},- createdByUserId: actorUserId ?? null,- });- await tx.insert(chatEndpoints).values({- id: endpointId,- companyId,- connectionId,- provider: input.provider,- publicId,- assignedAgentId: agent.id,- sponsorUserId: actorUserId ?? null,- // Group chat is a broad Teams reach grant rather than a discovered- // destination toggle. Keep it closed until the operator explicitly- // enables that surface, even when this process is running against a- // database created before the column default was hardened.- requireAtMention: input.provider === "slack",- allowGroupChats: !["microsoft-teams", "speko"].includes(input.provider),- allowUnlinkedPeople: !["slack", "imessage-photon", "speko"].includes(input.provider),- capabilities: CAPABILITIES[input.provider],- setup: {- step: "provider_setup",- ...(input.provider === "slack"- ? { slackApp: input.slackApp ?? defaultSlackAppConfiguration(agent.name),- command: (input.slackApp ?? defaultSlackAppConfiguration(agent.name)).command, slackSetupMethod: input.slackSetupMethod ?? slackRegistration.managerGrants.defaultMethod() }- : {}),- },+ await tx+ .update(toolConnections)+ .set({ credentialSecretRefs: refs, updatedAt: new Date() })+ .where(eq(toolConnections.id, endpoint.connectionId));+ await credentialLease.assertOwned(tx);});- });- await logActivity(db, {- companyId,- actorType: "user",- actorId: actorUserId ?? "board",- action: "chat_endpoint.created",- entityType: "tool_connection",- entityId: connectionId,- details: {- endpointId,- provider: input.provider,- assignedAgentId: agent.id,- },- });- return get(endpointId);+ } catch (error) {+ // A lost database acknowledgement can be ambiguous even when the+ // transaction committed. Delete only secrets proven unbound after the+ // failure; when that proof cannot be read, leak safely for later cleanup+ // instead of deleting a possibly-authoritative credential.+ const boundSecretIds =+ refs.length === 0+ ? new Set<string>()+ : await db+ .select({ secretId: companySecretBindings.secretId })+ .from(companySecretBindings)+ .where(+ and(+ eq(companySecretBindings.companyId, endpoint.companyId),+ inArray(+ companySecretBindings.secretId,+ refs.map((ref) => ref.secretId),+ ),+ ),+ )+ .then((rows) => new Set(rows.map((row) => row.secretId)))+ .catch(() => null);+ if (boundSecretIds) {+ await Promise.allSettled(+ refs+ .filter((ref) => !boundSecretIds.has(ref.secretId))+ .map((ref) => secrets.remove(ref.secretId)),+ );+ }+ throw error;+ }+ const currentIds = new Set(refs.map((ref) => ref.secretId));+ const retired = previousRefs.filter((ref) => !currentIds.has(ref.secretId));+ const results = await Promise.allSettled(+ retired.map((ref) => secrets.remove(ref.secretId)),+ );+ if (results.some((result) => result.status === "rejected")) {+ logger.warn(+ { endpointId: endpoint.id },+ "chat credential rotation left an unbound retired secret for later cleanup",+ );+ }+ return refs;}- async function update(- endpointId: string,- input: UpdateChatEndpointInput,- actorUserId?: string | null,+ async function clearCredentials(+ endpoint: EndpointRow,+ credentialLease: CredentialMutationLeaseGuard,) {- const initial = await endpointRecord(endpointId);- if (!initial) throw notFound("Chat endpoint not found");- if (initial.endpoint.provider === "agentmail") throw badRequest("Use the email inbox API for AgentMail");- await withCredentialMutationLease(- initial.endpoint,- async (credentialLease) => {- // Reach changes share the provider-transport lane with publications.- // Once a disable returns, no send that sampled the previous grant can- // still begin or finish behind it.- const existing = await endpointRecord(endpointId);- if (!existing) throw notFound("Chat endpoint not found");- const values: Partial<typeof chatEndpoints.$inferInsert> = {- updatedAt: new Date(),- };- if (input.communicationInstructions !== undefined) {- if (existing.endpoint.provider !== "slack") {- throw unprocessable("Communication instructions are currently supported for Slack connections");- }- values.communicationInstructions = input.communicationInstructions;- }- if (input.slackSetupMethod === "managed" && slackRegistration.managerGrants.defaultMethod() !== "managed") throw conflict("Managed Slack setup is unavailable");- if (input.slackSetupMethod && (existing.endpoint.provider !== "slack" || existing.endpoint.botExternalId || existing.endpoint.status !== "draft")) {- throw conflict("Setup method can only change before connecting the app");- }- if (input.slackApp || input.slackSetupMethod) {- const [registration] = await db.select().from(chatSlackRegistrations).where(eq(chatSlackRegistrations.endpointId, endpointId));- if (registration && (registration.managerGrantId || registration.status !== "failed")) {- if (registration.managerGrantId || input.slackSetupMethod === "managed" || input.slackApp || input.slackSetupMethod === "automatic") throw conflict("Slack app details are locked after creation starts");- // Manual recovery fences pending authorization under the same credential lease.- await slackRegistration.cleanup(endpointId, credentialLease);- }- }- if (input.slackSetupMethod) {- values.setup = { ...existing.endpoint.setup, slackSetupMethod: input.slackSetupMethod };- }- if (input.slackApp) {- if (existing.endpoint.provider !== "slack") {- throw unprocessable("Slack app details only apply to Slack connections");- }- if (existing.endpoint.status !== "draft" || existing.endpoint.botExternalId) {- throw conflict("Slack app details can only be edited before connecting the app");- }- values.setup = {- ...(values.setup ?? existing.endpoint.setup),- slackApp: input.slackApp,- command: input.slackApp.command,- };- }- if (input.allowDirectMessages !== undefined)- values.allowDirectMessages = input.allowDirectMessages;- if (input.requireAtMention !== undefined) {- if (existing.endpoint.provider !== "slack")- throw unprocessable("Require at-mention only applies to Slack connections");- values.requireAtMention = input.requireAtMention;- }- if (input.allowGroupChats && existing.endpoint.provider === "imessage-photon" && (!existing.endpoint.botExternalId || existing.endpoint.botExternalId.startsWith("photon-project:")))- throw unprocessable("Photon shared channels support direct messages only; groups require a dedicated channel");- if (input.allowGroupChats !== undefined)- values.allowGroupChats = input.allowGroupChats;- if (input.allowUnlinkedPeople !== undefined)- values.allowUnlinkedPeople = input.allowUnlinkedPeople;- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- await tx- .update(chatEndpoints)- .set(values)- .where(eq(chatEndpoints.id, endpointId));- await logActivity(tx as unknown as Db, {- companyId: existing.endpoint.companyId,- actorType: "user",- actorId: actorUserId ?? "board",- action: "chat_endpoint.updated",- entityType: "tool_connection",- entityId: existing.endpoint.connectionId,- details: { endpointId, fields: Object.keys(input) },- });- await credentialLease.assertOwned(tx);- });- },- );- return get(endpointId);- }-- async function normalizedCredentials(- endpoint: EndpointRow,- supplied: Record<string, string> | undefined,- ) {- const values = await resolveCredentials(endpoint).catch(- () => ({}) as Record<string, string>,+ let refs: ToolCredentialSecretRef[] = [];+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ const current = await tx+ .select({ refs: toolConnections.credentialSecretRefs })+ .from(toolConnections)+ .where(+ and(+ eq(toolConnections.companyId, endpoint.companyId),+ eq(toolConnections.id, endpoint.connectionId),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ if (!current) throw notFound("Chat connection not found");+ refs = current.refs;+ await tx+ .delete(companySecretBindings)+ .where(+ and(+ eq(companySecretBindings.companyId, endpoint.companyId),+ eq(companySecretBindings.targetType, "tool_connection"),+ eq(companySecretBindings.targetId, endpoint.connectionId),+ ),+ );+ await tx+ .update(toolConnections)+ .set({ credentialSecretRefs: [], updatedAt: new Date() })+ .where(eq(toolConnections.id, endpoint.connectionId));+ await credentialLease.assertOwned(tx);+ });+ const results = await Promise.allSettled(+ refs.map((ref) => secrets.remove(ref.secretId)),);- for (const [key, rawValue] of Object.entries(supplied ?? {})) {- if (typeof rawValue === "string" && rawValue.trim())- values[key] = key === "privateKey" ? rawValue : rawValue.trim();- }- if (endpoint.provider === "telegram" && !values.webhookSecret) {- values.webhookSecret = randomBytes(32).toString("hex");- }- const required =- endpoint.provider === "github"- ? ["appId", "privateKey", "webhookSecret"]- : REQUIRED_CREDENTIALS[endpoint.provider];- const missing = required.filter((key) => !values[key]);- if (missing.length > 0) {- throw unprocessable(- `Missing required ${PROVIDER_LABELS[endpoint.provider]} credentials: ${missing.join(", ")}`,+ if (results.some((result) => result.status === "rejected")) {+ logger.warn(+ { endpointId: endpoint.id },+ "chat endpoint removal left an unbound retired secret for later cleanup",);}- return endpoint.provider === "microsoft-teams"- ? normalizeMicrosoftTeamsCredentialIds(values)- : values;}- async function verifyCredentials(- provider: ChatProvider,- credentials: Record<string, string>,- ): Promise<VerifiedProviderIdentity> {- if (provider === "imessage-photon") {- const inspection = await inspectPhotonCredentials(credentials.projectId, credentials.projectSecret);- if (inspection.allocation !== (credentials.allocation ?? "dedicated")) throw unprocessable("Photon allocation changed; inspect the project again");- if (inspection.allocation === "shared") {- if (!inspection.eligible) throw unprocessable("Photon shared project is unavailable");- return { providerAccountId: inspection.projectId, providerAccountLabel: inspection.projectName, botExternalId: photonSharedIdentity(inspection.projectId), botUsername: null, botLabel: `${inspection.projectName} (DM only)` };- }- const line = inspection.lines.find((candidate) => candidate.lineId === credentials.lineId && candidate.eligible);- if (!line || !inspection.eligible) throw unprocessable("Select an eligible dedicated Photon line");- return { providerAccountId: inspection.projectId, providerAccountLabel: inspection.projectName, botExternalId: line.phoneNumber, botUsername: line.phoneNumber, botLabel: line.phoneNumber };- }- if (provider === "slack") {- const response = await fetchImpl("https://slack.com/api/auth.test", {- method: "POST",- signal: AbortSignal.timeout(PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS),- headers: {- authorization: `Bearer ${credentials.botToken}`,- "content-type": "application/x-www-form-urlencoded",+ async function resolveCredentialRefs(+ endpoint: EndpointRow,+ refs: ToolCredentialSecretRef[],+ database: DbOrTransaction = db,+ ): Promise<Record<string, string>> {+ const values: Record<string, string> = {};+ for (const ref of refs) {+ const key = ref.configPath.replace(/^credentials\./, "");+ values[key] = await (database === db ? secrets : secretService(database as Db)).resolveSecretValue(+ endpoint.companyId,+ ref.secretId,+ ref.versionSelector ?? "latest",+ {+ consumerType: "tool_connection",+ consumerId: endpoint.connectionId,+ configPath: ref.configPath,+ actorType: "system",+ actorId: null,},- body: "",- });- const result = (await response.json()) as {- ok?: boolean;- error?: string;- team_id?: string;- team?: string;- user_id?: string;- user?: string;- };- if (!response.ok || !result.ok)- throw unprocessable(- `Slack rejected the bot token: ${result.error ?? response.status}`,- );- const grantedScopes = new Set(- (response.headers.get("x-oauth-scopes") ?? "")- .split(",")- .map((scope) => scope.trim())- .filter(Boolean),- );- const missingScopes = REQUIRED_SLACK_BOT_SCOPES.filter(- (scope) => !grantedScopes.has(scope),);- if (missingScopes.length > 0) {- throw unprocessable(- `Slack app is missing required bot scopes: ${missingScopes.join(", ")}`,- {- code: "chat_provider_permissions_missing",- provider: "slack",- missingScopes,- },- );- }- return {- providerAccountId: result.team_id,- providerAccountLabel: result.team,- botExternalId: result.user_id,- botUsername: result.user,- botLabel: result.user,- };}- if (provider === "discord") {- const identity = await verifyDiscordBot({- applicationId: credentials.applicationId,- botToken: credentials.botToken,- fetch: fetchImpl,- guildId: credentials.guildId,- }).catch((error) => {- throw unprocessable(redactError(error), {- code: "chat_provider_permissions_missing",- provider: "discord",- });- });- return identity;+ return values;+ }++ async function resolveCredentials(+ endpoint: EndpointRow,+ database: DbOrTransaction = db,+ ): Promise<Record<string, string>> {+ const connection = await database+ .select({ refs: toolConnections.credentialSecretRefs, config: toolConnections.config })+ .from(toolConnections)+ .where(+ and(+ eq(toolConnections.companyId, endpoint.companyId),+ eq(toolConnections.id, endpoint.connectionId),+ ),+ )+ .then((rows) => rows[0] ?? null);+ if (!connection) throw notFound("Chat connection not found");+ const values = await resolveCredentialRefs(endpoint, connection.refs, database);+ if (endpoint.provider === "imessage-photon") {+ const configuration = photonChannelConfigurationSchema.parse(connection.config.photon);+ return { ...values, ...configuration, lineId: configuration.allocation === "shared" ? photonSharedScope(configuration.projectId) : configuration.lineId };}- if (provider === "telegram") {- const response = await fetchImpl(- `https://api.telegram.org/bot${encodeURIComponent(credentials.botToken)}/getMe`,- { signal: AbortSignal.timeout(PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS) },+ return values;+ }++ const withCredentialMutationLease = chatCredentialMutationLease(db, options);+ const { setupTestStatus, test } = createSetupProbes(db, { endpointRecord, withCredentialMutationLease, fetchImpl, findAuthorizedIdentityLink, runtimeGeneration, lockCurrentPrincipalAuthorization, get, setupTestActivationBarrier: () => options.setupTestActivationBarrier?.() ?? Promise.resolve() });+ const { listConversations, listActivity, listActivityPage } = createChatActivity(db, { endpointRecord, teamsTransferProtocol });+ const { lockTelegramCallbackNoticeAuthority } = createTelegramCallbackNoticeAuthority({ nonDirectDestinationAllowed, lockCurrentPrincipalAuthorization });+ const { stageProviderEffect, processProviderEffect, processPendingProviderEffects } = createProviderEffects(db, { endpointRecord, runtimeCallbackEndpoint, withCredentialMutationLease, runtimeFor, invalidateRuntime, lockCurrentPrincipalAuthorization, redactError, MAX_ERROR_TEXT, nonDirectDestinationAllowed, lockTelegramCallbackNoticeAuthority });+ const { publicationFiles } = createOutboundAttachments(db, { get storage() { return options.storage; } });+ const { ingestAttachments, attachmentOmissionDetail } = createInboundAttachments(db, { authorizeInboundWakeup, lifecycleRuntimeFence, sanitizeFilename, issuesSvc, isExternalActionAuthorizationChange, redactError, get storage() { return options.storage; } });+ const { handleReaction, processPendingReactionDeliveries } = createInboundReactions(db, { lockCurrentPrincipalAuthorization, runtimeCallbackRecord, runtimeCallbackEndpoint, ensurePrincipal, durableExternalThreadIdentity, recordCurrentMicrosoftTeamsRoute, lifecycleRuntimeFence, deliveryReady, redactError, nonDirectDestinationAllowed, reactionLinkPreflightBarrier: () => options.reactionLinkPreflightBarrier?.() ?? Promise.resolve(), reactionReplayEndpointLockBarrier: () => options.reactionReplayEndpointLockBarrier?.() ?? Promise.resolve(), reactionReplayConversationLockBarrier: () => options.reactionReplayConversationLockBarrier?.() ?? Promise.resolve() });+ const { addReceiptReaction, processReceiptReaction, processPendingReceiptReactions } = createReceiptReactions(db, { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, runtimeFor, fetchImpl, runtime, runtimeGeneration, credentialFingerprint, redactError, MAX_ERROR_TEXT, receiptReactionTransportBarrier: () => options.receiptReactionTransportBarrier?.() ?? Promise.resolve() });+ const { admitDiscordRootMention, discordRootThreadPending, reconcileDiscordRootThread } = createDiscordRootThreads(db, { ensureDiscordGatewayRuntimeIsCurrent, withCredentialMutationLease, runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, processMessage, redactError, scheduleConversationDrain, lifecycleRuntimeFence, runtimeFor, DISCORD_ROOT_THREAD_CONFIRMATION_DELAY_MS, discordRootThreadTransportBarrier: () => options.discordRootThreadTransportBarrier?.() ?? Promise.resolve() });+ const { handleDiscordGatewayEvent } = createDiscordGatewayEvents(db, { ensureDiscordGatewayRuntimeIsCurrent, discordGatewayRuntimeIsCurrent, runtimeCallbackRecord, runtimeCallbackEndpoint, applyProviderLifecycleEffect, runtimeGeneration, discordGatewayEventBarrier: (event) => options.discordGatewayEventBarrier?.(event) ?? Promise.resolve() });+ const { handlePhotonFailure, handlePhotonEvent } = createPhotonEvents(db, { runtimeCallbackRecord, runtimeCallbackEndpoint, invalidateRuntime, ensurePrincipal, requireCurrentExternalActionAuthorization, isExternalActionAuthorizationChange, scheduleMessageProcessing, processPendingPublications, questionResponses, redactError, renewDiscordGatewayOwnershipForMessageAdmission, handleSdkMessage });+ const { handleTelegramGenerationStopped, reserveTelegramPublicationDraft } = createTelegramPublicationDrafts(db, { runtimeCallbackRecord, runtimeCallbackEndpoint, runtimeFor, runtime, runtimeContexts, credentialFingerprint, authorizeRetainedChatSourcePublication });+ const { recordSlackFileUploadReceipt, stageSlackFilePublicationSuccess, processPendingSlackFileUploadReceipts, nextSlackReceiptAt } = createSlackFileReceipts(db, { endpointRecord, withCredentialMutationLease, runtimeCallbackEndpoint, nonDirectDestinationAllowed, runtimeFor, isExplicitOperatorPublication, recordExactOutboundPublicationLink });+ const { processPendingSlackSessionSyncs } = createSlackSessionStatus(db, { endpointRecord, withCredentialMutationLease, runtimeCallbackEndpoint, nonDirectDestinationAllowed, runIdFromMilestonePublication, resolveCredentials, fetchImpl, redactError, get slackSessionSyncSelectionBarrier() { return options.slackSessionSyncSelectionBarrier; } });+ const { reconcileDiscordCommands, handleDiscordNativeCommand } = createDiscordCommands(db, { endpointRecord, runtimeContextForRecord, runtimeGeneration, credentialFingerprint, resolveCredentialRefs, fetchImpl, withCredentialMutationLease, runtimeCallbackRecord, ensurePrincipal, runtimeCallbackEndpoint, nonDirectDestinationAllowed, lockCurrentPrincipalAuthorization, getDiscordGatewayOwnership: (endpointId) => discordGatewayOwnerships.get(endpointId), discordGatewayRuntimeIsCurrent, stageAuthorizedTaskControlPublication, scheduleMessageProcessing, processPendingPublications });+ const { latestSlackDmControlThreadId, finalizeSlackTaskStartFailure, admitConfirmedSlackTaskStart, processSlackTaskStart, processPendingSlackTaskStarts } = createSlackTaskStart(db, { endpointRecord, runtimeGeneration, credentialFingerprint, invalidateRuntime, runtimeFor, processMessage, runtimeContextForRecord, redactError, withCredentialMutationLease, sponsorAllowsGuest, nonDirectDestinationAllowed, runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, get slackTaskAdmissionClaimBarrier() { return options.slackTaskAdmissionClaimBarrier; }, maxErrorText: MAX_ERROR_TEXT });+ const { stageGitHubWebhookIngress, githubIngressAcceptedResponse, processGitHubWebhookIngress, processFailedGitHubWebhookDeliveries, processPendingGitHubWebhookIngress } = createGitHubWebhookIngress(db, { endpointRecord, runtimeContextForRecord, resolveCredentialRefs, runtimeGeneration, credentialFingerprint, getWebhookPublicBaseUrl, redactError, handleWebhook, runtimeCallbackEndpoint, fetchImpl, persistence, withCredentialMutationLease, isShuttingDown: () => shuttingDown, get githubWebhookReplayBarrier() { return options.githubWebhookReplayBarrier; }, supportedWebhookEvents: SUPPORTED_GITHUB_WEBHOOK_EVENTS });+ const { stageSlackSessionStop, processSlackSessionStop, processPendingSlackSessionStops } = createSlackSessionStop(db, { runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, nonDirectDestinationAllowed, stageAuthorizedTaskControlPublication, getPublicBaseUrl, get heartbeat() { return options.heartbeat; }, redactError });+ const { stageTelegramMaintenance, processTelegramMaintenance, processPendingTelegramMaintenance, hasTelegramStopSubscription, recordTelegramStopSubscription } = createTelegramMaintenance(db, { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, resolveCredentials, clearCredentials, runtimeCallbackEndpoint, getWebhookPublicBaseUrl, fetchImpl, runtimeGeneration, credentialFingerprint, redactError, credentialCheckTimeoutMs: PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS });+ const { reconcileGitHubWebhookRepository, reconcileProviderResourceRows, listResources, listGitHubRepositories, replaceResources, toggleAllGitHubRepositories, hasNewerProcessedProviderLifecycleEffect, applyProviderAvailability } = createChatResourceReconciliation(db, { endpointRecord, withCredentialMutationLease, runtimeGeneration, maxErrorText: MAX_ERROR_TEXT });++ async function generateSetupSecret(+ endpointId: string,+ actorUserId?: string | null,+ ) {+ const initial = await endpointRecord(endpointId);+ if (!initial) throw notFound("Chat endpoint not found");+ if (initial.endpoint.provider !== "github") {+ throw unprocessable(+ "Setup secret generation is only available for GitHub",);- const result = (await response.json()) as {- ok?: boolean;- description?: string;- result?: { id?: number; username?: string; first_name?: string };- };- if (!response.ok || !result.ok)- throw unprocessable(- `Telegram rejected the bot token: ${result.description ?? response.status}`,- );- return {- providerAccountId: String(result.result?.id ?? ""),- botExternalId: String(result.result?.id ?? ""),- botUsername: result.result?.username,- botLabel: result.result?.first_name,- };}- if (provider === "github") {- const token = githubAppJwt(credentials.appId, credentials.privateKey);- const response = await fetchImpl("https://api.github.com/app", {- signal: AbortSignal.timeout(PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS),- headers: {- accept: "application/vnd.github+json",- authorization: `Bearer ${token}`,- "x-github-api-version": "2022-11-28",- },- });- const result = (await response.json()) as {- id?: number;- login?: string;- slug?: string;- name?: string;- message?: string;- owner?: { login?: string; type?: string };- permissions?: Record<string, string>;- events?: string[];- };- if (!response.ok)- throw unprocessable(- `GitHub rejected the app credentials: ${result.message ?? response.status}`,- );- const missingPermissions = Object.entries(REQUIRED_GITHUB_PERMISSIONS)- .filter(- ([permission, access]) => result.permissions?.[permission] !== access,- )- .map(([permission]) => permission);- const excessivePermissions = Object.keys(result.permissions ?? {}).filter(- (permission) => !(permission in REQUIRED_GITHUB_PERMISSIONS) && !((permission === "contents" && result.permissions?.contents === "read") || (permission === "checks" && result.permissions?.checks === "write")),- );- const configuredEvents = new Set(result.events ?? []);- const missingEvents = REQUIRED_GITHUB_EVENTS.filter(- (event) => !configuredEvents.has(event),- );- const allowedEvents = new Set<string>([- ...REQUIRED_GITHUB_EVENTS,- ...UNAVOIDABLE_GITHUB_EVENTS,- "pull_request",- "pull_request_review",- "issues",- ]);- const excessiveEvents = [...configuredEvents].filter(- (event) => !allowedEvents.has(event),- );- if (- missingPermissions.length > 0 ||- excessivePermissions.length > 0 ||- missingEvents.length > 0 ||- excessiveEvents.length > 0- ) {- throw unprocessable(- [- missingPermissions.length > 0- ? `GitHub App needs the documented minimum access for: ${missingPermissions.join(", ")}`- : null,- excessivePermissions.length > 0- ? `GitHub App has broader permissions than Paperclip needs: ${excessivePermissions.join(", ")}`- : null,- missingEvents.length > 0- ? `GitHub App must subscribe to: ${missingEvents.join(", ")}`- : null,- excessiveEvents.length > 0- ? `GitHub App subscribes to broader events than Paperclip needs: ${excessiveEvents.join(", ")}`- : null,- ]- .filter(Boolean)- .join(". "),- {- code: "chat_provider_permissions_missing",- provider: "github",- missingPermissions,- excessivePermissions,- missingEvents,- excessiveEvents,- },- );- }- return {- githubOwnerType: result.owner?.type === "Organization" ? "organization" : result.owner?.type === "User" ? "personal" : undefined,- githubOwnerLogin: result.owner?.login,- providerAccountId: result.owner?.login,- providerAccountLabel: result.owner?.login ?? result.name,- // The App registration id is the stable, immutable endpoint identity.- // The adapter discovers the separate bot-user id while initializing.- botExternalId:- typeof result.id === "number" && Number.isFinite(result.id)- ? String(result.id)- : undefined,- botUsername: result.slug ? `${result.slug}[bot]` : undefined,- botLabel: result.name ?? result.slug,- };- }- if (provider === "speko") {- if (!/^whsec_[A-Za-z0-9+/]{43}=$/.test(credentials.signingSecret ?? "")) throw unprocessable("Speko requires a Standard Webhooks signing secret");- const identity = await createSpekoProvider(credentials.apiKey, fetchImpl).verifyAgent(credentials.agentId);- return { providerAccountId: identity.organizationId, providerAccountLabel: "Speko workspace", botExternalId: identity.id, botLabel: identity.name };- }- const teamsCredentials = normalizeMicrosoftTeamsCredentialIds(credentials);- const body = new URLSearchParams({- client_id: teamsCredentials.clientId,- client_secret: teamsCredentials.clientSecret,- grant_type: "client_credentials",- scope: "https://api.botframework.com/.default",- });- const response = await fetchImpl(- `https://login.microsoftonline.com/${encodeURIComponent(teamsCredentials.tenantId)}/oauth2/v2.0/token`,- {- method: "POST",- signal: AbortSignal.timeout(PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS),- headers: { "content-type": "application/x-www-form-urlencoded" },- body,- },- );- const result = (await response.json()) as {- access_token?: string;- error_description?: string;- };- if (!response.ok || !result.access_token)- throw unprocessable(- `Microsoft rejected the app credentials: ${result.error_description ?? response.status}`,- );- return {- providerAccountId: teamsCredentials.tenantId,- providerAccountLabel: teamsCredentials.tenantId,- botExternalId: teamsCredentials.clientId,- };- }-- function nativeBotIdentityKey(- provider: ChatProvider,- identity: VerifiedProviderIdentity,- ): string | null {- const account = identity.providerAccountId?.trim().toLowerCase();- const bot = identity.botExternalId?.trim().toLowerCase();- if (provider === "github" || provider === "discord") {- if (bot) return `${provider}:app:${bot}`;- return null;- }- if (!account || !bot) return null;- return `${provider}:${account}:${bot}`;- }-- function providerUsesGlobalApplicationIdentity(- provider: ChatProvider,- ): boolean {- return (- provider === "github" ||- provider === "discord" ||- provider === "microsoft-teams" || provider === "imessage-photon"- );- }-- function nativeBotIdentityMatches(- provider: ChatProvider,- current: VerifiedProviderIdentity,- incoming: VerifiedProviderIdentity,- ): boolean {- const currentKey = nativeBotIdentityKey(provider, current);- return (- currentKey !== null &&- currentKey === nativeBotIdentityKey(provider, incoming)- );- }-- function legacyGitHubLabelsMatchVerifiedCredentials(- current: VerifiedProviderIdentity,- verified: VerifiedProviderIdentity,- ): boolean {- return (- !current.botExternalId &&- Boolean(verified.botExternalId) &&- current.providerAccountId?.trim().toLowerCase() ===- verified.providerAccountId?.trim().toLowerCase() &&- current.botUsername?.trim().toLowerCase() ===- verified.botUsername?.trim().toLowerCase()- );- }-- async function assertNativeBotIdentityAvailable(- endpoint: EndpointRow,- identity: VerifiedProviderIdentity,- ): Promise<void> {- const key = nativeBotIdentityKey(endpoint.provider, identity);- if (!key) {- throw unprocessable(- `${PROVIDER_LABELS[endpoint.provider]} did not return a stable native bot identity`,- );- }- const candidates = await db- .select({- id: chatEndpoints.id,- companyId: chatEndpoints.companyId,- assignedAgentId: chatEndpoints.assignedAgentId,- providerAccountId: chatEndpoints.providerAccountId,- botExternalId: chatEndpoints.botExternalId,- botUsername: chatEndpoints.botUsername,- })- .from(chatEndpoints)- .where(- and(- providerUsesGlobalApplicationIdentity(endpoint.provider)- ? undefined- : eq(chatEndpoints.companyId, endpoint.companyId),- eq(chatEndpoints.provider, endpoint.provider),- ne(chatEndpoints.id, endpoint.id),- endpoint.provider === "imessage-photon" ? ne(chatEndpoints.status, "archived") : inArray(chatEndpoints.status, [+ let committedWebhookSecretRef: ToolCredentialSecretRef | null = null;+ return withCredentialMutationLease(+ initial.endpoint,+ async (credentialLease) => {+ // A competing request may have completed while this request waited for+ // the durable lease. Reload both endpoint state and credential refs only+ // after ownership so each successful rotation starts from its immediate+ // predecessor instead of replacing the credential set from a stale read.+ const record = await endpointRecord(endpointId);+ if (!record) throw notFound("Chat endpoint not found");+ const endpoint = record.endpoint;+ if (+ ![+ "draft","verifying","active",- "paused","attention",- ]),- ),- );- const conflictEndpoint = candidates.find((candidate) => {- if (!providerUsesGlobalApplicationIdentity(endpoint.provider)) {- return nativeBotIdentityKey(endpoint.provider, candidate) === key;- }- const candidateAppId = candidate.botExternalId?.trim().toLowerCase();- const incomingAppId = identity.botExternalId?.trim().toLowerCase();- if (candidateAppId && incomingAppId)- return candidateAppId === incomingAppId;- return (- candidate.providerAccountId?.trim().toLowerCase() ===- identity.providerAccountId?.trim().toLowerCase() &&- candidate.botUsername?.trim().toLowerCase() ===- identity.botUsername?.trim().toLowerCase()- );- });- if (conflictEndpoint) {- throw conflict(- `This ${PROVIDER_LABELS[endpoint.provider]} bot already represents another Paperclip agent connection`,- conflictEndpoint.companyId === endpoint.companyId- ? {- code: "chat_bot_identity_in_use",- endpointId: conflictEndpoint.id,- assignedAgentId: conflictEndpoint.assignedAgentId,- }- : { code: "chat_bot_identity_in_use" },- );- }- }-- function isNativeBotIdentityUniqueViolation(error: unknown): boolean {- return (- isUniqueViolation(error, "chat_endpoints_photon_number_uq") ||- isUniqueViolation(error, "chat_endpoints_live_bot_external_uq") ||- isUniqueViolation(error, "chat_endpoints_live_discord_bot_external_uq") ||- isUniqueViolation(- error,- "chat_endpoints_live_global_app_bot_external_uq",- ) ||- isUniqueViolation(error, "chat_endpoints_live_bot_username_uq")- );- }-- function nativeBotIdentityConflict(provider: ChatProvider) {- return conflict(- `This ${PROVIDER_LABELS[provider]} bot already represents another Paperclip agent connection`,- { code: "chat_bot_identity_in_use" },- );- }-- async function persistCredentials(- endpoint: EndpointRow,- credentials: Record<string, string>,- credentialLease: CredentialMutationLeaseGuard,- actorUserId?: string | null,- ) {- await credentialLease.assertOwned();- const previousRefs = await db- .select({ refs: toolConnections.credentialSecretRefs })- .from(toolConnections)- .where(- and(- eq(toolConnections.companyId, endpoint.companyId),- eq(toolConnections.id, endpoint.connectionId),- ),- )- .then((rows) => rows[0]?.refs ?? []);- const refs: ToolCredentialSecretRef[] = [];- try {- for (const [key, value] of Object.entries(credentials)) {- if (endpoint.provider === "imessage-photon" && key !== "projectSecret") continue;- await credentialLease.assertOwned();- const suffix = randomUUID();- const secret = await secrets.create(- endpoint.companyId,- {- name: `chat.${endpoint.provider}.${endpoint.id.slice(0, 8)}.${key}.${suffix.slice(0, 8)}`,- key: `CHAT_${endpoint.provider.replaceAll("-", "_")}_${endpoint.id.replaceAll("-", "_")}_${key}_${suffix}`.toUpperCase(),- provider: "local_encrypted",- managedMode: "paperclip_managed",- value,- description: `${PROVIDER_LABELS[endpoint.provider]} channel credential for endpoint ${endpoint.id}`,- },- { userId: actorUserId ?? undefined },- );- refs.push({- secretId: secret.id,- versionSelector: "latest",- configPath: `credentials.${key}`,- required: true,- label: key,- projectionClass: "unclassified",- });- await credentialLease.assertOwned();- }- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- const current = await tx- .select({ refs: toolConnections.credentialSecretRefs })- .from(toolConnections)- .where(- and(- eq(toolConnections.companyId, endpoint.companyId),- eq(toolConnections.id, endpoint.connectionId),- ),- )- .for("update")- .then((rows) => rows[0] ?? null);- if (!current) throw notFound("Chat connection not found");- if (- credentialFingerprint(current.refs) !==- credentialFingerprint(previousRefs)+ "revoked",+ "paused",+ ].includes(endpoint.status)) {- throw conflict("Chat credentials changed during rotation", {- code: "chat_endpoint_credentials_changed",- });+ throw conflict(+ "The GitHub webhook secret cannot be rotated in this connection state",+ {+ code: "chat_endpoint_setup_secret_unavailable",+ },+ );}- await tx- .delete(companySecretBindings)- .where(- and(- eq(companySecretBindings.companyId, endpoint.companyId),- eq(companySecretBindings.targetType, "tool_connection"),- eq(companySecretBindings.targetId, endpoint.connectionId),+ const webhookSecret = randomBytes(32).toString("hex");+ // Rotation must fail closed if any existing credential cannot be resolved.+ // Falling back to an empty object here would replace the full credential+ // set with only the new webhook secret and strand an otherwise-live App.+ const existing = await resolveCredentials(endpoint);+ const replacedExistingSecret = record.credentialSecretRefs.some(+ (ref) => ref.configPath === "credentials.webhookSecret",+ );+ const rotatingConfiguredApp =+ Boolean(endpoint.providerAccountId || endpoint.botExternalId) ||+ record.credentialSecretRefs.some((ref) =>+ ["credentials.appId", "credentials.privateKey"].includes(+ ref.configPath,),);- if (refs.length > 0) {- await tx.insert(companySecretBindings).values(- refs.map((ref) => ({- companyId: endpoint.companyId,- secretId: ref.secretId,- targetType: "tool_connection",- targetId: endpoint.connectionId,- configPath: ref.configPath,- versionSelector: String(ref.versionSelector ?? "latest"),- required: ref.required,- label: ref.label ?? null,- projectionClass: ref.projectionClass ?? "unclassified",- projectionAllowlistKey: ref.projectionAllowlistKey ?? null,- })),+ const rotationId = randomUUID();+ const auditDetails = {+ endpointId: endpoint.id,+ provider: endpoint.provider,+ rotationId,+ rotated: rotatingConfiguredApp,+ replacedPrevious: replacedExistingSecret,+ };+ const writeSetupSecretActivity =+ options.setupSecretActivityLogger ?? logActivity;+ // This durable intent is the audit boundary. If it cannot be written,+ // fail before changing state or refs so retry is safe. Endpoint/tool+ // state moves fail-closed before ref replacement. Once refs change, only+ // best-effort work remains and the plaintext must still be returned.+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ await writeSetupSecretActivity(tx as unknown as Db, {+ companyId: endpoint.companyId,+ actorType: "user",+ actorId: actorUserId ?? "board",+ action: "chat_endpoint.setup_secret_rotation_started",+ entityType: "tool_connection",+ entityId: endpoint.connectionId,+ details: auditDetails,+ });+ await credentialLease.assertOwned(tx);+ });+ try {+ if (rotatingConfiguredApp) {+ const updatedAt = new Date();+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ const current = await tx+ .select({ setup: chatEndpoints.setup })+ .from(chatEndpoints)+ .where(eq(chatEndpoints.id, endpoint.id))+ .for("update")+ .then((rows) => rows[0] ?? null);+ if (!current) throw notFound("Chat endpoint not found");+ await tx+ .update(chatEndpoints)+ .set({+ status: "attention",+ healthMessage:+ "Update the GitHub webhook secret, then reconnect this App",+ lastError: null,+ setup: {+ ...current.setup,+ step: "provider_setup",+ webhookVerifiedAt: null,+ runtimeGeneration: runtimeGeneration(current.setup) + 1,+ } as InternalSetupState,+ updatedAt,+ })+ .where(eq(chatEndpoints.id, endpoint.id));+ await tx+ .update(toolConnections)+ .set({+ status: "disabled",+ enabled: false,+ healthStatus: "degraded",+ healthMessage:+ "GitHub webhook secret rotation needs reconnect",+ lastError: null,+ healthCheckedAt: updatedAt,+ updatedAt,+ })+ .where(eq(toolConnections.id, endpoint.connectionId));+ await credentialLease.assertOwned(tx);+ });+ await invalidateRuntime(endpoint.id).catch(() => undefined);+ } else {+ // Replacing a secret while the operator is still creating the GitHub+ // App is not a live credential rotation. Keep first-time setup in its+ // draft state, clear any ping for the superseded value, and also heal+ // endpoints affected by the earlier pre-connect rotation trap.+ const updatedAt = new Date();+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ const current = await tx+ .select({ setup: chatEndpoints.setup })+ .from(chatEndpoints)+ .where(eq(chatEndpoints.id, endpoint.id))+ .for("update")+ .then((rows) => rows[0] ?? null);+ if (!current) throw notFound("Chat endpoint not found");+ await tx+ .update(chatEndpoints)+ .set({+ status: "draft",+ healthMessage: null,+ lastError: null,+ setup: {+ ...current.setup,+ step: "provider_setup",+ webhookVerifiedAt: null,+ },+ updatedAt,+ })+ .where(eq(chatEndpoints.id, endpoint.id));+ await tx+ .update(toolConnections)+ .set({+ status: "draft",+ enabled: false,+ healthStatus: "unchecked",+ healthMessage: null,+ lastError: null,+ healthCheckedAt: null,+ updatedAt,+ })+ .where(eq(toolConnections.id, endpoint.connectionId));+ await credentialLease.assertOwned(tx);+ });+ }+ await options.setupSecretCredentialPersistBarrier?.();+ // Make credential refs the final required mutation. Once this returns,+ // only the best-effort completion audit remains, so the request cannot+ // fail after making the newly generated secret authoritative.+ const persistedRefs = await persistCredentials(+ endpoint,+ { ...existing, webhookSecret },+ credentialLease,+ actorUserId,);- }- await tx- .update(toolConnections)- .set({ credentialSecretRefs: refs, updatedAt: new Date() })- .where(eq(toolConnections.id, endpoint.connectionId));- await credentialLease.assertOwned(tx);- });- } catch (error) {- // A lost database acknowledgement can be ambiguous even when the- // transaction committed. Delete only secrets proven unbound after the- // failure; when that proof cannot be read, leak safely for later cleanup- // instead of deleting a possibly-authoritative credential.- const boundSecretIds =- refs.length === 0- ? new Set<string>()- : await db- .select({ secretId: companySecretBindings.secretId })- .from(companySecretBindings)- .where(- and(- eq(companySecretBindings.companyId, endpoint.companyId),- inArray(- companySecretBindings.secretId,- refs.map((ref) => ref.secretId),- ),+ committedWebhookSecretRef =+ persistedRefs.find(+ (ref) => ref.configPath === "credentials.webhookSecret",+ ) ?? null;+ if (!committedWebhookSecretRef) {+ throw new Error(+ "GitHub webhook secret was not present after credential persistence",+ );+ }+ } catch (error) {+ await writeSetupSecretActivity(db, {+ companyId: endpoint.companyId,+ actorType: "user",+ actorId: actorUserId ?? "board",+ action: "chat_endpoint.setup_secret_rotation_failed",+ entityType: "tool_connection",+ entityId: endpoint.connectionId,+ details: auditDetails,+ }).catch((auditError) => {+ logger.warn(+ {+ endpointId: endpoint.id,+ error: redactError(auditError),+ rotationId,+ },+ "could not audit failed GitHub setup-secret rotation",+ );+ });+ throw error;+ }+ await db+ .transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ await writeSetupSecretActivity(tx as unknown as Db, {+ companyId: endpoint.companyId,+ actorType: "user",+ actorId: actorUserId ?? "board",+ action: "chat_endpoint.setup_secret_generated",+ entityType: "tool_connection",+ entityId: endpoint.connectionId,+ details: auditDetails,+ });+ await credentialLease.assertOwned(tx);+ })+ .catch((error) => {+ logger.warn(+ {+ endpointId: endpoint.id,+ error: redactError(error),+ rotationId,+ },+ "GitHub setup secret rotated but completion audit failed",+ );+ });+ return { webhookSecret };+ },+ {+ beforeFinalOwnershipCheck: options.setupSecretFinalOwnershipBarrier,+ recoverCommittedResultAfterLeaseLoss: async () => {+ const committedRef = committedWebhookSecretRef;+ if (!committedRef) return false;+ const authoritative = await db+ .select({ refs: toolConnections.credentialSecretRefs })+ .from(toolConnections)+ .innerJoin(+ companySecretBindings,+ and(+ eq(companySecretBindings.companyId, initial.endpoint.companyId),+ eq(companySecretBindings.targetType, "tool_connection"),+ eq(+ companySecretBindings.targetId,+ initial.endpoint.connectionId,),- )- .then((rows) => new Set(rows.map((row) => row.secretId)))- .catch(() => null);- if (boundSecretIds) {- await Promise.allSettled(- refs- .filter((ref) => !boundSecretIds.has(ref.secretId))- .map((ref) => secrets.remove(ref.secretId)),- );- }- throw error;- }- const currentIds = new Set(refs.map((ref) => ref.secretId));- const retired = previousRefs.filter((ref) => !currentIds.has(ref.secretId));- const results = await Promise.allSettled(- retired.map((ref) => secrets.remove(ref.secretId)),- );- if (results.some((result) => result.status === "rejected")) {- logger.warn(- { endpointId: endpoint.id },- "chat credential rotation left an unbound retired secret for later cleanup",- );- }- return refs;- }-- async function clearCredentials(- endpoint: EndpointRow,- credentialLease: CredentialMutationLeaseGuard,- ) {- let refs: ToolCredentialSecretRef[] = [];- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- const current = await tx- .select({ refs: toolConnections.credentialSecretRefs })- .from(toolConnections)- .where(- and(- eq(toolConnections.companyId, endpoint.companyId),- eq(toolConnections.id, endpoint.connectionId),- ),- )- .for("update")- .then((rows) => rows[0] ?? null);- if (!current) throw notFound("Chat connection not found");- refs = current.refs;- await tx- .delete(companySecretBindings)- .where(- and(- eq(companySecretBindings.companyId, endpoint.companyId),- eq(companySecretBindings.targetType, "tool_connection"),- eq(companySecretBindings.targetId, endpoint.connectionId),- ),- );- await tx- .update(toolConnections)- .set({ credentialSecretRefs: [], updatedAt: new Date() })- .where(eq(toolConnections.id, endpoint.connectionId));- await credentialLease.assertOwned(tx);- });- const results = await Promise.allSettled(- refs.map((ref) => secrets.remove(ref.secretId)),+ eq(companySecretBindings.configPath, committedRef.configPath),+ eq(companySecretBindings.secretId, committedRef.secretId),+ eq(+ companySecretBindings.versionSelector,+ String(committedRef.versionSelector ?? "latest"),+ ),+ ),+ )+ .where(+ and(+ eq(toolConnections.companyId, initial.endpoint.companyId),+ eq(toolConnections.id, initial.endpoint.connectionId),+ ),+ )+ .then((rows) => rows[0] ?? null);+ return (+ authoritative?.refs.some(+ (ref) =>+ credentialFingerprint([ref]) ===+ credentialFingerprint([committedRef]),+ ) === true+ );+ },+ },);- if (results.some((result) => result.status === "rejected")) {- logger.warn(- { endpointId: endpoint.id },- "chat endpoint removal left an unbound retired secret for later cleanup",- );- }}- async function resolveCredentialRefs(- endpoint: EndpointRow,- refs: ToolCredentialSecretRef[],- database: DbOrTransaction = db,- ): Promise<Record<string, string>> {- const values: Record<string, string> = {};- for (const ref of refs) {- const key = ref.configPath.replace(/^credentials\./, "");- values[key] = await (database === db ? secrets : secretService(database as Db)).resolveSecretValue(- endpoint.companyId,- ref.secretId,- ref.versionSelector ?? "latest",- {- consumerType: "tool_connection",- consumerId: endpoint.connectionId,- configPath: ref.configPath,- actorType: "system",- actorId: null,- },- );+ async function hydrateSlackResourceLabel(+ endpointId: string,+ providerResourceId: string,+ ): Promise<void> {+ const record = await endpointRecord(endpointId);+ if (+ !record ||+ record.endpoint.provider !== "slack" ||+ record.endpoint.status === "archived" ||+ record.endpoint.status === "revoked"+ ) {+ return;}- return values;- }-- async function resolveCredentials(- endpoint: EndpointRow,- database: DbOrTransaction = db,- ): Promise<Record<string, string>> {- const connection = await database- .select({ refs: toolConnections.credentialSecretRefs, config: toolConnections.config })- .from(toolConnections)+ const credentials = await resolveCredentials(record.endpoint);+ const resource = await getSlackBotChannel({+ botToken: credentials.botToken,+ channelId: providerResourceId,+ fetch: fetchImpl,+ });+ if (+ !resource ||+ slackResourceLabelIsFallback(providerResourceId, resource.label)+ )+ return;+ await db+ .update(chatEndpointResources)+ .set({ label: resource.label, updatedAt: new Date() }).where(and(- eq(toolConnections.companyId, endpoint.companyId),- eq(toolConnections.id, endpoint.connectionId),+ eq(chatEndpointResources.companyId, record.endpoint.companyId),+ eq(chatEndpointResources.endpointId, endpointId),+ eq(chatEndpointResources.type, "channel"),+ eq(chatEndpointResources.providerResourceId, providerResourceId),+ eq(chatEndpointResources.availability, "available"),),- )- .then((rows) => rows[0] ?? null);- if (!connection) throw notFound("Chat connection not found");- const values = await resolveCredentialRefs(endpoint, connection.refs, database);- if (endpoint.provider === "imessage-photon") {- const configuration = photonChannelConfigurationSchema.parse(connection.config.photon);- return { ...values, ...configuration, lineId: configuration.allocation === "shared" ? photonSharedScope(configuration.projectId) : configuration.lineId };- }- return values;+ );}- const withCredentialMutationLease = chatCredentialMutationLease(db, options);- const { handlePhotonFailure, handlePhotonEvent } = createPhotonEvents(db, { runtimeCallbackRecord, runtimeCallbackEndpoint, invalidateRuntime, ensurePrincipal, requireCurrentExternalActionAuthorization, isExternalActionAuthorizationChange, scheduleMessageProcessing, processPendingPublications, questionResponses, redactError, renewDiscordGatewayOwnershipForMessageAdmission, handleSdkMessage });- const { handleTelegramGenerationStopped, reserveTelegramPublicationDraft } = createTelegramPublicationDrafts(db, { runtimeCallbackRecord, runtimeCallbackEndpoint, runtimeFor, runtime, runtimeContexts, credentialFingerprint, authorizeRetainedChatSourcePublication });- const { recordSlackFileUploadReceipt, stageSlackFilePublicationSuccess, processPendingSlackFileUploadReceipts, nextSlackReceiptAt } = createSlackFileReceipts(db, { endpointRecord, withCredentialMutationLease, runtimeCallbackEndpoint, nonDirectDestinationAllowed, runtimeFor, isExplicitOperatorPublication, recordExactOutboundPublicationLink });- const { processPendingSlackSessionSyncs } = createSlackSessionStatus(db, { endpointRecord, withCredentialMutationLease, runtimeCallbackEndpoint, nonDirectDestinationAllowed, runIdFromMilestonePublication, resolveCredentials, fetchImpl, redactError, get slackSessionSyncSelectionBarrier() { return options.slackSessionSyncSelectionBarrier; } });- const { reconcileDiscordCommands, handleDiscordNativeCommand } = createDiscordCommands(db, { endpointRecord, runtimeContextForRecord, runtimeGeneration, credentialFingerprint, resolveCredentialRefs, fetchImpl, withCredentialMutationLease, runtimeCallbackRecord, ensurePrincipal, runtimeCallbackEndpoint, nonDirectDestinationAllowed, lockCurrentPrincipalAuthorization, getDiscordGatewayOwnership: (endpointId) => discordGatewayOwnerships.get(endpointId), discordGatewayRuntimeIsCurrent, stageAuthorizedTaskControlPublication, scheduleMessageProcessing, processPendingPublications });- const { latestSlackDmControlThreadId, finalizeSlackTaskStartFailure, admitConfirmedSlackTaskStart, processSlackTaskStart, processPendingSlackTaskStarts } = createSlackTaskStart(db, { endpointRecord, runtimeGeneration, credentialFingerprint, invalidateRuntime, runtimeFor, processMessage, runtimeContextForRecord, redactError, withCredentialMutationLease, sponsorAllowsGuest, nonDirectDestinationAllowed, runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, get slackTaskAdmissionClaimBarrier() { return options.slackTaskAdmissionClaimBarrier; }, maxErrorText: MAX_ERROR_TEXT });- const { stageGitHubWebhookIngress, githubIngressAcceptedResponse, processGitHubWebhookIngress, processFailedGitHubWebhookDeliveries, processPendingGitHubWebhookIngress } = createGitHubWebhookIngress(db, { endpointRecord, runtimeContextForRecord, resolveCredentialRefs, runtimeGeneration, credentialFingerprint, getWebhookPublicBaseUrl, redactError, handleWebhook, runtimeCallbackEndpoint, fetchImpl, persistence, withCredentialMutationLease, isShuttingDown: () => shuttingDown, get githubWebhookReplayBarrier() { return options.githubWebhookReplayBarrier; }, supportedWebhookEvents: SUPPORTED_GITHUB_WEBHOOK_EVENTS });- const { stageSlackSessionStop, processSlackSessionStop, processPendingSlackSessionStops } = createSlackSessionStop(db, { runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, nonDirectDestinationAllowed, stageAuthorizedTaskControlPublication, getPublicBaseUrl, get heartbeat() { return options.heartbeat; }, redactError });- const { stageTelegramMaintenance, processTelegramMaintenance, processPendingTelegramMaintenance, hasTelegramStopSubscription, recordTelegramStopSubscription } = createTelegramMaintenance(db, { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, resolveCredentials, clearCredentials, runtimeCallbackEndpoint, getWebhookPublicBaseUrl, fetchImpl, runtimeGeneration, credentialFingerprint, redactError, credentialCheckTimeoutMs: PROVIDER_CREDENTIAL_CHECK_TIMEOUT_MS });- const { reconcileGitHubWebhookRepository, reconcileProviderResourceRows, listResources, listGitHubRepositories, replaceResources, toggleAllGitHubRepositories, hasNewerProcessedProviderLifecycleEffect, applyProviderAvailability } = createChatResourceReconciliation(db, { endpointRecord, withCredentialMutationLease, runtimeGeneration, maxErrorText: MAX_ERROR_TEXT });-- async function generateSetupSecret(- endpointId: string,- actorUserId?: string | null,- ) {- const initial = await endpointRecord(endpointId);- if (!initial) throw notFound("Chat endpoint not found");- if (initial.endpoint.provider !== "github") {- throw unprocessable(- "Setup secret generation is only available for GitHub",- );- }- let committedWebhookSecretRef: ToolCredentialSecretRef | null = null;- return withCredentialMutationLease(- initial.endpoint,- async (credentialLease) => {- // A competing request may have completed while this request waited for- // the durable lease. Reload both endpoint state and credential refs only- // after ownership so each successful rotation starts from its immediate- // predecessor instead of replacing the credential set from a stale read.- const record = await endpointRecord(endpointId);- if (!record) throw notFound("Chat endpoint not found");- const endpoint = record.endpoint;- if (- ![- "draft",- "verifying",- "active",- "attention",- "revoked",- "paused",- ].includes(endpoint.status)- ) {- throw conflict(- "The GitHub webhook secret cannot be rotated in this connection state",- {- code: "chat_endpoint_setup_secret_unavailable",- },- );- }- const webhookSecret = randomBytes(32).toString("hex");- // Rotation must fail closed if any existing credential cannot be resolved.- // Falling back to an empty object here would replace the full credential- // set with only the new webhook secret and strand an otherwise-live App.- const existing = await resolveCredentials(endpoint);- const replacedExistingSecret = record.credentialSecretRefs.some(- (ref) => ref.configPath === "credentials.webhookSecret",- );- const rotatingConfiguredApp =- Boolean(endpoint.providerAccountId || endpoint.botExternalId) ||- record.credentialSecretRefs.some((ref) =>- ["credentials.appId", "credentials.privateKey"].includes(- ref.configPath,- ),- );- const rotationId = randomUUID();- const auditDetails = {- endpointId: endpoint.id,- provider: endpoint.provider,- rotationId,- rotated: rotatingConfiguredApp,- replacedPrevious: replacedExistingSecret,+ async function prepareProviderInventory(+ endpoint: EndpointRow,+ credentials: Record<string, string>,+ ): Promise<{+ credentials: Record<string, string>;+ inventory: ChatProviderInventoryResult | null;+ managementUrl?: string;+ }> {+ try {+ if (endpoint.provider === "slack") {+ return {+ credentials,+ inventory: await listSlackBotChannels({+ botToken: credentials.botToken,+ fetch: fetchImpl,+ }),};- const writeSetupSecretActivity =- options.setupSecretActivityLogger ?? logActivity;- // This durable intent is the audit boundary. If it cannot be written,- // fail before changing state or refs so retry is safe. Endpoint/tool- // state moves fail-closed before ref replacement. Once refs change, only- // best-effort work remains and the plaintext must still be returned.- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- await writeSetupSecretActivity(tx as unknown as Db, {- companyId: endpoint.companyId,- actorType: "user",- actorId: actorUserId ?? "board",- action: "chat_endpoint.setup_secret_rotation_started",- entityType: "tool_connection",- entityId: endpoint.connectionId,- details: auditDetails,- });- await credentialLease.assertOwned(tx);- });- try {- if (rotatingConfiguredApp) {- const updatedAt = new Date();- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- const current = await tx- .select({ setup: chatEndpoints.setup })- .from(chatEndpoints)- .where(eq(chatEndpoints.id, endpoint.id))- .for("update")- .then((rows) => rows[0] ?? null);- if (!current) throw notFound("Chat endpoint not found");- await tx- .update(chatEndpoints)- .set({- status: "attention",- healthMessage:- "Update the GitHub webhook secret, then reconnect this App",- lastError: null,- setup: {- ...current.setup,- step: "provider_setup",- webhookVerifiedAt: null,- runtimeGeneration: runtimeGeneration(current.setup) + 1,- } as InternalSetupState,- updatedAt,- })- .where(eq(chatEndpoints.id, endpoint.id));- await tx- .update(toolConnections)- .set({- status: "disabled",- enabled: false,- healthStatus: "degraded",- healthMessage:- "GitHub webhook secret rotation needs reconnect",- lastError: null,- healthCheckedAt: updatedAt,- updatedAt,- })- .where(eq(toolConnections.id, endpoint.connectionId));- await credentialLease.assertOwned(tx);- });- await invalidateRuntime(endpoint.id).catch(() => undefined);- } else {- // Replacing a secret while the operator is still creating the GitHub- // App is not a live credential rotation. Keep first-time setup in its- // draft state, clear any ping for the superseded value, and also heal- // endpoints affected by the earlier pre-connect rotation trap.- const updatedAt = new Date();- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- const current = await tx- .select({ setup: chatEndpoints.setup })- .from(chatEndpoints)- .where(eq(chatEndpoints.id, endpoint.id))- .for("update")- .then((rows) => rows[0] ?? null);- if (!current) throw notFound("Chat endpoint not found");- await tx- .update(chatEndpoints)- .set({- status: "draft",- healthMessage: null,- lastError: null,- setup: {- ...current.setup,- step: "provider_setup",- webhookVerifiedAt: null,- },- updatedAt,- })- .where(eq(chatEndpoints.id, endpoint.id));- await tx- .update(toolConnections)- .set({- status: "draft",- enabled: false,- healthStatus: "unchecked",- healthMessage: null,- lastError: null,- healthCheckedAt: null,- updatedAt,- })- .where(eq(toolConnections.id, endpoint.connectionId));- await credentialLease.assertOwned(tx);- });- }- await options.setupSecretCredentialPersistBarrier?.();- // Make credential refs the final required mutation. Once this returns,- // only the best-effort completion audit remains, so the request cannot- // fail after making the newly generated secret authoritative.- const persistedRefs = await persistCredentials(- endpoint,- { ...existing, webhookSecret },- credentialLease,- actorUserId,- );- committedWebhookSecretRef =- persistedRefs.find(- (ref) => ref.configPath === "credentials.webhookSecret",- ) ?? null;- if (!committedWebhookSecretRef) {- throw new Error(- "GitHub webhook secret was not present after credential persistence",- );- }- } catch (error) {- await writeSetupSecretActivity(db, {- companyId: endpoint.companyId,- actorType: "user",- actorId: actorUserId ?? "board",- action: "chat_endpoint.setup_secret_rotation_failed",- entityType: "tool_connection",- entityId: endpoint.connectionId,- details: auditDetails,- }).catch((auditError) => {- logger.warn(- {- endpointId: endpoint.id,- error: redactError(auditError),- rotationId,- },- "could not audit failed GitHub setup-secret rotation",- );- });- throw error;- }- await db- .transaction(async (tx) => {- await credentialLease.assertOwned(tx);- await writeSetupSecretActivity(tx as unknown as Db, {- companyId: endpoint.companyId,- actorType: "user",- actorId: actorUserId ?? "board",- action: "chat_endpoint.setup_secret_generated",- entityType: "tool_connection",- entityId: endpoint.connectionId,- details: auditDetails,- });- await credentialLease.assertOwned(tx);- })- .catch((error) => {- logger.warn(- {- endpointId: endpoint.id,- error: redactError(error),- rotationId,- },- "GitHub setup secret rotated but completion audit failed",- );- });- return { webhookSecret };- },- {- beforeFinalOwnershipCheck: options.setupSecretFinalOwnershipBarrier,- recoverCommittedResultAfterLeaseLoss: async () => {- const committedRef = committedWebhookSecretRef;- if (!committedRef) return false;- const authoritative = await db- .select({ refs: toolConnections.credentialSecretRefs })- .from(toolConnections)- .innerJoin(- companySecretBindings,- and(- eq(companySecretBindings.companyId, initial.endpoint.companyId),- eq(companySecretBindings.targetType, "tool_connection"),- eq(- companySecretBindings.targetId,- initial.endpoint.connectionId,- ),- eq(companySecretBindings.configPath, committedRef.configPath),- eq(companySecretBindings.secretId, committedRef.secretId),- eq(- companySecretBindings.versionSelector,- String(committedRef.versionSelector ?? "latest"),- ),- ),- )- .where(- and(- eq(toolConnections.companyId, initial.endpoint.companyId),- eq(toolConnections.id, initial.endpoint.connectionId),- ),- )- .then((rows) => rows[0] ?? null);- return (- authoritative?.refs.some(- (ref) =>- credentialFingerprint([ref]) ===- credentialFingerprint([committedRef]),- ) === true- );- },- },- );- }-- async function hydrateSlackResourceLabel(- endpointId: string,- providerResourceId: string,- ): Promise<void> {- const record = await endpointRecord(endpointId);- if (- !record ||- record.endpoint.provider !== "slack" ||- record.endpoint.status === "archived" ||- record.endpoint.status === "revoked"- ) {- return;- }- const credentials = await resolveCredentials(record.endpoint);- const resource = await getSlackBotChannel({- botToken: credentials.botToken,- channelId: providerResourceId,- fetch: fetchImpl,- });- if (- !resource ||- slackResourceLabelIsFallback(providerResourceId, resource.label)- )- return;- await db- .update(chatEndpointResources)- .set({ label: resource.label, updatedAt: new Date() })- .where(- and(- eq(chatEndpointResources.companyId, record.endpoint.companyId),- eq(chatEndpointResources.endpointId, endpointId),- eq(chatEndpointResources.type, "channel"),- eq(chatEndpointResources.providerResourceId, providerResourceId),- eq(chatEndpointResources.availability, "available"),- ),- );- }-- async function prepareProviderInventory(- endpoint: EndpointRow,- credentials: Record<string, string>,- ): Promise<{- credentials: Record<string, string>;- inventory: ChatProviderInventoryResult | null;- managementUrl?: string;- }> {- try {- if (endpoint.provider === "slack") {- return {- credentials,- inventory: await listSlackBotChannels({- botToken: credentials.botToken,- fetch: fetchImpl,- }),- };- }- if (endpoint.provider === "github") {- const appJwt = githubAppJwt(credentials.appId, credentials.privateKey);- const installation = await discoverDedicatedGitHubAppInstallation({- appJwt,- fetch: fetchImpl,+ }+ if (endpoint.provider === "github") {+ const appJwt = githubAppJwt(credentials.appId, credentials.privateKey);+ const installation = await discoverDedicatedGitHubAppInstallation({+ appJwt,+ fetch: fetchImpl,});const preparedCredentials = {...credentials,@@ -7143,288 +4986,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {.limit(1).then((rows) => rows[0] ?? null);}- async function setupTestStatus(endpointId: string, userId: string) {- const record = await endpointRecord(endpointId);- if (!record) throw notFound("Chat endpoint not found");- const startedAt = record.endpoint.setup.testStartedAt;- if (!startedAt) return { messageReceivedAt: null };- const links = await db.select({ principalId: chatIdentityLinks.principalId }).from(chatIdentityLinks).where(and(- eq(chatIdentityLinks.companyId, record.endpoint.companyId), eq(chatIdentityLinks.endpointId, endpointId),- eq(chatIdentityLinks.paperclipUserId, userId), eq(chatIdentityLinks.status, "linked"),- ));- if (!links.length) return { messageReceivedAt: null };- const principalIds = links.map((link) => link.principalId);- const [delivery, command] = await Promise.all([- db.select({ at: chatDeliveries.createdAt }).from(chatDeliveries).where(and(- eq(chatDeliveries.companyId, record.endpoint.companyId), eq(chatDeliveries.endpointId, endpointId),- inArray(chatDeliveries.principalId, principalIds), gte(chatDeliveries.createdAt, new Date(startedAt)),- inArray(chatDeliveries.eventKind, ["message", "mention"]),- )).orderBy(asc(chatDeliveries.createdAt)).limit(1).then((rows) => rows[0]),- db.select({ at: chatActions.createdAt }).from(chatActions).where(and(- eq(chatActions.companyId, record.endpoint.companyId), eq(chatActions.endpointId, endpointId),- inArray(chatActions.principalId, principalIds), eq(chatActions.kind, "slash_task_start"), gte(chatActions.createdAt, new Date(startedAt)),- )).orderBy(asc(chatActions.createdAt)).limit(1).then((rows) => rows[0]),- ]);- const at = [delivery?.at, command?.at].filter((value): value is Date => Boolean(value)).sort((a, b) => a.getTime() - b.getTime())[0];- return { messageReceivedAt: at?.toISOString() ?? null };- }-- async function test(endpointId: string, finishOptions?: { optionalSlackTestForUser: string }) {- const initial = await endpointRecord(endpointId);- if (!initial) throw notFound("Chat endpoint not found");- return withCredentialMutationLease(- initial.endpoint,- async (credentialLease) => {- // Reload only after owning the same lane as reconnect, pause, removal,- // and credential rotation. Qualification and activation must describe- // one exact provider runtime, never a setup snapshot that a concurrent- // reconnect has already superseded.- const record = await endpointRecord(endpointId);- if (!record) throw notFound("Chat endpoint not found");- const endpoint = record.endpoint;- if (endpoint.status !== "verifying" || endpoint.setup.step !== "test") {- throw conflict("This connection is not waiting for a setup test", {- code: "chat_endpoint_not_testing",- });- }- if (endpoint.provider === "github" && endpoint.setup.github) {- const verified = await githubChatManagementService(db, fetchImpl).verification(endpoint.id);- if (!verified.ready && !(finishOptions?.optionalSlackTestForUser && verified.connectionReady)) throw conflict("Finish verifying the App, repositories, and assigned agent's tools before activating this bot", { checks: verified.checks });- }- const testStartedAtValue = endpoint.setup.testStartedAt;- const testStartedAt = testStartedAtValue- ? new Date(testStartedAtValue)- : null;- const optionalSlackTest = Boolean(finishOptions?.optionalSlackTestForUser);- if (optionalSlackTest) {- if (!["slack", "github"].includes(endpoint.provider) || !endpoint.setup.webhookVerifiedAt || !endpoint.providerAccountId) {- throw conflict("Verify the connection before finishing setup");- }- const linked = await findAuthorizedIdentityLink(endpoint, finishOptions!.optionalSlackTestForUser);- if (!linked) throw forbidden("Connect your account before finishing setup");- }- if (!optionalSlackTest) {- if (- !endpoint.lastEventAt ||- !testStartedAtValue ||- !testStartedAt ||- Number.isNaN(testStartedAt.getTime()) ||- endpoint.lastEventAt < testStartedAt- ) {- throw conflict(- "Send the test message in the provider before completing setup",- {- code: "chat_test_message_missing",- },- );- }- const requiredTrigger =- ["telegram", "imessage-photon"].includes(endpoint.provider)- ? "direct_message"- : "subscribed_message";- const qualifyingDelivery = await db- .select({- id: chatDeliveries.id,- conversationId: chatDeliveries.conversationId,- processedAt: chatDeliveries.processedAt,- })- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.companyId, endpoint.companyId),- eq(chatDeliveries.endpointId, endpoint.id),- eq(chatDeliveries.state, "processed"),- gte(chatDeliveries.processedAt, testStartedAt),- sql`${chatDeliveries.normalizedEvent}->>'trigger' = ${requiredTrigger}`,- ),- )- .orderBy(desc(chatDeliveries.processedAt))- .limit(1)- .then((rows) => rows[0] ?? null);- if (- !qualifyingDelivery?.conversationId ||- !qualifyingDelivery.processedAt- ) {- throw conflict(- ["telegram", "imessage-photon"].includes(endpoint.provider)- ? "Send the test direct message before completing setup"- : "Reply once without mentioning the agent before completing setup",- { code: "chat_test_follow_up_missing" },- );- }- const finalPublication = await db- .select({- commentId: chatPublications.commentId,- payload: chatPublications.payload,- })- .from(chatPublications)- .innerJoin(- issueComments,- and(- eq(issueComments.id, chatPublications.commentId),- eq(issueComments.companyId, chatPublications.companyId),- eq(issueComments.issueId, chatPublications.issueId),- eq(issueComments.authorType, "agent"),- eq(issueComments.authorAgentId, endpoint.assignedAgentId),- ),- )- .innerJoin(- chatMessageLinks,- and(- eq(chatMessageLinks.companyId, chatPublications.companyId),- eq(chatMessageLinks.endpointId, chatPublications.endpointId),- eq(- chatMessageLinks.conversationId,- chatPublications.conversationId,- ),- eq(chatMessageLinks.deliveryId, qualifyingDelivery.id),- eq(chatMessageLinks.direction, "inbound"),- isNotNull(chatMessageLinks.commentId),- ),- )- .innerJoin(- heartbeatRuns,- and(- eq(heartbeatRuns.id, issueComments.createdByRunId),- eq(heartbeatRuns.companyId, chatPublications.companyId),- eq(heartbeatRuns.agentId, endpoint.assignedAgentId),- eq(heartbeatRuns.status, "succeeded"),- eq(- sql<string>`${heartbeatRuns.contextSnapshot} ->> 'issueId'`,- sql<string>`${chatPublications.issueId}::text`,- ),- or(- sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`,- sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'commentId'`,- sql`coalesce(${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`,- ),- ),- )- .where(- and(- eq(chatPublications.companyId, endpoint.companyId),- eq(chatPublications.endpointId, endpoint.id),- eq(- chatPublications.conversationId,- qualifyingDelivery.conversationId,- ),- eq(chatPublications.state, "published"),- gte(chatPublications.publishedAt, qualifyingDelivery.processedAt),- ),- )- .orderBy(desc(chatPublications.publishedAt))- .then((rows) =>- rows.find(- (row) =>- row.payload.interactionId === undefined &&- row.payload.progressState === undefined &&- row.commentId !== null,- ),- );- let githubToolReply = false;- if (!finalPublication && endpoint.provider === "github") {- const setupRuns = await db.select({ id: heartbeatRuns.id, issueId: chatConversations.issueId })- .from(heartbeatRuns)- .innerJoin(chatMessageLinks, and(- eq(chatMessageLinks.companyId, endpoint.companyId),- eq(chatMessageLinks.endpointId, endpoint.id),- eq(chatMessageLinks.deliveryId, qualifyingDelivery.id),- eq(chatMessageLinks.direction, "inbound"),- or(- sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'`,- sql`coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`,- ),- ))- .innerJoin(chatConversations, and(- eq(chatConversations.id, qualifyingDelivery.conversationId),- eq(chatConversations.id, chatMessageLinks.conversationId),- eq(chatConversations.companyId, endpoint.companyId),- sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${chatConversations.issueId}::text`,- ))- .where(and(eq(heartbeatRuns.companyId, endpoint.companyId),- eq(heartbeatRuns.agentId, endpoint.assignedAgentId), eq(heartbeatRuns.status, "succeeded")))- .orderBy(desc(heartbeatRuns.createdAt)).limit(20);- for (const run of setupRuns) {- if (await githubRunReplyState(db, { companyId: endpoint.companyId, endpointId: endpoint.id,- issueId: run.issueId, runId: run.id }) === "confirmed") {- githubToolReply = true;- break;- }- }- }- if (!finalPublication && !githubToolReply) {- throw conflict(- "Wait for the Paperclip agent to reply to the setup turn before completing setup",- {- code: "chat_test_round_trip_incomplete",- },- );- }- }- await options.setupTestActivationBarrier?.();- const expectedGeneration = runtimeGeneration(endpoint.setup);- await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- if (optionalSlackTest) {- const linked = await tx.select({ principalId: chatIdentityLinks.principalId }).from(chatIdentityLinks).where(and(- eq(chatIdentityLinks.endpointId, endpoint.id), eq(chatIdentityLinks.paperclipUserId, finishOptions!.optionalSlackTestForUser), eq(chatIdentityLinks.status, "linked"),- )).limit(1).then((rows) => rows[0]);- if (!linked || !(await lockCurrentPrincipalAuthorization(tx, endpoint, linked.principalId)).allowed) throw forbidden("Your connected account is no longer authorized");- }- await notifyChatEndpointWork(tx);- const [activated] = await tx- .update(chatEndpoints)- .set({- status: "active",- setup: {- ...endpoint.setup,- step: "complete",- testStartedAt: null,- testSkipped: optionalSlackTest,- },- healthMessage: optionalSlackTest ? "Connected; conversation test optional" : "Connected",- activatedAt: endpoint.activatedAt ?? new Date(),- updatedAt: new Date(),- })- .where(- and(- eq(chatEndpoints.id, endpointId),- eq(chatEndpoints.status, "verifying"),- sql`${chatEndpoints.setup}->>'step' = 'test'`,- sql`coalesce((${chatEndpoints.setup}->>'runtimeGeneration')::integer, 0) = ${expectedGeneration}`,- sql`${chatEndpoints.setup}->>'testStartedAt' = ${testStartedAtValue}`,- ),- )- .returning({ id: chatEndpoints.id });- if (!activated) {- throw conflict("This setup test was superseded by a reconnect", {- code: "chat_endpoint_test_superseded",- });- }- await tx- .update(toolConnections)- .set({- status: "active",- enabled: true,- healthStatus: "healthy",- healthMessage: optionalSlackTest ? "Connected; conversation test optional" : "Connected",- lastError: null,- healthCheckedAt: new Date(),- updatedAt: new Date(),- })- .where(eq(toolConnections.id, endpoint.connectionId));- if (optionalSlackTest) await logActivity(tx as unknown as Db, {- companyId: endpoint.companyId, actorType: "user", actorId: finishOptions!.optionalSlackTestForUser,- action: "chat.setup_completed", entityType: "chat_endpoint", entityId: endpointId,- details: { conversationTestOptional: true },- });- await credentialLease.assertOwned(tx);- });- return get(endpointId);- },- );- }-async function ensurePrincipal(endpoint: EndpointRow,author: Author,@@ -7795,610 +5356,21 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {return resource;}- async function ingestAttachments(input: {- endpoint: EndpointRow;- endpointRuntime: ChatEndpointRuntime;- deliveryId: string;- issueId: string;- issueCommentId: string;- attachments: Attachment[];- attachmentLimitOmissions?: number;- unavailableReferenceCount?: number;- actorUserId: string | null;- }): Promise<{- storedIds: string[];- omissionReasons: Record<string, number>;- }> {- const omissionReasons: Record<string, number> = {};- const omit = (reason: string, count = 1) => {- omissionReasons[reason] = (omissionReasons[reason] ?? 0) + count;+ async function settleTelegramAttachmentOnlyFailure(input: {+ activeDelivery: DeliveryRow;+ attachmentResult: {+ storedIds: string[];+ omissionReasons: Record<string, number>;};- const boundedAttachments = input.attachments.slice(0, 20);- const photonDerivatives = new Map<Attachment, { source: Attachment; sourceHash: string; kind: "heif_jpeg_preview" | "live_photo_video" }>();- const originalPhotonAttachments = new Map<Attachment, string>();- if (- input.endpoint.provider === "microsoft-teams" &&- input.unavailableReferenceCount- ) {- // A channel/group reference is not a download capability. Still tell- // the exact current-turn consumer that those bytes are unavailable,- // including when there are no ingestible attachments at all.- omit("download_unavailable", input.unavailableReferenceCount);- }- if (- ["github", "imessage-photon"].includes(input.endpoint.provider) &&- input.attachmentLimitOmissions- ) {- omit("attachment_limit", input.attachmentLimitOmissions);- }- if (input.attachments.length > boundedAttachments.length) {- omit(- "attachment_limit",- input.attachments.length - boundedAttachments.length,- );- }- if (!options.storage) {- if (boundedAttachments.length)- omit("storage_unavailable", boundedAttachments.length);- return { storedIds: [], omissionReasons };- }- const existingByFingerprint = new Map<string, string[]>();- const existingAttachments = await db- .select({- id: issueAttachments.id,- byteSize: assets.byteSize,- contentType: assets.contentType,- originalFilename: assets.originalFilename,- sha256: assets.sha256,- })- .from(issueAttachments)- .innerJoin(- assets,- and(- eq(assets.companyId, issueAttachments.companyId),- eq(assets.id, issueAttachments.assetId),- ),- )- .where(- and(- eq(issueAttachments.companyId, input.endpoint.companyId),- eq(issueAttachments.issueId, input.issueId),- eq(issueAttachments.issueCommentId, input.issueCommentId),- ),- );- for (const existing of existingAttachments) {- const fingerprint = JSON.stringify([- existing.sha256,- existing.byteSize,- existing.contentType,- existing.originalFilename,- ]);- const ids = existingByFingerprint.get(fingerprint) ?? [];- ids.push(existing.id);- existingByFingerprint.set(fingerprint, ids);- }- const storedIds: string[] = [];- const withCurrentAttachmentAuthorization = async <T>(- work: (tx: DbTransaction) => Promise<T>,- enforceUnchangedSource = false,- telegramMedia?: Attachment,- ): Promise<T> => {- for (let attempt = 0; ; attempt++) {- try {- return await db.transaction(async (tx) => {- const action = await tx- .select()- .from(chatActions)- .where(- and(- eq(chatActions.companyId, input.endpoint.companyId),- eq(chatActions.endpointId, input.endpoint.id),- eq(chatActions.deliveryId, input.deliveryId),- eq(chatActions.kind, "inbound_wakeup"),- ),- )- .limit(1)- .then((rows) => rows[0]);- if (- !action ||- !["preparing", "issued", "processing", "processed"].includes(- action.status,- ) ||- action.payload.issueId !== input.issueId ||- action.payload.commentId !== input.issueCommentId- )- throw forbidden(- "The attachment's current chat admission is unavailable",- { code: "chat_action_authorization_changed" },- );- const current = await authorizeInboundWakeup(tx, action);- // Delivery settlement/replay can update these receipts without- // taking the issue lock. Lock in delivery -> action order only- // after policy authorization; NOWAIT breaks cross-worker lock- // inversions and the outer loop retries the whole transaction.- const lockedDelivery = await tx- .select()- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.companyId, input.endpoint.companyId),- eq(chatDeliveries.id, input.deliveryId),- ),- )- .for("update", { noWait: true })- .limit(1)- .then((rows) => rows[0]);- const lockedAction = await tx- .select()- .from(chatActions)- .where(- and(- eq(chatActions.companyId, input.endpoint.companyId),- eq(chatActions.id, action.id),- ),- )- .for("update", { noWait: true })- .limit(1)- .then((rows) => rows[0]);- const scopeKeys = [- "version",- "issueId",- "commentId",- "agentId",- "sessionGeneration",- "requestedByActorType",- "requestedByActorId",- ] as const;- if (- current.delivery.state !== "processing" ||- !lockedDelivery ||- !lockedAction ||- lockedDelivery.state !== "processing" ||- lockedDelivery.endpointId !== action.endpointId ||- lockedDelivery.conversationId !== action.conversationId ||- lockedDelivery.principalId !== action.principalId ||- lockedDelivery.attempts !== current.delivery.attempts ||- JSON.stringify(lifecycleRuntimeFence(lockedDelivery)) !==- JSON.stringify(lifecycleRuntimeFence(current.delivery)) ||- lockedAction.endpointId !== action.endpointId ||- lockedAction.deliveryId !== action.deliveryId ||- lockedAction.conversationId !== action.conversationId ||- lockedAction.principalId !== action.principalId ||- lockedAction.kind !== "inbound_wakeup" ||- !["preparing", "issued", "processing", "processed"].includes(- lockedAction.status,- ) ||- scopeKeys.some(- (key) => lockedAction.payload[key] !== action.payload[key],- )- )- throw forbidden(- "The attachment's current chat admission is unavailable",- { code: "chat_action_authorization_changed" },- );- if (enforceUnchangedSource) {- if (telegramMedia) {- const normalized = lockedDelivery.normalizedEvent as {- principal?: { externalId?: string };- message?: {- providerMessageId?: string;- attachments?: Array<{ recovery?: unknown }>;- };- };- const fence = lifecycleRuntimeFence(lockedDelivery);- const descriptor =- input.endpointRuntime.attachmentRecoveryDescriptor(- telegramMedia,- {- threadId: current.conversation.externalThreadId,- messageId: normalized.message?.providerMessageId ?? "",- principalExternalId: normalized.principal?.externalId,- runtimeGeneration: fence?.generation,- credentialFingerprint: fence?.credentialFingerprint,- },- );- if (- descriptor?.locator.kind !== "telegram_media" ||- !normalized.message?.attachments?.some((item) => {- const retained = item.recovery as {- version?: unknown;- provider?: unknown;- locator?: Record<string, unknown>;- attachment?: Record<string, unknown>;- } | null;- return (- retained?.version === 1 &&- retained.provider === "telegram" &&- Object.entries(descriptor.locator).every(- ([key, value]) => retained.locator?.[key] === value,- ) &&- Object.entries(descriptor.attachment).every(- ([key, value]) => retained.attachment?.[key] === value,- )- );- })- )- throw forbidden(- "The media's admitted source is unavailable",- { code: "chat_action_authorization_changed" },- );- }- const [source] = await tx- .select({ id: issueComments.id })- .from(issueComments)- .where(- and(- eq(issueComments.companyId, input.endpoint.companyId),- eq(issueComments.issueId, input.issueId),- eq(issueComments.id, input.issueCommentId),- isNull(issueComments.deletedAt),- sql`${issueComments.updatedAt} = ${issueComments.createdAt}`,- ),- )- .for("share", { noWait: true });- // Lifecycle admission precedes its conversation drain. Pending- // source changes already invalidate this image download, even- // when the append-only original comment is still untouched.- const [lifecycle] = await tx- .select({ id: chatDeliveries.id })- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.companyId, input.endpoint.companyId),- eq(chatDeliveries.endpointId, input.endpoint.id),- or(- isNull(chatDeliveries.conversationId),- eq(- chatDeliveries.conversationId,- current.conversation.id,- ),- ),- ne(chatDeliveries.state, "filtered"),- inArray(chatDeliveries.eventKind, [- "message_updated",- "message_deleted",- "message_restored",- ]),- sql`${chatDeliveries.normalizedEvent}->'runtimeContext' = ${JSON.stringify(lifecycleRuntimeFence(lockedDelivery))}::jsonb`,- sql`${chatDeliveries.normalizedEvent}->'message'->>'targetProviderEventId' = ${lockedDelivery.providerEventId}`,- ),- )- .limit(1);- if (!source || lifecycle)- throw forbidden(- "The image's admitted source changed before attachment registration",- {- code: "chat_action_authorization_changed",- },- );- }- return await work(tx);- });- } catch (error) {- if (!isExternalChatWaitAuthorizationContention(error) || attempt >= 4)- throw error;- // Retry the complete short transaction; no network/storage work or- // backoff occurs while governance rows are locked.- await new Promise((resolve) =>- setTimeout(resolve, 20 * (attempt + 1)),- );- }- }- };- // One shared deadline bounds the sequential batch; an expired batch never- // starts another GitHub request. Other providers retain their own policy.- const githubBatchSignal =- input.endpoint.provider === "github"- ? AbortSignal.timeout(GITHUB_ATTACHMENT_BATCH_TIMEOUT_MS)- : undefined;- // This new image-only lane shares one budget across token acquisition and- // downloads. DB/storage commit semantics remain explicit and unchanged.- const teamsInlineBatchSignal =- input.endpoint.provider === "microsoft-teams"- ? AbortSignal.timeout(10_000)- : undefined;- for (let attachment of boundedAttachments) {- const teamsInlineImage =- input.endpoint.provider === "microsoft-teams" &&- input.endpointRuntime.attachmentRecoveryDescriptor(attachment)?.locator- .kind === "teams_inline_image";- const telegramMedia =- input.endpoint.provider === "telegram" &&- hasTelegramMediaProvenance(attachment);- const sourceBoundMedia =- teamsInlineImage ||- telegramMedia ||- input.endpoint.provider === "imessage-photon";- const requireCurrentAttachmentAuthorization =- input.endpoint.provider === "github" || sourceBoundMedia;- try {- if (teamsInlineImage && teamsInlineBatchSignal?.aborted) {- omit("download_unavailable");- continue;- }- // GitHub's anonymized upload URLs carry no trustworthy MIME metadata.- // Resolve public bytes only here, after durable comment admission, and- // then apply the same storage/type policy as every native attachment.- if (input.endpoint.provider === "github") {- await withCurrentAttachmentAuthorization(async () => {});- attachment = await prepareGitHubPublicAttachment(- attachment,- githubBatchSignal,- async (request, signal) => {- await withCurrentAttachmentAuthorization(async () => {});- return (- (await input.endpointRuntime.resolveGitHubAttachmentComment?.(- request,- signal,- )) ?? null- );- },- );- }- if (- requireCurrentAttachmentAuthorization &&- input.endpoint.provider !== "github"- )- await withCurrentAttachmentAuthorization(- async () => {},- sourceBoundMedia,- telegramMedia ? attachment : undefined,- );- if (- attachment.size !== undefined &&- attachment.size > MAX_ATTACHMENT_BYTES- ) {- omit("declared_too_large");- continue;- }- if (!attachment.fetchData) {- omit("download_unavailable");- continue;- }- const originalFilename = sanitizeFilename(attachment.name);- let contentType = normalizeUploadAttachmentContentType({- contentType: normalizeContentType(- attachment.mimeType ?? "application/octet-stream",- ),- originalFilename,- isAllowedContentType,- });- // Reject a provider-declared type before allocating the downloaded- // payload. The actual byte length is checked again after the adapter's- // bounded fetch contract resolves.- // A filename may infer an Office MIME for ordinary documents, but it- // must not bypass byte identification for native media without MIME.- const identifyTelegram =- telegramMedia &&- telegramMediaNeedsIdentification(attachment) &&- normalizeContentType(- attachment.mimeType ?? "application/octet-stream",- ) === "application/octet-stream";- if (!isAllowedContentType(contentType) && !identifyTelegram) {- omit("unsupported_type");- continue;- }- const fetched = teamsInlineImage- ? await input.endpointRuntime.fetchTeamsInlineImage(- attachment,- teamsInlineBatchSignal!,- )- : await attachment.fetchData();- const body = Buffer.isBuffer(fetched) ? fetched : Buffer.from(fetched);- if (body.length === 0) {- omit("empty_download");- continue;- }- if (body.length > MAX_ATTACHMENT_BYTES) {- omit("downloaded_too_large");- continue;- }- if (identifyTelegram) {- contentType =- identifyTelegramMedia(attachment, body) ??- "application/octet-stream";- if (!isAllowedContentType(contentType)) {- omit("unsupported_type");- continue;- }- }- const photonSourceHash = createHash("sha256")- .update(body)- .digest("hex");- if (input.endpoint.provider === "imessage-photon") {- await validatePhotonImage(body, contentType);- const companion = takePhotonCompanion(body);- if (companion?.unavailable) omit("companion_unavailable");- else if (companion) {- const video: Attachment = { type: "video", name: companion.fileName, mimeType: companion.mimeType, size: companion.data.length, fetchData: async () => companion.data };- photonDerivatives.set(video, { source: attachment, sourceHash: photonSourceHash, kind: "live_photo_video" });- boundedAttachments.push(video);- }- if (- HEIF_CONTENT_TYPES.has(contentType) &&- isAllowedContentType("image/jpeg")- ) {- try {- const preview = await photonHeifPreview(body);- const derivative: Attachment = {- type: "image",- name: `${originalFilename} (JPEG preview).jpg`,- mimeType: "image/jpeg",- size: preview.length,- fetchData: async () => preview,- };- photonDerivatives.set(derivative, { source: attachment, sourceHash: photonSourceHash, kind: "heif_jpeg_preview" });- boundedAttachments.push(derivative);- } catch {- omit("preview_unavailable");- }- }- }- const fingerprint = JSON.stringify([- photonSourceHash,- body.length,- contentType,- originalFilename,- ]);- const existingIds = existingByFingerprint.get(fingerprint);- const existingId = existingIds?.shift();- if (requireCurrentAttachmentAuthorization) {- // Revoke during either API resolution or the anonymous byte download- // must prevent storage and attachment registration for that input.- await withCurrentAttachmentAuthorization(- async () => {},- sourceBoundMedia,- telegramMedia ? attachment : undefined,- );- }- const registerPhotonProvenance = async (attachmentId: string) => {- if (input.endpoint.provider !== "imessage-photon") return;- const relation = photonDerivatives.get(attachment);- if (!relation) {- originalPhotonAttachments.set(attachment, attachmentId);- return;- }- const originalAttachmentId =- originalPhotonAttachments.get(relation.source);- if (!originalAttachmentId)- throw new Error("Photon related attachment source is missing");- await db- .insert(chatActions)- .values({- companyId: input.endpoint.companyId,- endpointId: input.endpoint.id,- deliveryId: input.deliveryId,- kind: relation.kind === "heif_jpeg_preview" ? "attachment_derivative" : "attachment_companion",- providerActionId: `photon-${relation.kind}:${input.deliveryId}:${originalAttachmentId}`,- payload: {- originalAttachmentId,- derivativeAttachmentId: attachmentId,- originalSha256: relation.sourceHash,- derivativeSha256: photonSourceHash,- kind: relation.kind,- },- status: "processed",- })- .onConflictDoNothing();- };- if (existingId) {- storedIds.push(existingId);- await registerPhotonProvenance(existingId);- continue;- }- const stored = await options.storage.putFile({- companyId: input.endpoint.companyId,- namespace: `issues/${input.issueId}`,- originalFilename,- contentType,- body,- });- const registration = {- issueId: input.issueId,- issueCommentId: input.issueCommentId,- provider: stored.provider,- objectKey: stored.objectKey,- contentType: stored.contentType,- byteSize: stored.byteSize,- sha256: stored.sha256,- originalFilename: stored.originalFilename,- createdByUserId: input.actorUserId,- };- let row;- try {- row = requireCurrentAttachmentAuthorization- ? await withCurrentAttachmentAuthorization(- (tx) =>- issueService(tx as unknown as Db).createAttachment(- registration,- ),- sourceBoundMedia,- telegramMedia ? attachment : undefined,- )- : await issuesSvc.createAttachment(registration);- } catch (error) {- // An explicit authorization denial happens before registration. Do- // not delete on ambiguous database errors which may have committed.- if (- requireCurrentAttachmentAuthorization &&- isExternalActionAuthorizationChange(error)- )- await options.storage- .deleteObject(input.endpoint.companyId, stored.objectKey)- .catch(() => undefined);- throw error;- }- storedIds.push(row.id);- await registerPhotonProvenance(row.id);- } catch (error) {- if (isExternalActionAuthorizationChange(error)) throw error;- if (- error instanceof PhotonError &&- ["attachment_not_ready", "network", "quota", "credentials"].includes(- error.code,- )- )- throw error;- // Use the closed current-input omission vocabulary consumed by native- // prompts; provider-specific diagnostics remain redacted log codes.- omit(- error instanceof GitHubAttachmentUnavailableError- ? "download_unavailable"- : "processing_failed",- );- // A malformed or unavailable provider attachment must not strand the- // durable text delivery. The rejected file is intentionally omitted;- // the delivery remains auditable through its normalized attachment- // metadata without persisting provider credentials or download URLs.- logger.warn(- {- endpointId: input.endpoint.id,- issueId: input.issueId,- ...(error instanceof GitHubAttachmentUnavailableError- ? {- deliveryId: input.deliveryId,- attachmentDiagnosticCode: error.code,- }- : {}),- attachmentName: sanitizeFilename(attachment.name),- error: redactError(error),- },- "external chat attachment was rejected",- );- }- }- return { storedIds, omissionReasons };- }-- function attachmentOmissionDetail(result: {- omissionReasons: Record<string, number>;- }): string | null {- const entries = Object.entries(result.omissionReasons).filter(- ([, count]) => count > 0,- );- const omitted = entries.reduce((total, [, count]) => total + count, 0);- if (!omitted) return null;- const reasons = entries- .map(([reason, count]) => `${reason.replaceAll("_", " ")}: ${count}`)- .join(", ");- return `${omitted} external attachment${omitted === 1 ? " was" : "s were"} omitted (${reasons})`;- }-- async function settleTelegramAttachmentOnlyFailure(input: {- activeDelivery: DeliveryRow;- attachmentResult: {- storedIds: string[];- omissionReasons: Record<string, number>;- };- commentId: string;- conversationId: string;- endpoint: EndpointRow;- message: Message;- principalId: string | null;- resourceId: string | null;- runtimeContext?: InboundRuntimeContext;- thread: Thread;- }): Promise<boolean> {+ commentId: string;+ conversationId: string;+ endpoint: EndpointRow;+ message: Message;+ principalId: string | null;+ resourceId: string | null;+ runtimeContext?: InboundRuntimeContext;+ thread: Thread;+ }): Promise<boolean> {if (input.endpoint.provider !== "telegram" ||input.message.text.trim().length > 0 ||@@ -8491,351 +5463,40 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {return true;}- async function admitDiscordRootMention(- configuredEndpoint: EndpointRow,- event: DiscordRootMentionAdmissionEvent,- context: RuntimeContext,- ): Promise<boolean> {- if (- !(await ensureDiscordGatewayRuntimeIsCurrent(- configuredEndpoint.id,- context,- ))- ) {- return false;- }- return withCredentialMutationLease(- configuredEndpoint,- async (credentialLease) => {- const threadId = `discord:${event.guildId}:${event.channelId}:${event.messageId}`;- const providerEventId = `${threadId}:${event.messageId}`;- const allowed = await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- const endpoint = await runtimeCallbackEndpoint(- tx,- configuredEndpoint.id,- context,- ["verifying", "active"],- );- const existing = await tx- .select({ state: chatDeliveries.state })- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.endpointId, configuredEndpoint.id),- eq(chatDeliveries.providerEventId, providerEventId),- ),- )- .then((rows) => rows[0] ?? null);- if (- existing &&- ["processed", "filtered", "failed"].includes(existing.state)- )- return false;-- let reason: string | null = null;- if (!endpoint || endpoint.providerAccountId !== event.guildId) {- reason = "Connection is not active";- }- const resource = endpoint- ? await tx- .select()- .from(chatEndpointResources)- .where(- and(- eq(chatEndpointResources.endpointId, endpoint.id),- eq(chatEndpointResources.type, "channel"),- eq(- chatEndpointResources.providerResourceId,- event.channelId,- ),- ),- )- .for("update")- .then((rows) => rows[0] ?? null)- : null;- const enabledCount =- endpoint?.status === "verifying"- ? await tx- .select({ count: sql<number>`count(*)::int` })- .from(chatEndpointResources)- .where(- and(- eq(chatEndpointResources.endpointId, endpoint.id),- eq(chatEndpointResources.type, "channel"),- eq(chatEndpointResources.enabled, true),- eq(chatEndpointResources.availability, "available"),- ),- )- .then((rows) => rows[0]?.count ?? 0)- : 0;- const setupDestination =- endpoint?.status === "verifying" &&- enabledCount === 0 &&- resource?.availability === "available";- if (- !reason &&- !(- endpoint?.allowGroupChats &&- resource?.availability === "available" &&- (resource.enabled || setupDestination)- )- ) {- reason = "Destination is not enabled in Paperclip";- }-- if (!reason && endpoint) {- const principal = await tx- .select({ id: chatExternalPrincipals.id })- .from(chatExternalPrincipals)- .where(- and(- eq(chatExternalPrincipals.companyId, endpoint.companyId),- eq(chatExternalPrincipals.provider, "discord"),- eq(chatExternalPrincipals.providerAccountId, event.guildId),- eq(chatExternalPrincipals.externalId, event.userId),- ),- )- .then((rows) => rows[0] ?? null);- let allowed: boolean;- let linkedDenied = false;- if (principal) {- const authorization = await lockCurrentPrincipalAuthorization(- tx,- endpoint,- principal.id,- );- allowed = authorization.allowed;- linkedDenied = authorization.linkedDenied;- } else if (!endpoint.allowUnlinkedPeople) {- allowed = false;- } else if (!endpoint.sponsorUserId) {- allowed = true;- } else {- const sponsor = await tx- .select({- status: companyMemberships.status,- membershipRole: companyMemberships.membershipRole,- })- .from(companyMemberships)- .where(- and(- eq(companyMemberships.companyId, endpoint.companyId),- eq(companyMemberships.principalType, "user"),- eq(companyMemberships.principalId, endpoint.sponsorUserId),- ),- )- .for("update")- .then((rows) => rows[0] ?? null);- allowed =- sponsor?.status === "active" &&- sponsor.membershipRole !== "viewer";- }- if (!allowed) {- reason = linkedDenied- ? "Linked Paperclip account is not currently permitted"- : endpoint.allowUnlinkedPeople- ? "Endpoint sponsor can no longer authorize external guests"- : "External identity must be linked to a Paperclip account";- }- }- if (!reason) {- await credentialLease.assertOwned(tx);- return true;- }-- const filteredAt = new Date();- const normalizedEvent = {- providerEventId,- kind: "mention",- trigger: "mention",- resource: {- type: "channel",- providerResourceId: event.channelId,- },- conversation: { externalThreadId: threadId },- message: { providerMessageId: event.messageId },- filtering: { contentRetained: false, providerThreadCreated: false },- };- await notifyChatDeliveryWork(tx);- await tx- .insert(chatDeliveries)- .values({- companyId: configuredEndpoint.companyId,- endpointId: configuredEndpoint.id,- providerEventId,- deduplicationKey: createHash("sha256")- .update(providerEventId)- .digest("hex"),- eventKind: "mention",- normalizedEvent,- state: "filtered",- redactedError: reason,- processedAt: filteredAt,- })- .onConflictDoUpdate({- target: [- chatDeliveries.endpointId,- chatDeliveries.providerEventId,- ],- set: {- normalizedEvent,- principalId: null,- state: "filtered",- nextAttemptAt: null,- redactedError: reason,- processedAt: filteredAt,- updatedAt: filteredAt,- },- });- await tx- .update(chatEndpoints)- .set({ lastEventAt: filteredAt, updatedAt: filteredAt })- .where(eq(chatEndpoints.id, configuredEndpoint.id));- await credentialLease.assertOwned(tx);- return false;- });- if (!allowed || !event.message || !context.endpointRuntime) {- return false;- }- const thread = context.endpointRuntime.thread(event.threadId);- await processMessage(- configuredEndpoint,- thread,- event.message,- "mention",- true,- null,- context,- undefined,- null,- true,- undefined,- true,- );- const staged = await db- .select({ state: chatDeliveries.state })- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.endpointId, configuredEndpoint.id),- eq(chatDeliveries.providerEventId, providerEventId),- ),- )- .then((rows) => rows[0] ?? null);- if (- !staged ||- !["received", "retry", "processing"].includes(staged.state)- ) {- return false;- }-- await options.discordRootThreadTransportBarrier?.();- await credentialLease.assertOwned();- if (- !(await ensureDiscordGatewayRuntimeIsCurrent(- configuredEndpoint.id,- context,- ))- ) {- return false;- }- try {- await context.endpointRuntime.ensureDiscordRootThread({- channelId: event.channelId,- content: event.message.text,- messageId: event.messageId,- });- } catch (error) {- // The durable provisional receipt owns recovery. Do not let a- // transient REST failure escape the Gateway event handler or ask the- // adapter to create the same thread outside Paperclip's lifecycle- // fence.- logger.warn(- {- endpointId: configuredEndpoint.id,- error: redactError(error),- providerEventId,- },- "Discord root thread creation will be retried from the durable receipt",- );- return false;- }- const promoted = await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- const current = await runtimeCallbackEndpoint(- tx,- configuredEndpoint.id,- context,- ["verifying", "active"],- );- if (!current) return false;- await notifyChatDeliveryWork(tx);- const [row] = await tx- .update(chatDeliveries)- .set({- state: "received",- normalizedEvent: sql`${chatDeliveries.normalizedEvent} - 'providerThreadPending'`,- nextAttemptAt: null,- redactedError: null,- updatedAt: new Date(),- })- .where(- and(- eq(chatDeliveries.endpointId, configuredEndpoint.id),- eq(chatDeliveries.providerEventId, providerEventId),- eq(chatDeliveries.state, "retry"),- sql`${chatDeliveries.normalizedEvent}->>'providerThreadPending' = 'true'`,- ),- )- .returning({ id: chatDeliveries.id });- await credentialLease.assertOwned(tx);- return Boolean(row);- });- if (promoted)- scheduleConversationDrain(configuredEndpoint.id, threadId);- // Paperclip created the provider thread inside its credential/reach- // lease. Returning false prevents the adapter from creating it again;- // the durable drain owns the remaining task mutation.- return false;- },- );- }-- async function stageInboundWakeup(- tx: DbOrTransaction,- input: {- endpoint: EndpointRow;- deliveryId: string;- conversation: typeof chatConversations.$inferSelect;- commentId: string;- principalId: string;- actorUserId: string | null;- },- ) {- await tx- .insert(chatActions)- .values({- companyId: input.endpoint.companyId,- endpointId: input.endpoint.id,- deliveryId: input.deliveryId,- conversationId: input.conversation.id,- principalId: input.principalId,- kind: "inbound_wakeup",- providerActionId: `inbound_wakeup:${input.deliveryId}`,- status: "preparing",- payload: {- version: 1,- issueId: input.conversation.issueId,- agentId: input.endpoint.assignedAgentId,- commentId: input.commentId,- sessionGeneration: input.conversation.sessionGeneration,- requestedByActorType: input.actorUserId ? "user" : "system",- requestedByActorId: input.actorUserId ?? input.principalId,- },- })- .onConflictDoNothing();- }+ async function stageInboundWakeup(+ tx: DbOrTransaction,+ input: {+ endpoint: EndpointRow;+ deliveryId: string;+ conversation: typeof chatConversations.$inferSelect;+ commentId: string;+ principalId: string;+ actorUserId: string | null;+ },+ ) {+ await tx+ .insert(chatActions)+ .values({+ companyId: input.endpoint.companyId,+ endpointId: input.endpoint.id,+ deliveryId: input.deliveryId,+ conversationId: input.conversation.id,+ principalId: input.principalId,+ kind: "inbound_wakeup",+ providerActionId: `inbound_wakeup:${input.deliveryId}`,+ status: "preparing",+ payload: {+ version: 1,+ issueId: input.conversation.issueId,+ agentId: input.endpoint.assignedAgentId,+ commentId: input.commentId,+ sessionGeneration: input.conversation.sessionGeneration,+ requestedByActorType: input.actorUserId ? "user" : "system",+ requestedByActorId: input.actorUserId ?? input.principalId,+ },+ })+ .onConflictDoNothing();+ }async function authorizeInboundWakeup(tx: DbOrTransaction,@@ -11256,2688 +7917,2118 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {redactedError: filteredReason,processedAt: new Date(),updatedAt: new Date(),- })- .where(eq(chatDeliveries.id, activeDelivery.id));- });- return;- }-- const filterPreControlSource = async (database: DbOrTransaction) => {- if (- controlCommand === "status" ||- (controlCommand === "new" &&- endpoint.provider === "telegram" &&- surfaceKind === "native_thread") ||- guidanceCommand ||- (await readChatControlChronology(- database,- endpoint,- thread,- activeDelivery,- )) !== "before_or_unproven"- )- return false;- const filteredAt = new Date();- await database- .update(chatDeliveries)- .set({- state: "filtered",- nextAttemptAt: null,- processedAt: filteredAt,- updatedAt: filteredAt,- redactedError:- "Message predates or cannot be ordered after a completed chat close/new. Send a new request to start work.",- })- .where(- and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.companyId, endpoint.companyId),- eq(chatDeliveries.state, "processing"),- ),- );- return true;- };- if (await filterPreControlSource(db)) return;- const photonQuote =- endpoint.provider === "imessage-photon"- ? photonReplyReference(message.raw)- : null;- if (controlCommand && photonQuote) {- const source = await db- .select({ conversationId: chatMessageLinks.conversationId })- .from(chatMessageLinks)- .where(- and(- eq(chatMessageLinks.companyId, endpoint.companyId),- eq(chatMessageLinks.endpointId, endpoint.id),- eq(chatMessageLinks.providerMessageId, photonQuote.guid),- ),- )- .limit(1)- .then((rows) => rows[0]);- if (!source || source.conversationId !== existingConversation?.id) {- await db.transaction(async (tx) => {- await notifyChatDeliveryWork(tx);- return tx- .update(chatDeliveries)- .set({- state: "filtered",- processedAt: new Date(),- nextAttemptAt: null,- redactedError:- "Quoted control does not belong to the current task generation",- updatedAt: new Date(),- })- .where(eq(chatDeliveries.id, activeDelivery.id));- });- return;- }- }-- if (guidanceCommand) {- const assignedAgentName =- guidanceCommand === "start"- ? await db- .select({ name: agents.name })- .from(agents)- .where(- and(- eq(agents.companyId, endpoint.companyId),- eq(agents.id, endpoint.assignedAgentId),- ),- )- .then((rows) => rows[0]?.name ?? "this agent")- : null;- const responseText =- guidanceCommand === "start"- ? `Send a direct message to start work with ${assignedAgentName}. In a group, use /task@${endpoint.botUsername ?? "your_bot"} followed by your request. Use /status, /new, or /close to manage the active task in this chat.`- : guidanceCommand === "task"- ? `Please include a request after /task@${endpoint.botUsername ?? "your_bot"}.`- : `Available commands: /task@${endpoint.botUsername ?? "your_bot"} followed by your request, /status, /new, and /close.`;- const publicationBinding =- existingConversation && existingIssue- ? { conversation: existingConversation, issue: existingIssue }- : null;- let effect: typeof chatActions.$inferSelect | null = null;- if (publicationBinding) {- await db.transaction(async (tx) => {- await tx- .update(chatEndpoints)- .set({ lastEventAt: new Date(), updatedAt: new Date() })- .where(eq(chatEndpoints.id, endpoint.id));- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- conversationId: publicationBinding.conversation.id,- state: "processed",- processedAt: new Date(),- redactedError: null,- updatedAt: new Date(),- })- .where(eq(chatDeliveries.id, activeDelivery.id));- await stageAuthorizedTaskControlPublication(tx, {- companyId: endpoint.companyId,- endpointId: endpoint.id,- conversationId: publicationBinding.conversation.id,- issueId: publicationBinding.issue.id,- idempotencyKey: `control:guidance:${activeDelivery.id}`,- payload: projectSafeChatPublication({- classification: "external",- source: "task_control",- text: responseText,- }),- principalId: principalResolution.principal.id,- });- });- } else {- const effectContext =- runtimeContext ??- runtimeContextForRecord(- (await endpointRecord(endpoint.id)) ??- (() => {- throw new Error("Chat endpoint is unavailable");- })(),- );- effect = await db.transaction((tx) =>- stageProviderEffect(tx, {- endpoint,- deliveryId: activeDelivery.id,- principalId: principalResolution.principal.id,- providerActionId: `provider_effect:delivery:${activeDelivery.id}`,- payload: {- version: 1,- effect: "thread_message",- threadId: thread.id,- text: responseText,- settleDelivery: true,- resourceId: resource.id,- },- runtimeContext: effectContext,- }),- );- if (!effect) throw new Error("Provider effect was not persisted");- if ((await processProviderEffect(effect.id, thread)) !== "processed")- return;- }- // Telegram's command reply is the acknowledgement. A control-only- // request starts no run that could later retire a processing receipt.- await Promise.allSettled([- receiptReactionSupported && endpoint.provider !== "telegram"- ? addReceiptReaction({- deliveryId: activeDelivery.id,- endpoint,- message,- runtimeContext,- thread,- })- : Promise.resolve(),- addressed && !thread.isDM ? thread.subscribe() : Promise.resolve(),- ]);- return;- }-- if (controlCommand) {- const isTelegramForumTopic =- endpoint.provider === "telegram" && surfaceKind === "native_thread";- const taskLabel = existingIssue- ? `${existingIssue.identifier}: ${existingIssue.title}`- : "No task is active in this conversation.";- const responseText =- controlCommand === "status"- ? existingIssue- ? `${taskLabel} — ${existingIssue.status}`- : taskLabel- : controlCommand === "new"- ? isTelegramForumTopic- ? existingIssue- ? `${taskLabel} stays bound to this forum topic. Open a new Telegram forum topic to start a new Paperclip task.`- : "Open a new Telegram forum topic to start a new Paperclip task."- : "Send your request to start a new Paperclip task."- : existingConversation- ? isTelegramForumTopic- ? "This chat conversation is closed. A later message here will continue the same Paperclip task."- : "This chat conversation is closed. Send another message to start a new task."- : "No task is active. Send a message to start one.";- const publicationBinding =- existingConversation && existingIssue- ? { conversation: existingConversation, issue: existingIssue }- : null;- if (publicationBinding) {- const publicationControl =- controlCommand === "new" && isTelegramForumTopic- ? "new_guidance"- : controlCommand;- const staged = await db.transaction(async (tx) => {- await tx- .update(chatEndpoints)- .set({ lastEventAt: new Date(), updatedAt: new Date() })- .where(eq(chatEndpoints.id, endpoint.id));- if (await filterPreControlSource(tx)) return false;- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- conversationId: publicationBinding.conversation.id,- state: "processed",- processedAt: new Date(),- updatedAt: new Date(),- })- .where(eq(chatDeliveries.id, activeDelivery.id));- await stageAuthorizedTaskControlPublication(tx, {- companyId: endpoint.companyId,- endpointId: endpoint.id,- conversationId: publicationBinding.conversation.id,- issueId: publicationBinding.issue.id,- idempotencyKey: `control:${publicationControl}:${activeDelivery.id}`,- payload: projectSafeChatPublication({- classification: "external",- source: "task_control",- text: responseText,- }),- principalId: principalResolution.principal.id,- });- return true;- });- if (!staged) return;- } else {- const effectContext =- runtimeContext ??- runtimeContextForRecord(- (await endpointRecord(endpoint.id)) ??- (() => {- throw new Error("Chat endpoint is unavailable");- })(),- );- const effect = await db.transaction(async (tx) => {- return stageProviderEffect(tx, {- endpoint,- deliveryId: activeDelivery.id,- principalId: principalResolution.principal.id,- providerActionId: `provider_effect:delivery:${activeDelivery.id}`,- payload: {- version: 1,- effect: "thread_message",- threadId: thread.id,- text: responseText,- settleDelivery: true,- resourceId: resource.id,- },- runtimeContext: effectContext,- });- });- if (!effect) throw new Error("Provider effect was not persisted");- if ((await processProviderEffect(effect.id, thread)) !== "processed")- return;- }- // This command stages a reply, not new agent work to acknowledge.- await Promise.allSettled([- receiptReactionSupported && endpoint.provider !== "telegram"- ? addReceiptReaction({- deliveryId: activeDelivery.id,- endpoint,- message,- runtimeContext,- thread,- })- : Promise.resolve(),- addressed && !thread.isDM ? thread.subscribe() : Promise.resolve(),- ]);- return;- }-- const inboundActivityPublications: ActivityPublication[] = [];- const persistTaskMutation = async (- taskTx: DbOrTransaction,- taskEndpoint: EndpointRow,- taskUserId: string | null,- ) => {- let conversation = existingConversation;- if (!conversation) {- const sessionGeneration = isLinear- ? (latestConversation?.sessionGeneration ?? 0) + 1- : 1;- const issue = await issuesSvc.create(- endpoint.companyId,- {- title: safeTitle(- githubAutomatic- ? `PR #${githubAutomatic.context.pullNumber}: ${githubAutomatic.context.title}`- : githubIssue ? `GitHub issue #${githubIssue.context.issueNumber}: ${githubIssue.context.title}` : message.text,- `${PROVIDER_LABELS[endpoint.provider]} conversation`,- ),- description: `Started from ${PROVIDER_LABELS[endpoint.provider]}: ${resource.label}`,- status: "todo",- priority: "medium",- assigneeAgentId: endpoint.assignedAgentId,- createdByUserId: taskUserId ?? endpoint.sponsorUserId,- responsibleUserId: taskUserId ?? endpoint.sponsorUserId,- originKind: "chat_channel",- originId: `${endpoint.id}:${thread.id}:${sessionGeneration}`,- idempotencyKey: `chat:${endpoint.id}:${thread.id}:${sessionGeneration}`,- },- taskTx,- );- await taskTx- .insert(chatConversations)- .values({- companyId: endpoint.companyId,- endpointId: endpoint.id,- resourceId: resource.id,- issueId: issue.id,- externalConversationId: thread.channelId,- externalThreadId: thread.id,- sessionGeneration,- externalLabel: resource.label,- providerUrl,- isDirectMessage: thread.isDM,- communicationGuidance: buildChatCommunicationGuidance({- provider: taskEndpoint.provider,- isDirectMessage: thread.isDM,- communicationInstructions: taskEndpoint.communicationInstructions,- }),- state: "active",- lastActivityAt: new Date(),- })- .onConflictDoNothing();- conversation = await taskTx- .select()- .from(chatConversations)- .where(- and(- eq(chatConversations.endpointId, endpoint.id),- eq(chatConversations.externalConversationId, thread.channelId),- eq(chatConversations.externalThreadId, thread.id),- eq(chatConversations.sessionGeneration, sessionGeneration),- ),- )- .then((rows) => rows[0] ?? null);- }- if (!conversation)- throw conflict(- "Could not bind external conversation to a Paperclip task",- );-- const issue =- existingIssue?.id === conversation.issueId- ? existingIssue- : await taskTx- .select()- .from(issues)- .where(eq(issues.id, conversation.issueId))- .then((rows) => rows[0] ?? null);- if (!issue) throw notFound("Bound task not found");- const [assignedAgentTrust] = taskEndpoint.provider === "github" ? await taskTx.select({ permissions: agents.permissions }).from(agents).where(and(eq(agents.companyId, taskEndpoint.companyId), eq(agents.id, taskEndpoint.assignedAgentId))) : [];- if (!taskUserId || ((githubAutomatic || githubIssue) && !principalResolution.userId) || assignedAgentTrust?.permissions?.trustPreset === LOW_TRUST_REVIEW_PRESET) {- const reviewPreset = {- id: LOW_TRUST_REVIEW_PRESET,- version: LOW_TRUST_REVIEW_PRESET_VERSION,- rawOutputDisposition: LOW_TRUST_REVIEW_RAW_OUTPUT_DISPOSITION,- } as const;- await taskTx- .update(issues)- .set({- sourceTrust: {- preset: LOW_TRUST_REVIEW_PRESET,- disposition: "quarantined",- sourceIssueId: issue.id,- },- executionPolicy: {- mode: "normal",- commentRequired: true,- stages: [],- ...issue.executionPolicy,- reviewPreset,- authorizationPolicy: {- ...githubPolicyRecord(issue.executionPolicy?.authorizationPolicy),- trustPreset: LOW_TRUST_REVIEW_PRESET,- reviewPreset,- trustBoundary: {- mode: LOW_TRUST_REVIEW_PRESET,- companyId: endpoint.companyId,- rootIssueId: issue.id,- issueIds: [issue.id],- allowedAgentIds: [endpoint.assignedAgentId],- allowedToolClasses: [- "git.read",- "github.pr.read",- "tests.local",- ],- ...githubPolicyRecord(githubPolicyRecord(issue.executionPolicy?.authorizationPolicy)?.trustBoundary),- },- },- },- updatedAt: new Date(),- })- .where(- and(- eq(issues.id, issue.id),- eq(issues.companyId, endpoint.companyId),- ),- );- }-- if (issue.status === "done" || issue.status === "cancelled") {- await issuesSvc.update(- issue.id,- {- status: "todo",- actorUserId: taskUserId ?? taskEndpoint.sponsorUserId,- },- taskTx,- );- }- const body =- (githubManual ? githubManualMessagePrompt({- event: githubManual.event,- policy: githubManual.policy,- repository: resource.providerResourceId,- thread: thread.id,- sender: { id: principalResolution.principal.externalId, login: principalResolution.principal.handle },- message: message.text,- }) : message.text.trim()) ||- (message.attachments.length > 0- ? taskEndpoint.provider === "microsoft-teams" &&- !thread.isDM &&- nativeInboundAttachments.length === 0- ? `Shared ${message.attachments.length} Microsoft Teams file reference${message.attachments.length === 1 ? "" : "s"}.${providerUrl ? ` Open in Microsoft Teams: ${providerUrl}` : ""}`- : `Shared ${message.attachments.length} file${message.attachments.length === 1 ? "" : "s"}.`- : taskEndpoint.provider === "slack" && (trigger === "mention" || message.isMention === true)- ? "Started a conversation by mentioning the agent."- : "Sent an empty message.");- let comment!: Awaited<ReturnType<typeof issuesSvc.addComment>>;- await taskTx- .update(chatEndpoints)- .set({- status: taskEndpoint.status,- setup: taskEndpoint.setup,- healthMessage:- taskEndpoint.status === "verifying"- ? "Test conversation received"- : "Connected",- lastEventAt: new Date(),- activatedAt:- taskEndpoint.status === "active"- ? taskEndpoint.activatedAt- : null,- updatedAt: new Date(),- })- .where(eq(chatEndpoints.id, taskEndpoint.id));- comment = await issuesSvc.addComment(- conversation!.issueId,- body.slice(0, MAX_INBOUND_TEXT),- taskUserId ? { userId: taskUserId } : {},- {- authorType: taskUserId ? "user" : "system",- metadata: {- version: 1,- ...(endpoint.provider === "imessage-photon"- ? { sourceChannel: "imessage-photon" as const }- : {}),- sections: [- {- title: `${PROVIDER_LABELS[endpoint.provider]} sender`,- rows: [- ...(endpoint.provider === "imessage-photon" &&- photonReplyReference(message.raw)- ? [- {- type: "key_value" as const,- label: "Reply to message",- value: photonReplyReference(message.raw)!.guid,- },- ...(photonReplyReference(message.raw)!.part- ? [- {- type: "key_value" as const,- label: "Reply part",- value: photonReplyReference(message.raw)!- .part!,- },- ]- : []),- ]- : []),- {- type: "key_value",- label: "Name",- value: message.author.fullName || message.author.userName,- },- {- type: "key_value",- label: "Provider ID",- value: stableExternalPrincipalId(- endpoint.provider,- message.author,- message.raw,- ),- },- {- type: "key_value",- label: "Authority",- value: taskUserId- ? "Linked Paperclip user"- : "Sponsored external guest (restricted)",- },- ],- },- ],- },- sourceTrust: taskUserId- ? null- : {- preset: LOW_TRUST_REVIEW_PRESET,- disposition: "quarantined",- sourceIssueId: conversation!.issueId,- },- },- taskTx,- );- await taskTx- .update(chatDeliveries)- .set({- conversationId: conversation!.id,- updatedAt: new Date(),- })- .where(eq(chatDeliveries.id, activeDelivery.id));- await taskTx- .insert(chatMessageLinks)- .values({- companyId: endpoint.companyId,- endpointId: endpoint.id,- conversationId: conversation!.id,- deliveryId: activeDelivery.id,- commentId: comment.id,- providerMessageId: message.id,- direction: "inbound",- })- .onConflictDoNothing();- if (taskEndpoint.provider === "slack" || taskEndpoint.provider === "speko") {- await resumeExternalConversation(taskTx as unknown as Db, endpoint.companyId, conversation.issueId);- }- await taskTx- .update(chatConversations)- .set({- state: "active",- lastActivityAt: new Date(),- ...(providerUrl ? { providerUrl } : {}),- updatedAt: new Date(),- })- .where(eq(chatConversations.id, conversation!.id));- await taskTx- .update(toolConnections)- .set({- status: "active",- enabled: true,- healthStatus: "healthy",- healthMessage: "Connected",- lastHealthAt: new Date(),- updatedAt: new Date(),- })- .where(eq(toolConnections.id, taskEndpoint.connectionId));- if (endpoint.provider === "github") {- const guest = !principalResolution.userId;- await taskTx.update(chatDeliveries).set({ normalizedEvent: sql`${chatDeliveries.normalizedEvent} || ${JSON.stringify({ githubAuthority: { guest, responsibleUserId: taskUserId, sponsorUserId: guest ? taskEndpoint.sponsorUserId : null } })}::jsonb` }).where(eq(chatDeliveries.id, activeDelivery.id));- }- if (githubAutomatic) {- await taskTx.insert(chatGitHubReviews).values({- companyId: endpoint.companyId, endpointId: endpoint.id, issueId: issue.id,- repositoryId: githubAutomatic.context.repositoryId, repository: githubAutomatic.context.repository,- pullNumber: githubAutomatic.context.pullNumber, headSha: githubAutomatic.context.headSha,- deliveryId: activeDelivery.id, configurationRevision: githubAutomatic.revision,- policySnapshot: githubAutomatic.policy, event: githubAutomatic.context, state: "queued",- }).onConflictDoNothing();- }- await stageInboundWakeup(taskTx, {- endpoint: taskEndpoint,- deliveryId: activeDelivery.id,- conversation,- commentId: comment.id,- principalId: principalResolution.principal.id,- actorUserId: taskUserId,- });- if (taskEndpoint.provider === "imessage-photon") {- await logActivity(- taskTx as Db,- {- companyId: taskEndpoint.companyId,- actorType: taskUserId ? "user" : "system",- actorId: taskUserId ?? "chat:imessage-photon",- action: "issue.comment_added",- entityType: "issue",- entityId: issue.id,- details: {- commentId: comment.id,- issueIdentifier: issue.identifier,- source: "chat:imessage-photon",- endpointId: taskEndpoint.id,- },- },- inboundActivityPublications,- );- }- return { actorUserId: taskUserId, comment, conversation, issue };- };- const taskMutation = await db.transaction(async (tx) => {- // Admission and durable task mutation are separate so the provider- // webhook can return inside its response budget. Take the endpoint and- // destination locks again at the authoritative mutation boundary for- // every provider: either a reach revocation commits first and this- // event is redacted, or this task/comment commits first and the- // revocation waits. There is no stale-snapshot middle.- await options.reachAuthorizationBarrier?.();- const currentEndpoint = await tx- .select()- .from(chatEndpoints)- .where(eq(chatEndpoints.id, endpoint.id))- .for("update")- .then((rows) => rows[0] ?? null);- if (!currentEndpoint) throw notFound("Chat endpoint not found");- const currentResource = thread.isDM- ? resource- : await tx- .select()- .from(chatEndpointResources)- .where(- and(- eq(chatEndpointResources.id, resource.id),- eq(chatEndpointResources.endpointId, endpoint.id),- ),- )- .for("update")- .then((rows) => rows[0] ?? null);- const currentPrincipalAuthorization =- await lockCurrentPrincipalAuthorization(- tx,- currentEndpoint,- principalResolution.principal.id,- );- const automaticContext = githubAutomatic?.context ?? githubIssue?.context;- const automaticAdmission = automaticContext ? await githubAutomaticAdmission(tx, currentEndpoint, automaticContext) : null;- if (automaticContext && !automaticAdmission?.allowed) currentPrincipalAuthorization.allowed = false;- if (automaticAdmission?.allowed) currentPrincipalAuthorization.userId = automaticAdmission.responsibleUserId ?? null;- const endpointStillAllowed =- currentEndpoint.status === "verifying" ||- currentEndpoint.status === "active";- const destinationStillAllowed = thread.isDM- ? currentEndpoint.allowDirectMessages- : nonDirectDestinationAllowed(currentEndpoint, currentResource);- const mentionStillAllowed =- currentEndpoint.provider !== "slack" ||- !currentEndpoint.requireAtMention ||- trigger === "mention" ||- message.isMention === true;- if (- !endpointStillAllowed ||- !mentionStillAllowed ||- !destinationStillAllowed ||- !currentPrincipalAuthorization.allowed- ) {- const filteredAt = new Date();- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- state: "filtered",- normalizedEvent: redactedDestinationNormalized,- principalId: null,- nextAttemptAt: null,- processedAt: filteredAt,- redactedError: !mentionStillAllowed- ? "Message did not @mention the bot"- : endpointStillAllowed- ? destinationStillAllowed- ? currentPrincipalAuthorization.linkedDenied- ? "Linked Paperclip account is not currently permitted"- : currentEndpoint.allowUnlinkedPeople- ? "Endpoint sponsor can no longer authorize external guests"- : "External identity must be linked to a Paperclip account"- : "Destination is not enabled in Paperclip"- : "Connection is not active",- updatedAt: filteredAt,- })- .where(- and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.state, "processing"),- ),- );- // A principal first observed only by this now-revoked event must not- // survive as a side-channel. Preserve established or linked- // identities referenced by any other durable record.- await tx- .delete(chatExternalPrincipals)- .where(- and(- eq(chatExternalPrincipals.id, principalResolution.principal.id),- notExists(- tx- .select({ id: chatDeliveries.id })- .from(chatDeliveries)- .where(- eq(- chatDeliveries.principalId,- principalResolution.principal.id,- ),- ),- ),- notExists(- tx- .select({ id: chatIdentityLinks.id })- .from(chatIdentityLinks)- .where(- eq(- chatIdentityLinks.principalId,- principalResolution.principal.id,- ),- ),- ),- notExists(- tx- .select({ id: chatActions.id })- .from(chatActions)- .where(- eq(- chatActions.principalId,- principalResolution.principal.id,- ),- ),- ),- ),- );- return null;- }- // Close completion takes this endpoint lock in its receipt transaction.- // Recheck after the lock: an old input held between precheck and task- // mutation must not create work after that control commits.- if (await filterPreControlSource(tx)) return null;- return persistTaskMutation(- tx,- currentPrincipalAuthorization.sponsorUserId ? { ...currentEndpoint, sponsorUserId: currentPrincipalAuthorization.sponsorUserId } : currentEndpoint,- currentPrincipalAuthorization.userId,- );- });- if (!taskMutation) return;- // The open task can fetch the comment immediately, before attachments- // finish preparing or the agent starts. Never publish an uncommitted row.- for (const publication of inboundActivityPublications) {- publishActivity(publication);- }- const { actorUserId, comment, conversation, issue } = taskMutation;- const attachmentResult = await ingestAttachments({- endpoint,- endpointRuntime,- deliveryId: activeDelivery.id,- issueId: conversation.issueId,- issueCommentId: comment.id,- attachments: nativeInboundAttachments,- attachmentLimitOmissions: githubAttachmentLimitOmissions(message),- unavailableReferenceCount: unavailableTeamsReferences,- actorUserId,- });- if (- await settleTelegramAttachmentOnlyFailure({- activeDelivery,- attachmentResult,- commentId: comment.id,- conversationId: conversation.id,- endpoint,- message,- principalId: principalResolution.principal.id,- resourceId: resource.id,- runtimeContext,- thread,- })- ) {- return;- }- // Do not discard a subscription failure after marking the delivery- // processed. A retry reuses the committed message link above and tries- // this idempotent subscription again before completing the delivery.- if (addressed && !thread.isDM) await thread.subscribe();- await acceptInboundWakeup(activeDelivery.id, attachmentResult);- if (!(await processInboundWakeup(activeDelivery.id))) return;- const acceptedWake = await db- .select({ status: chatActions.status })- .from(chatActions)- .where(- and(- eq(chatActions.deliveryId, activeDelivery.id),- eq(chatActions.kind, "inbound_wakeup"),- ),- )- .limit(1)- .then((rows) => rows[0] ?? null);- if (acceptedWake?.status !== "processed") return;- // Provider-visible acknowledgement begins only after the task, external- // comment, durable wakeup request, delivery state, and message link commit.- await Promise.allSettled([- receiptReactionSupported- ? addReceiptReaction({- deliveryId: activeDelivery.id,- endpoint,- message,- runtimeContext,- thread,- })- : Promise.resolve(),- // Slack implements this through assistant.threads.setStatus, which- // requires assistant:write. The least-privilege Paperclip manifest- // deliberately does not request that scope; the coalesced lifecycle- // reply below is the visible working state instead.- endpoint.provider === "slack"- ? Promise.resolve()- : thread.startTyping("Working…"),- ]);- } catch (error) {- const providerEffectAmbiguous =- error !== null &&- typeof error === "object" &&- "code" in error &&- error.code === "CHAT_PROVIDER_EFFECT_AMBIGUOUS";- const terminal =- providerEffectAmbiguous ||- isExternalActionAuthorizationChange(error) ||- activeDelivery.attempts >= 5;- await db.transaction(async (tx) => {- await notifyChatDeliveryWork(tx);- return tx- .update(chatDeliveries)- .set({- state: terminal ? "failed" : "retry",- nextAttemptAt: terminal- ? null- : new Date(- Date.now() +- Math.min(60_000, 1000 * 2 ** activeDelivery.attempts),- ),- redactedError: redactError(error),- updatedAt: new Date(),- })- .where(- and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.state, "processing"),- ),- );- });- if (terminal) await settleRejectedInboundWakeups(activeDelivery.id);- throw error;- }- }-- function deliveryContentWasRedacted(normalizedEvent: unknown): boolean {- if (- !normalizedEvent ||- typeof normalizedEvent !== "object" ||- Array.isArray(normalizedEvent)- )- return false;- const filtering = (normalizedEvent as { filtering?: unknown }).filtering;- return (- Boolean(filtering) &&- typeof filtering === "object" &&- !Array.isArray(filtering) &&- (filtering as { contentRetained?: unknown }).contentRetained === false- );- }-- function setupDestinationActivationSuppressed(- normalizedEvent: unknown,- ): boolean {- if (- !normalizedEvent ||- typeof normalizedEvent !== "object" ||- Array.isArray(normalizedEvent)- )- return false;- const normalized = normalizedEvent as {- admission?: { origin?: unknown };- admissionAuthorization?: { version?: unknown };- };- return (- normalized.admission?.origin === "provider_confirmed_action" ||- normalized.admissionAuthorization?.version === 1- );- }-- function discordRootThreadPending(- delivery: Pick<DeliveryRow, "normalizedEvent">,- ): boolean {- return (- Boolean(delivery.normalizedEvent) &&- typeof delivery.normalizedEvent === "object" &&- !Array.isArray(delivery.normalizedEvent) &&- (delivery.normalizedEvent as { providerThreadPending?: unknown })- .providerThreadPending === true- );- }-- async function reconcileDiscordRootThread(- endpoint: EndpointRow,- delivery: DeliveryRow,- threadId: string,- ): Promise<boolean> {- try {- const normalized = delivery.normalizedEvent as {- message?: { providerMessageId?: unknown; text?: unknown };- resource?: { providerResourceId?: unknown };- };- const discordThreadParts = threadId.split(":");- const channelId =- discordThreadParts[0] === "discord" && discordThreadParts.length >= 4- ? discordThreadParts[2]- : normalized.resource?.providerResourceId;- const messageId = normalized.message?.providerMessageId;- if (typeof channelId !== "string" || typeof messageId !== "string") {- throw new DiscordAdapterCompatibilityError(- "the provisional root receipt is missing its channel or message id",- );- }- const runtimeFence = lifecycleRuntimeFence(delivery);- if (!runtimeFence) {- throw new DiscordAdapterCompatibilityError(- "the provisional root receipt is missing its runtime fence",- );- }- return await withCredentialMutationLease(- endpoint,- async (credentialLease) => {- const currentEndpoint = await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- const current = await runtimeCallbackEndpoint(- tx,- endpoint.id,- runtimeFence,- ["verifying", "active"],- );- await credentialLease.assertOwned(tx);- return current;- });- if (!currentEndpoint) {- throw conflict(- "Discord root thread credentials or connection state changed before recovery",- { code: "chat_endpoint_runtime_superseded" },- );- }- const endpointRuntime = await runtimeFor(currentEndpoint);- await credentialLease.assertOwned();- await endpointRuntime.ensureDiscordRootThread({- channelId,- messageId,- content:- typeof normalized.message?.text === "string"- ? normalized.message.text- : "Paperclip task",- });- return await db.transaction(async (tx) => {- await credentialLease.assertOwned(tx);- const current = await runtimeCallbackEndpoint(- tx,- endpoint.id,- runtimeFence,- ["verifying", "active"],- );- if (!current) return false;- await notifyChatDeliveryWork(tx);- const [promoted] = await tx- .update(chatDeliveries)- .set({- state: "received",- normalizedEvent: sql`${chatDeliveries.normalizedEvent} - 'providerThreadPending'`,- nextAttemptAt: null,- redactedError: null,- updatedAt: new Date(),- })- .where(- and(- eq(chatDeliveries.id, delivery.id),- eq(chatDeliveries.state, "retry"),- sql`${chatDeliveries.normalizedEvent}->>'providerThreadPending' = 'true'`,- ),- )- .returning({ id: chatDeliveries.id });- await credentialLease.assertOwned(tx);- return Boolean(promoted);- });- },- );- } catch (error) {- const disposition = classifyChatPublicationError(- error,- delivery.attempts + 1,- );- const terminal =- disposition.kind === "resource_unavailable" ||- disposition.kind === "failed";- const retryAfterMs =- disposition.kind === "retry"- ? disposition.retryAfterMs- : DISCORD_ROOT_THREAD_CONFIRMATION_DELAY_MS;- const now = new Date();- await db.transaction(async (tx) => {- if (disposition.kind === "resource_unavailable") {- const fence = lifecycleRuntimeFence(delivery);- const normalized = delivery.normalizedEvent as {- resource?: { providerResourceId?: unknown };- };- const providerResourceId = normalized.resource?.providerResourceId;- const current = fence- ? await runtimeCallbackEndpoint(tx, endpoint.id, fence, [- "verifying",- "active",- "attention",- ])- : null;- const resource =- current && typeof providerResourceId === "string"- ? await tx- .select({ id: chatEndpointResources.id })- .from(chatEndpointResources)- .where(- and(- eq(chatEndpointResources.companyId, current.companyId),- eq(chatEndpointResources.endpointId, current.id),- eq(- chatEndpointResources.providerResourceId,- providerResourceId,- ),- ),- )- .for("update")- .then((rows) => rows[0] ?? null)- : null;- if (resource) {- await tx- .update(chatEndpointResources)- .set({ availability: "unavailable", updatedAt: now })- .where(eq(chatEndpointResources.id, resource.id));- await tx- .update(chatConversations)- .set({ state: "unavailable", updatedAt: now })- .where(- and(- eq(chatConversations.companyId, current!.companyId),- eq(chatConversations.endpointId, current!.id),- eq(chatConversations.resourceId, resource.id),- inArray(chatConversations.state, ["active", "waiting"]),- ),- );- }- }- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- state: terminal ? "filtered" : "retry",- attempts: delivery.attempts + 1,- nextAttemptAt: terminal- ? null- : new Date(now.getTime() + retryAfterMs),- processedAt: terminal ? now : null,- redactedError: terminal- ? "Discord thread creation was not confirmed"- : redactError(error),- updatedAt: now,- })- .where(- and(- eq(chatDeliveries.id, delivery.id),- eq(chatDeliveries.state, "retry"),- sql`${chatDeliveries.normalizedEvent}->>'providerThreadPending' = 'true'`,- ),- );- });- return false;- }- }-- function normalizedDeliveryThreadId(delivery: Pick<DeliveryRow, "normalizedEvent">): string | null {- const normalized = delivery.normalizedEvent as {- conversation?: { externalThreadId?: unknown };- };- return typeof normalized.conversation?.externalThreadId === "string"- ? normalized.conversation.externalThreadId- : null;- }-- function normalizedLifecycleTargetEventId(- delivery: Pick<DeliveryRow, "eventKind" | "normalizedEvent">,- ): string | null {- if (- delivery.eventKind !== "message_updated" &&- delivery.eventKind !== "message_deleted" &&- delivery.eventKind !== "message_restored"- )- return null;- const normalized = delivery.normalizedEvent as {- message?: { targetProviderEventId?: unknown; admissionDependencyEventId?: unknown };- };- // An edit can also introduce a new addressed request. Process that durable- // admission before waiting for the old, potentially unadmitted source.- if (typeof normalized.message?.admissionDependencyEventId === "string")- return normalized.message.admissionDependencyEventId;- return typeof normalized.message?.targetProviderEventId === "string"- ? normalized.message.targetProviderEventId- : null;- }-- function normalizedLifecycleEffect(- delivery: Pick<DeliveryRow, "normalizedEvent">,- ): ChatProviderLifecycleEffect | null {- const normalized = delivery.normalizedEvent as { lifecycle?: unknown };- const value = normalized.lifecycle;- if (!value || typeof value !== "object" || Array.isArray(value))- return null;- const effect = value as Record<string, unknown>;- if (- (effect.provider !== "slack" &&- effect.provider !== "github" &&- effect.provider !== "discord" &&- effect.provider !== "microsoft-teams" &&- effect.provider !== "telegram") ||- typeof effect.providerEventId !== "string"- )- return null;- if (- effect.kind === "endpoint" &&- (effect.availability === "available" ||- effect.availability === "attention" ||- effect.availability === "revoked") &&- typeof effect.reason === "string"- )- return effect as ChatProviderLifecycleEffect;- if (- effect.kind === "resource" &&- (effect.availability === "available" ||- effect.availability === "unavailable" ||- effect.availability === "removed") &&- typeof effect.providerResourceId === "string" &&- (effect.previousProviderResourceId === undefined ||- typeof effect.previousProviderResourceId === "string") &&- typeof effect.resourceType === "string" &&- typeof effect.label === "string"- )- return effect as ChatProviderLifecycleEffect;- return null;- }-- function deliveryReady(delivery: DeliveryRow, now: Date): boolean {- // Accepted input may still own the conversation head through its wake- // outbox. The action dispatcher checks its own retry/claim deadline.- if (delivery.state === "processed") return true;- if (delivery.state === "received")- return !delivery.nextAttemptAt || delivery.nextAttemptAt <= now;- if (delivery.state === "retry") {- return !delivery.nextAttemptAt || delivery.nextAttemptAt <= now;- }- return (- delivery.state === "processing" &&- delivery.updatedAt <=- new Date(now.getTime() - DELIVERY_PROCESSING_STALE_MS)- );- }-- function conversationDeliveryOrder() {- return [- asc(- sql`coalesce(nullif(${chatDeliveries.normalizedEvent}->'message'->>'providerSentAt', '')::timestamptz, ${chatDeliveries.receivedAt})`,- ),- // GitHub timestamps and Telegram message dates have one-second- // resolution. GitHub's numeric comment id and Telegram's message_id- // are monotonic within one conversation, so use them before receipt- // order. The Telegram update_id is a final provider-native tie-breaker- // for unusual payloads that lack a usable message_id.- asc(sql`coalesce(- case- when ${chatDeliveries.normalizedEvent}->'message'->>'providerMessageSequence' ~ '^[0-9]+$'- then (${chatDeliveries.normalizedEvent}->'message'->>'providerMessageSequence')::numeric- else null- end,- case- when ${chatDeliveries.normalizedEvent}->'message'->>'providerMessageId' ~ '^[0-9]+$'- then (${chatDeliveries.normalizedEvent}->'message'->>'providerMessageId')::numeric- else null- end- )`),- asc(sql`case- when ${chatDeliveries.normalizedEvent}->'message'->>'providerUpdateId' ~ '^[0-9]+$'- then (${chatDeliveries.normalizedEvent}->'message'->>'providerUpdateId')::numeric- else null- end`),- // GitHub exposes no sortable webhook sequence. When an edit and delete- // share its whole-second updated_at value, preserve the only valid- // lifecycle state transition: update before delete. Provider-native- // update ids (Telegram) remain the stronger preceding key.- asc(sql`case ${chatDeliveries.eventKind}- when 'message_updated' then 1- when 'message_deleted' then 2- when 'message_restored' then 3- else 0- end`),- asc(chatDeliveries.receivedAt),- asc(chatDeliveries.id),- ];- }+ })+ .where(eq(chatDeliveries.id, activeDelivery.id));+ });+ return;+ }- async function earliestOpenConversationDelivery(- endpointId: string,- threadId: string,- ): Promise<DeliveryRow | null> {- const externalThreadId = sql<string>`${chatDeliveries.normalizedEvent}->'conversation'->>'externalThreadId'`;- const candidate = await db- .select()- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.endpointId, endpointId),- or(- inArray(chatDeliveries.state, ["received", "retry", "processing"]),+ const filterPreControlSource = async (database: DbOrTransaction) => {+ if (+ controlCommand === "status" ||+ (controlCommand === "new" &&+ endpoint.provider === "telegram" &&+ surfaceKind === "native_thread") ||+ guidanceCommand ||+ (await readChatControlChronology(+ database,+ endpoint,+ thread,+ activeDelivery,+ )) !== "before_or_unproven"+ )+ return false;+ const filteredAt = new Date();+ await database+ .update(chatDeliveries)+ .set({+ state: "filtered",+ nextAttemptAt: null,+ processedAt: filteredAt,+ updatedAt: filteredAt,+ redactedError:+ "Message predates or cannot be ordered after a completed chat close/new. Send a new request to start work.",+ })+ .where(and(- eq(chatDeliveries.state, "processed"),- pendingInboundWakeupCondition(),+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.companyId, endpoint.companyId),+ eq(chatDeliveries.state, "processing"),),- ),- notInArray(chatDeliveries.eventKind, [- "reaction_added",- "reaction_removed",- ]),- externalThreadIdentityCondition(externalThreadId, threadId),- ),- )- .orderBy(...conversationDeliveryOrder())- .limit(1)- .then((rows) => rows[0] ?? null);- if (!candidate) return null;-- // A lifecycle callback can reach Paperclip before its create callback. If- // the root becomes durable while the lifecycle row is waiting, always- // return that exact dependency first even when a coarse or malformed- // provider timestamp would otherwise put the edit/delete at the head.- const targetProviderEventId = normalizedLifecycleTargetEventId(candidate);- if (!targetProviderEventId) return candidate;- return db- .select()- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.endpointId, endpointId),- eq(chatDeliveries.providerEventId, targetProviderEventId),- inArray(chatDeliveries.state, ["received", "retry", "processing"]),- ),- )- .limit(1)- .then((rows) => rows[0] ?? candidate);- }-- function pendingInboundWakeupCondition(readyOnly = false): SQL {- return sql`exists (- select 1 from ${chatActions}- where ${chatActions.deliveryId} = ${chatDeliveries.id}- and ${chatActions.endpointId} = ${chatDeliveries.endpointId}- and ${chatActions.companyId} = ${chatDeliveries.companyId}- and ${chatActions.kind} = 'inbound_wakeup'- and ${chatActions.status} in ('issued', 'processing')- ${- readyOnly- ? sql`and (- (${chatActions.status} = 'issued' and (${chatActions.result}->>'retryAt' is null or (${chatActions.result}->>'retryAt')::timestamptz <= now()))- or (${chatActions.status} = 'processing' and ${chatActions.updatedAt} <= ${new Date(Date.now() - DELIVERY_PROCESSING_STALE_MS).toISOString()}::timestamptz)- )`- : sql``+ );+ return true;+ };+ if (await filterPreControlSource(db)) return;+ const photonQuote =+ endpoint.provider === "imessage-photon"+ ? photonReplyReference(message.raw)+ : null;+ if (controlCommand && photonQuote) {+ const source = await db+ .select({ conversationId: chatMessageLinks.conversationId })+ .from(chatMessageLinks)+ .where(+ and(+ eq(chatMessageLinks.companyId, endpoint.companyId),+ eq(chatMessageLinks.endpointId, endpoint.id),+ eq(chatMessageLinks.providerMessageId, photonQuote.guid),+ ),+ )+ .limit(1)+ .then((rows) => rows[0]);+ if (!source || source.conversationId !== existingConversation?.id) {+ await db.transaction(async (tx) => {+ await notifyChatDeliveryWork(tx);+ return tx+ .update(chatDeliveries)+ .set({+ state: "filtered",+ processedAt: new Date(),+ nextAttemptAt: null,+ redactedError:+ "Quoted control does not belong to the current task generation",+ updatedAt: new Date(),+ })+ .where(eq(chatDeliveries.id, activeDelivery.id));+ });+ return;}- )`;- }-- async function acquireConversationDeliveryLease(input: {- companyId: string;- endpointId: string;- threadId: string;- }): Promise<{ leaseKey: string; token: string } | null> {- const now = new Date();- const token = randomUUID();- const leaseKey = `inbound:${createHash("sha256").update(durableExternalThreadIdentity(input.threadId)).digest("hex")}`;- const expiresAt = new Date(now.getTime() + DELIVERY_LEASE_TTL_MS);- const inserted = await db- .insert(chatEndpointLeases)- .values({- companyId: input.companyId,- endpointId: input.endpointId,- leaseKey,- token,- expiresAt,- })- .onConflictDoNothing()- .returning({ id: chatEndpointLeases.id });- if (inserted.length > 0) return { leaseKey, token };- const reclaimed = await db- .update(chatEndpointLeases)- .set({ token, expiresAt, updatedAt: now })- .where(- and(- eq(chatEndpointLeases.companyId, input.companyId),- eq(chatEndpointLeases.endpointId, input.endpointId),- eq(chatEndpointLeases.leaseKey, leaseKey),- lte(chatEndpointLeases.expiresAt, now),- ),- )- .returning({ id: chatEndpointLeases.id });- return reclaimed.length > 0 ? { leaseKey, token } : null;- }+ }- async function releaseConversationDeliveryLease(input: {- endpointId: string;- leaseKey: string;- token: string;- }): Promise<void> {- await db- .delete(chatEndpointLeases)- .where(- and(- eq(chatEndpointLeases.endpointId, input.endpointId),- eq(chatEndpointLeases.leaseKey, input.leaseKey),- eq(chatEndpointLeases.token, input.token),- ),- );- }+ if (guidanceCommand) {+ const assignedAgentName =+ guidanceCommand === "start"+ ? await db+ .select({ name: agents.name })+ .from(agents)+ .where(+ and(+ eq(agents.companyId, endpoint.companyId),+ eq(agents.id, endpoint.assignedAgentId),+ ),+ )+ .then((rows) => rows[0]?.name ?? "this agent")+ : null;+ const responseText =+ guidanceCommand === "start"+ ? `Send a direct message to start work with ${assignedAgentName}. In a group, use /task@${endpoint.botUsername ?? "your_bot"} followed by your request. Use /status, /new, or /close to manage the active task in this chat.`+ : guidanceCommand === "task"+ ? `Please include a request after /task@${endpoint.botUsername ?? "your_bot"}.`+ : `Available commands: /task@${endpoint.botUsername ?? "your_bot"} followed by your request, /status, /new, and /close.`;+ const publicationBinding =+ existingConversation && existingIssue+ ? { conversation: existingConversation, issue: existingIssue }+ : null;+ let effect: typeof chatActions.$inferSelect | null = null;+ if (publicationBinding) {+ await db.transaction(async (tx) => {+ await tx+ .update(chatEndpoints)+ .set({ lastEventAt: new Date(), updatedAt: new Date() })+ .where(eq(chatEndpoints.id, endpoint.id));+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ conversationId: publicationBinding.conversation.id,+ state: "processed",+ processedAt: new Date(),+ redactedError: null,+ updatedAt: new Date(),+ })+ .where(eq(chatDeliveries.id, activeDelivery.id));+ await stageAuthorizedTaskControlPublication(tx, {+ companyId: endpoint.companyId,+ endpointId: endpoint.id,+ conversationId: publicationBinding.conversation.id,+ issueId: publicationBinding.issue.id,+ idempotencyKey: `control:guidance:${activeDelivery.id}`,+ payload: projectSafeChatPublication({+ classification: "external",+ source: "task_control",+ text: responseText,+ }),+ principalId: principalResolution.principal.id,+ });+ });+ } else {+ const effectContext =+ runtimeContext ??+ runtimeContextForRecord(+ (await endpointRecord(endpoint.id)) ??+ (() => {+ throw new Error("Chat endpoint is unavailable");+ })(),+ );+ effect = await db.transaction((tx) =>+ stageProviderEffect(tx, {+ endpoint,+ deliveryId: activeDelivery.id,+ principalId: principalResolution.principal.id,+ providerActionId: `provider_effect:delivery:${activeDelivery.id}`,+ payload: {+ version: 1,+ effect: "thread_message",+ threadId: thread.id,+ text: responseText,+ settleDelivery: true,+ resourceId: resource.id,+ },+ runtimeContext: effectContext,+ }),+ );+ if (!effect) throw new Error("Provider effect was not persisted");+ if ((await processProviderEffect(effect.id, thread)) !== "processed")+ return;+ }+ // Telegram's command reply is the acknowledgement. A control-only+ // request starts no run that could later retire a processing receipt.+ await Promise.allSettled([+ receiptReactionSupported && endpoint.provider !== "telegram"+ ? addReceiptReaction({+ deliveryId: activeDelivery.id,+ endpoint,+ message,+ runtimeContext,+ thread,+ })+ : Promise.resolve(),+ addressed && !thread.isDM ? thread.subscribe() : Promise.resolve(),+ ]);+ return;+ }- function messageFromDelivery(- delivery: DeliveryRow,- thread: Thread,- endpointRuntime: ChatEndpointRuntime,- ): {- message: Message;- receiptReactionSupported: boolean;- suppressSetupDestinationActivation: boolean;- trigger: ChatSdkMessageCallbackEvent["trigger"];- providerUrl: string | null;- } | null {- if (telegramDeliveryHasZeroMessageId(delivery, endpointRuntime.provider))- return null;- const normalized = delivery.normalizedEvent as {- acknowledgement?: { receiptReactionSupported?: unknown };- kind?: unknown;- trigger?: unknown;- principal?: {- externalId?: unknown;- displayName?: unknown;- handle?: unknown;- };- message?: {- providerMessageId?: unknown;- sourceProviderMessageId?: unknown;- text?: unknown;- mentionedBot?: unknown;- attachments?: Array<{- name?: unknown;- mimeType?: unknown;- size?: unknown;- recovery?: unknown;- }>;- attachmentLimitOmissions?: unknown;- photonReply?: { guid?: unknown; part?: unknown };- };- conversation?: { providerUrl?: unknown };- };- const providerMessageId = normalized.message?.providerMessageId;- const externalId = normalized.principal?.externalId;- if (typeof providerMessageId !== "string" || typeof externalId !== "string")- return null;- const isTeams = endpointRuntime.provider === "microsoft-teams";- const referenceOnlyTeamsAttachments = isTeams && !thread.isDM;- const originFence = lifecycleRuntimeFence(delivery);- const storedAttachments = normalized.message?.attachments ?? [];- const attachments = (- isTeams ? storedAttachments.slice(0, 20) : storedAttachments- )- .map((attachment) => {- if (!attachment || typeof attachment !== "object") return null;- const rehydrated =- attachment.recovery &&- (!referenceOnlyTeamsAttachments ||- (typeof attachment.recovery === "object" &&- attachment.recovery !== null &&- "locator" in attachment.recovery &&- typeof attachment.recovery.locator === "object" &&- attachment.recovery.locator !== null &&- "kind" in attachment.recovery.locator &&- attachment.recovery.locator.kind === "teams_inline_image"))- ? endpointRuntime.rehydrateAttachment(attachment.recovery, {+ if (controlCommand) {+ const isTelegramForumTopic =+ endpoint.provider === "telegram" && surfaceKind === "native_thread";+ const taskLabel = existingIssue+ ? `${existingIssue.identifier}: ${existingIssue.title}`+ : "No task is active in this conversation.";+ const responseText =+ controlCommand === "status"+ ? existingIssue+ ? `${taskLabel} — ${existingIssue.status}`+ : taskLabel+ : controlCommand === "new"+ ? isTelegramForumTopic+ ? existingIssue+ ? `${taskLabel} stays bound to this forum topic. Open a new Telegram forum topic to start a new Paperclip task.`+ : "Open a new Telegram forum topic to start a new Paperclip task."+ : "Send your request to start a new Paperclip task."+ : existingConversation+ ? isTelegramForumTopic+ ? "This chat conversation is closed. A later message here will continue the same Paperclip task."+ : "This chat conversation is closed. Send another message to start a new task."+ : "No task is active. Send a message to start one.";+ const publicationBinding =+ existingConversation && existingIssue+ ? { conversation: existingConversation, issue: existingIssue }+ : null;+ if (publicationBinding) {+ const publicationControl =+ controlCommand === "new" && isTelegramForumTopic+ ? "new_guidance"+ : controlCommand;+ const staged = await db.transaction(async (tx) => {+ await tx+ .update(chatEndpoints)+ .set({ lastEventAt: new Date(), updatedAt: new Date() })+ .where(eq(chatEndpoints.id, endpoint.id));+ if (await filterPreControlSource(tx)) return false;+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ conversationId: publicationBinding.conversation.id,+ state: "processed",+ processedAt: new Date(),+ updatedAt: new Date(),+ })+ .where(eq(chatDeliveries.id, activeDelivery.id));+ await stageAuthorizedTaskControlPublication(tx, {+ companyId: endpoint.companyId,+ endpointId: endpoint.id,+ conversationId: publicationBinding.conversation.id,+ issueId: publicationBinding.issue.id,+ idempotencyKey: `control:${publicationControl}:${activeDelivery.id}`,+ payload: projectSafeChatPublication({+ classification: "external",+ source: "task_control",+ text: responseText,+ }),+ principalId: principalResolution.principal.id,+ });+ return true;+ });+ if (!staged) return;+ } else {+ const effectContext =+ runtimeContext ??+ runtimeContextForRecord(+ (await endpointRecord(endpoint.id)) ??+ (() => {+ throw new Error("Chat endpoint is unavailable");+ })(),+ );+ const effect = await db.transaction(async (tx) => {+ return stageProviderEffect(tx, {+ endpoint,+ deliveryId: activeDelivery.id,+ principalId: principalResolution.principal.id,+ providerActionId: `provider_effect:delivery:${activeDelivery.id}`,+ payload: {+ version: 1,+ effect: "thread_message",threadId: thread.id,- messageId: typeof normalized.message?.sourceProviderMessageId === "string" ? normalized.message.sourceProviderMessageId : providerMessageId,- runtimeGeneration: originFence?.generation,- credentialFingerprint: originFence?.credentialFingerprint,- principalExternalId: externalId,+ text: responseText,+ settleDelivery: true,+ resourceId: resource.id,+ },+ runtimeContext: effectContext,+ });+ });+ if (!effect) throw new Error("Provider effect was not persisted");+ if ((await processProviderEffect(effect.id, thread)) !== "processed")+ return;+ }+ // This command stages a reply, not new agent work to acknowledge.+ await Promise.allSettled([+ receiptReactionSupported && endpoint.provider !== "telegram"+ ? addReceiptReaction({+ deliveryId: activeDelivery.id,+ endpoint,+ message,+ runtimeContext,+ thread,+ })+ : Promise.resolve(),+ addressed && !thread.isDM ? thread.subscribe() : Promise.resolve(),+ ]);+ return;+ }++ const inboundActivityPublications: ActivityPublication[] = [];+ const persistTaskMutation = async (+ taskTx: DbOrTransaction,+ taskEndpoint: EndpointRow,+ taskUserId: string | null,+ ) => {+ let conversation = existingConversation;+ if (!conversation) {+ const sessionGeneration = isLinear+ ? (latestConversation?.sessionGeneration ?? 0) + 1+ : 1;+ const issue = await issuesSvc.create(+ endpoint.companyId,+ {+ title: safeTitle(+ githubAutomatic+ ? `PR #${githubAutomatic.context.pullNumber}: ${githubAutomatic.context.title}`+ : githubIssue ? `GitHub issue #${githubIssue.context.issueNumber}: ${githubIssue.context.title}` : message.text,+ `${PROVIDER_LABELS[endpoint.provider]} conversation`,+ ),+ description: `Started from ${PROVIDER_LABELS[endpoint.provider]}: ${resource.label}`,+ status: "todo",+ priority: "medium",+ assigneeAgentId: endpoint.assignedAgentId,+ createdByUserId: taskUserId ?? endpoint.sponsorUserId,+ responsibleUserId: taskUserId ?? endpoint.sponsorUserId,+ originKind: "chat_channel",+ originId: `${endpoint.id}:${thread.id}:${sessionGeneration}`,+ idempotencyKey: `chat:${endpoint.id}:${thread.id}:${sessionGeneration}`,+ },+ taskTx,+ );+ await taskTx+ .insert(chatConversations)+ .values({+ companyId: endpoint.companyId,+ endpointId: endpoint.id,+ resourceId: resource.id,+ issueId: issue.id,+ externalConversationId: thread.channelId,+ externalThreadId: thread.id,+ sessionGeneration,+ externalLabel: resource.label,+ providerUrl,+ isDirectMessage: thread.isDM,+ communicationGuidance: buildChatCommunicationGuidance({+ provider: taskEndpoint.provider,isDirectMessage: thread.isDM,+ communicationInstructions: taskEndpoint.communicationInstructions,+ }),+ state: "active",+ lastActivityAt: new Date(),+ })+ .onConflictDoNothing();+ conversation = await taskTx+ .select()+ .from(chatConversations)+ .where(+ and(+ eq(chatConversations.endpointId, endpoint.id),+ eq(chatConversations.externalConversationId, thread.channelId),+ eq(chatConversations.externalThreadId, thread.id),+ eq(chatConversations.sessionGeneration, sessionGeneration),+ ),+ )+ .then((rows) => rows[0] ?? null);+ }+ if (!conversation)+ throw conflict(+ "Could not bind external conversation to a Paperclip task",+ );++ const issue =+ existingIssue?.id === conversation.issueId+ ? existingIssue+ : await taskTx+ .select()+ .from(issues)+ .where(eq(issues.id, conversation.issueId))+ .then((rows) => rows[0] ?? null);+ if (!issue) throw notFound("Bound task not found");+ const [assignedAgentTrust] = taskEndpoint.provider === "github" ? await taskTx.select({ permissions: agents.permissions }).from(agents).where(and(eq(agents.companyId, taskEndpoint.companyId), eq(agents.id, taskEndpoint.assignedAgentId))) : [];+ if (!taskUserId || ((githubAutomatic || githubIssue) && !principalResolution.userId) || assignedAgentTrust?.permissions?.trustPreset === LOW_TRUST_REVIEW_PRESET) {+ const reviewPreset = {+ id: LOW_TRUST_REVIEW_PRESET,+ version: LOW_TRUST_REVIEW_PRESET_VERSION,+ rawOutputDisposition: LOW_TRUST_REVIEW_RAW_OUTPUT_DISPOSITION,+ } as const;+ await taskTx+ .update(issues)+ .set({+ sourceTrust: {+ preset: LOW_TRUST_REVIEW_PRESET,+ disposition: "quarantined",+ sourceIssueId: issue.id,+ },+ executionPolicy: {+ mode: "normal",+ commentRequired: true,+ stages: [],+ ...issue.executionPolicy,+ reviewPreset,+ authorizationPolicy: {+ ...githubPolicyRecord(issue.executionPolicy?.authorizationPolicy),+ trustPreset: LOW_TRUST_REVIEW_PRESET,+ reviewPreset,+ trustBoundary: {+ mode: LOW_TRUST_REVIEW_PRESET,+ companyId: endpoint.companyId,+ rootIssueId: issue.id,+ issueIds: [issue.id],+ allowedAgentIds: [endpoint.assignedAgentId],+ allowedToolClasses: [+ "git.read",+ "github.pr.read",+ "tests.local",+ ],+ ...githubPolicyRecord(githubPolicyRecord(issue.executionPolicy?.authorizationPolicy)?.trustBoundary),+ },+ },+ },+ updatedAt: new Date(),})- : null;- if (rehydrated) return rehydrated;- if (- isTeams ||- endpointRuntime.provider === "imessage-photon" ||- (endpointRuntime.provider === "telegram" &&- typeof attachment.recovery === "object" &&- attachment.recovery !== null &&- "locator" in attachment.recovery &&- typeof attachment.recovery.locator === "object" &&- attachment.recovery.locator !== null &&- "kind" in attachment.recovery.locator &&- attachment.recovery.locator.kind === "telegram_media")- ) {- // Non-personal references and personal files whose safe download- // capability did not survive restart still belong to this input.- // Keep bounded metadata so ingestion records an explicit omission;- // never persist bearer URLs or fabricate a download capability.- // Even a legacy URL locator cannot enable non-personal downloads.- // A Telegram media locator which fails its exact source proof also- // remains an unavailable input, never an empty attachment-free turn.- return {- type: "file",- name:- sanitizeFilename(- typeof attachment.name === "string"- ? attachment.name- : undefined,- ) ?? undefined,- mimeType: normalizeContentType(- typeof attachment.mimeType === "string"- ? attachment.mimeType- : undefined,- ).slice(0, 255),- size:- typeof attachment.size === "number" &&- Number.isSafeInteger(attachment.size) &&- attachment.size >= 0- ? attachment.size- : undefined,- } as Attachment;+ .where(+ and(+ eq(issues.id, issue.id),+ eq(issues.companyId, endpoint.companyId),+ ),+ );+ }++ if (issue.status === "done" || issue.status === "cancelled") {+ await issuesSvc.update(+ issue.id,+ {+ status: "todo",+ actorUserId: taskUserId ?? taskEndpoint.sponsorUserId,+ },+ taskTx,+ );+ }+ const body =+ (githubManual ? githubManualMessagePrompt({+ event: githubManual.event,+ policy: githubManual.policy,+ repository: resource.providerResourceId,+ thread: thread.id,+ sender: { id: principalResolution.principal.externalId, login: principalResolution.principal.handle },+ message: message.text,+ }) : message.text.trim()) ||+ (message.attachments.length > 0+ ? taskEndpoint.provider === "microsoft-teams" &&+ !thread.isDM &&+ nativeInboundAttachments.length === 0+ ? `Shared ${message.attachments.length} Microsoft Teams file reference${message.attachments.length === 1 ? "" : "s"}.${providerUrl ? ` Open in Microsoft Teams: ${providerUrl}` : ""}`+ : `Shared ${message.attachments.length} file${message.attachments.length === 1 ? "" : "s"}.`+ : taskEndpoint.provider === "slack" && (trigger === "mention" || message.isMention === true)+ ? "Started a conversation by mentioning the agent."+ : "Sent an empty message.");+ let comment!: Awaited<ReturnType<typeof issuesSvc.addComment>>;+ await taskTx+ .update(chatEndpoints)+ .set({+ status: taskEndpoint.status,+ setup: taskEndpoint.setup,+ healthMessage:+ taskEndpoint.status === "verifying"+ ? "Test conversation received"+ : "Connected",+ lastEventAt: new Date(),+ activatedAt:+ taskEndpoint.status === "active"+ ? taskEndpoint.activatedAt+ : null,+ updatedAt: new Date(),+ })+ .where(eq(chatEndpoints.id, taskEndpoint.id));+ comment = await issuesSvc.addComment(+ conversation!.issueId,+ body.slice(0, MAX_INBOUND_TEXT),+ taskUserId ? { userId: taskUserId } : {},+ {+ authorType: taskUserId ? "user" : "system",+ metadata: {+ version: 1,+ ...(endpoint.provider === "imessage-photon"+ ? { sourceChannel: "imessage-photon" as const }+ : {}),+ sections: [+ {+ title: `${PROVIDER_LABELS[endpoint.provider]} sender`,+ rows: [+ ...(endpoint.provider === "imessage-photon" &&+ photonReplyReference(message.raw)+ ? [+ {+ type: "key_value" as const,+ label: "Reply to message",+ value: photonReplyReference(message.raw)!.guid,+ },+ ...(photonReplyReference(message.raw)!.part+ ? [+ {+ type: "key_value" as const,+ label: "Reply part",+ value: photonReplyReference(message.raw)!+ .part!,+ },+ ]+ : []),+ ]+ : []),+ {+ type: "key_value",+ label: "Name",+ value: message.author.fullName || message.author.userName,+ },+ {+ type: "key_value",+ label: "Provider ID",+ value: stableExternalPrincipalId(+ endpoint.provider,+ message.author,+ message.raw,+ ),+ },+ {+ type: "key_value",+ label: "Authority",+ value: taskUserId+ ? "Linked Paperclip user"+ : "Sponsored external guest (restricted)",+ },+ ],+ },+ ],+ },+ sourceTrust: taskUserId+ ? null+ : {+ preset: LOW_TRUST_REVIEW_PRESET,+ disposition: "quarantined",+ sourceIssueId: conversation!.issueId,+ },+ },+ taskTx,+ );+ await taskTx+ .update(chatDeliveries)+ .set({+ conversationId: conversation!.id,+ updatedAt: new Date(),+ })+ .where(eq(chatDeliveries.id, activeDelivery.id));+ await taskTx+ .insert(chatMessageLinks)+ .values({+ companyId: endpoint.companyId,+ endpointId: endpoint.id,+ conversationId: conversation!.id,+ deliveryId: activeDelivery.id,+ commentId: comment.id,+ providerMessageId: message.id,+ direction: "inbound",+ })+ .onConflictDoNothing();+ if (taskEndpoint.provider === "slack" || taskEndpoint.provider === "speko") {+ await resumeExternalConversation(taskTx as unknown as Db, endpoint.companyId, conversation.issueId);}- return null;- })- .filter((attachment): attachment is Attachment => Boolean(attachment));- const message = {- id: providerMessageId,- threadId: thread.id,- text:- typeof normalized.message?.text === "string"- ? normalized.message.text- : "",- formatted: { type: "root", children: [] },- raw:- endpointRuntime.provider === "imessage-photon" &&- typeof normalized.message?.photonReply?.guid === "string"- ? {- replyTargetGuid: normalized.message.photonReply.guid,- threadOriginatorPart: normalized.message.photonReply.part,- }- : endpointRuntime.provider === "github" && typeof normalized.message?.sourceProviderMessageId === "string"- ? { githubSourceMessageId: normalized.message.sourceProviderMessageId } : {},- author: {- userId: externalId,- userName:- typeof normalized.principal?.handle === "string"- ? normalized.principal.handle- : externalId,- fullName:- typeof normalized.principal?.displayName === "string"- ? normalized.principal.displayName- : externalId,- isBot: false,- isMe: false,- isSystem: false,- },- metadata: { dateSent: delivery.receivedAt, edited: false },- attachments,- links: [],- isMention: normalized.message?.mentionedBot === true,- } as unknown as Message;- const githubManual = delivery.normalizedEvent.githubManual;- if (endpointRuntime.provider === "github" && githubManual && typeof githubManual === "object") githubManualMessages.set(message, githubManual as { policy: GitHubReviewPolicy; revision: number; event: "mention" | "comment" });- const githubAutomatic = delivery.normalizedEvent.githubAutomatic;- if (endpointRuntime.provider === "github" && githubAutomatic && typeof githubAutomatic === "object") {- githubAutomaticMessages.set(message, githubAutomatic as { context: GitHubReviewEventContext; revision: number; policy: GitHubReviewPolicy });- }- const githubIssue = delivery.normalizedEvent.githubIssue;- if (endpointRuntime.provider === "github" && githubIssue && typeof githubIssue === "object") {- githubIssueMessages.set(message, githubIssue as { context: GitHubIssueEventContext; revision: number; policy: GitHubReviewPolicy });- }- if (- endpointRuntime.provider === "github" ||- endpointRuntime.provider === "imessage-photon"- ) {- restoreGitHubAttachmentLimitOmissions(- message,- normalized.message?.attachmentLimitOmissions,- );- }- const normalizedTrigger = normalized.trigger;- const trigger: ChatSdkMessageCallbackEvent["trigger"] =- normalizedTrigger === "direct_message" ||- normalizedTrigger === "mention" ||- normalizedTrigger === "subscribed_message" ||- normalizedTrigger === "unaddressed_message"- ? normalizedTrigger- : normalized.kind === "direct_message"- ? "direct_message"- : normalized.kind === "mention"- ? "mention"- : "subscribed_message";- return {- message,- // Legacy deliveries all originated from native provider messages and- // therefore retain the historical default.- receiptReactionSupported:- normalized.acknowledgement?.receiptReactionSupported !== false,- suppressSetupDestinationActivation: setupDestinationActivationSuppressed(- delivery.normalizedEvent,- ),- trigger,- providerUrl:- typeof normalized.conversation?.providerUrl === "string"- ? normalized.conversation.providerUrl- : null,- };- }-- /**- * Drain one external conversation in durable receipt order. The database- * lease is endpoint + thread scoped, so separate server processes can work- * on different conversations concurrently but can never mutate the same- * Paperclip task from two inbound turns at once.- */- async function drainConversationDeliveries(- endpointId: string,- threadId: string,- ): Promise<boolean> {- const endpoint = await db- .select()- .from(chatEndpoints)- .where(eq(chatEndpoints.id, endpointId))- .then((rows) => rows[0] ?? null);- if (!endpoint) return false;- if (endpoint.status === "paused" || endpoint.status === "attention")- return false;-- const lease = await acquireConversationDeliveryLease({- companyId: endpoint.companyId,- endpointId,- threadId,- });- if (!lease) return false;-- let leaseOwned = true;- let renewal: Promise<void> | null = null;- const renewTimer = setInterval(- () => {- if (!leaseOwned || renewal) return;- const expiresAt = new Date(Date.now() + DELIVERY_LEASE_TTL_MS);- renewal = Promise.resolve()- .then(async () => {- const renewed = options.renewConversationDeliveryLease- ? await options.renewConversationDeliveryLease({- endpointId,- leaseKey: lease.leaseKey,- token: lease.token,- expiresAt,- })- : await db- .update(chatEndpointLeases)- .set({ expiresAt, updatedAt: new Date() })- .where(- and(- eq(chatEndpointLeases.endpointId, endpointId),- eq(chatEndpointLeases.leaseKey, lease.leaseKey),- eq(chatEndpointLeases.token, lease.token),- ),- )- .returning({ id: chatEndpointLeases.id })- .then((rows) => rows.length > 0);- if (!renewed) leaseOwned = false;+ await taskTx+ .update(chatConversations)+ .set({+ state: "active",+ lastActivityAt: new Date(),+ ...(providerUrl ? { providerUrl } : {}),+ updatedAt: new Date(),})- .catch((error) => {- // A failed renewal has unknown durability. Stop this local drain at- // the next delivery boundary so another worker can never overlap- // later turns after the original lease expires or is reclaimed.- leaseOwned = false;- logger.warn(- { endpointId, error: redactError(error) },- "could not renew external chat conversation lease",- );+ .where(eq(chatConversations.id, conversation!.id));+ await taskTx+ .update(toolConnections)+ .set({+ status: "active",+ enabled: true,+ healthStatus: "healthy",+ healthMessage: "Connected",+ lastHealthAt: new Date(),+ updatedAt: new Date(),})- .finally(() => {- renewal = null;- });- },- options.conversationLeaseRenewalIntervalMs ?? DELIVERY_LEASE_TTL_MS / 3,- );- renewTimer.unref?.();-- try {- for (- let processed = 0;- processed < DELIVERY_DRAIN_LIMIT;- processed += 1- ) {- if (!leaseOwned) break;- const delivery = await earliestOpenConversationDelivery(- endpointId,- threadId,- );- if (!delivery || !deliveryReady(delivery, new Date())) break;- if (delivery.state === "processed") {- if (!(await processInboundWakeup(delivery.id))) break;- continue;+ .where(eq(toolConnections.id, taskEndpoint.connectionId));+ if (endpoint.provider === "github") {+ const guest = !principalResolution.userId;+ await taskTx.update(chatDeliveries).set({ normalizedEvent: sql`${chatDeliveries.normalizedEvent} || ${JSON.stringify({ githubAuthority: { guest, responsibleUserId: taskUserId, sponsorUserId: guest ? taskEndpoint.sponsorUserId : null } })}::jsonb` }).where(eq(chatDeliveries.id, activeDelivery.id));}- if (telegramDeliveryHasZeroMessageId(delivery, endpoint.provider)) {- const filtered = await db- .transaction(async (tx) => {- // Do not round-trip a PostgreSQL microsecond timestamp through- // JS Date for a CAS. Lock the exact receipt, then revalidate the- // current source and claim before changing it. A competing live- // claim is a retry boundary, not permission to settle its work.- const [current] = await tx- .select()- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.id, delivery.id),- eq(chatDeliveries.companyId, endpoint.companyId),- eq(chatDeliveries.endpointId, endpoint.id),- ),- )- .for("update", { noWait: true });- const filteredAt = new Date();- if (- !current ||- current.state !== delivery.state ||- current.eventKind !== delivery.eventKind ||- !["received", "retry", "processing"].includes(current.state) ||- normalizedDeliveryThreadId(current) !== threadId ||- !deliveryReady(current, filteredAt) ||- !telegramDeliveryHasZeroMessageId(current, endpoint.provider)- )- return false;- await notifyChatDeliveryWork(tx);- const changed = await tx- .update(chatDeliveries)- .set({- state: "filtered",- nextAttemptAt: null,- processedAt: filteredAt,- updatedAt: filteredAt,- redactedError:- "Telegram message ID zero cannot authorize ordinary work",- })- .where(eq(chatDeliveries.id, current.id))- .returning({ id: chatDeliveries.id });- return changed.length === 1;- })- .catch((error: unknown) => {- if (isExternalChatWaitAuthorizationContention(error))- return false;- throw error;- });- if (!filtered) break;- // Retain original evidence/comments; filtering adds no user content- // and cannot hydrate attachments, invoke commands, or send feedback.- await settleRejectedInboundWakeups(delivery.id);- liveInboundMessages.delete(delivery.id);- continue;+ if (githubAutomatic) {+ await taskTx.insert(chatGitHubReviews).values({+ companyId: endpoint.companyId, endpointId: endpoint.id, issueId: issue.id,+ repositoryId: githubAutomatic.context.repositoryId, repository: githubAutomatic.context.repository,+ pullNumber: githubAutomatic.context.pullNumber, headSha: githubAutomatic.context.headSha,+ deliveryId: activeDelivery.id, configurationRevision: githubAutomatic.revision,+ policySnapshot: githubAutomatic.policy, event: githubAutomatic.context, state: "queued",+ }).onConflictDoNothing();}- if (endpoint.status === "archived" || endpoint.status === "revoked") {- await db.transaction(async (tx) => {- await notifyChatDeliveryWork(tx);- return tx- .update(chatDeliveries)- .set({- state: "filtered",- redactedError: "Connection was removed before processing",- processedAt: new Date(),- updatedAt: new Date(),- })- .where(eq(chatDeliveries.id, delivery.id));- });- liveInboundMessages.delete(delivery.id);- continue;+ await stageInboundWakeup(taskTx, {+ endpoint: taskEndpoint,+ deliveryId: activeDelivery.id,+ conversation,+ commentId: comment.id,+ principalId: principalResolution.principal.id,+ actorUserId: taskUserId,+ });+ if (taskEndpoint.provider === "imessage-photon") {+ await logActivity(+ taskTx as Db,+ {+ companyId: taskEndpoint.companyId,+ actorType: taskUserId ? "user" : "system",+ actorId: taskUserId ?? "chat:imessage-photon",+ action: "issue.comment_added",+ entityType: "issue",+ entityId: issue.id,+ details: {+ commentId: comment.id,+ issueIdentifier: issue.identifier,+ source: "chat:imessage-photon",+ endpointId: taskEndpoint.id,+ },+ },+ inboundActivityPublications,+ );}-+ return { actorUserId: taskUserId, comment, conversation, issue };+ };+ const taskMutation = await db.transaction(async (tx) => {+ // Admission and durable task mutation are separate so the provider+ // webhook can return inside its response budget. Take the endpoint and+ // destination locks again at the authoritative mutation boundary for+ // every provider: either a reach revocation commits first and this+ // event is redacted, or this task/comment commits first and the+ // revocation waits. There is no stale-snapshot middle.+ await options.reachAuthorizationBarrier?.();+ const currentEndpoint = await tx+ .select()+ .from(chatEndpoints)+ .where(eq(chatEndpoints.id, endpoint.id))+ .for("update")+ .then((rows) => rows[0] ?? null);+ if (!currentEndpoint) throw notFound("Chat endpoint not found");+ const currentResource = thread.isDM+ ? resource+ : await tx+ .select()+ .from(chatEndpointResources)+ .where(+ and(+ eq(chatEndpointResources.id, resource.id),+ eq(chatEndpointResources.endpointId, endpoint.id),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ const currentPrincipalAuthorization =+ await lockCurrentPrincipalAuthorization(+ tx,+ currentEndpoint,+ principalResolution.principal.id,+ );+ const automaticContext = githubAutomatic?.context ?? githubIssue?.context;+ const automaticAdmission = automaticContext ? await githubAutomaticAdmission(tx, currentEndpoint, automaticContext) : null;+ if (automaticContext && !automaticAdmission?.allowed) currentPrincipalAuthorization.allowed = false;+ if (automaticAdmission?.allowed) currentPrincipalAuthorization.userId = automaticAdmission.responsibleUserId ?? null;+ const endpointStillAllowed =+ currentEndpoint.status === "verifying" ||+ currentEndpoint.status === "active";+ const destinationStillAllowed = thread.isDM+ ? currentEndpoint.allowDirectMessages+ : nonDirectDestinationAllowed(currentEndpoint, currentResource);+ const mentionStillAllowed =+ currentEndpoint.provider !== "slack" ||+ !currentEndpoint.requireAtMention ||+ trigger === "mention" ||+ message.isMention === true;if (- endpoint.provider === "discord" &&- discordRootThreadPending(delivery)+ !endpointStillAllowed ||+ !mentionStillAllowed ||+ !destinationStillAllowed ||+ !currentPrincipalAuthorization.allowed) {- // This is the only recovery path for the narrow crash window after- // pre-admission but before Chat's ordinary callback. A successful- // read proves the root thread exists; an explicit 404/410 proves it- // does not. Ambiguous transport and auth failures remain retryable.- if (await reconcileDiscordRootThread(endpoint, delivery, threadId)) {- continue;- }- break;- }-- const live = liveInboundMessages.get(delivery.id);- try {- if (- delivery.eventKind === "message_updated" ||- delivery.eventKind === "message_deleted" ||- delivery.eventKind === "message_restored"- ) {- await processLifecycleDelivery(endpoint, delivery);- } else if (live) {- await processMessage(- endpoint,- live.thread,- live.message,- live.trigger,- false,- live.providerUrl,- live.runtimeContext,- undefined,- delivery.id,- live.receiptReactionSupported,- undefined,- false,- setupDestinationActivationSuppressed(delivery.normalizedEvent),- );- } else {- if (deliveryContentWasRedacted(delivery.normalizedEvent)) {- const filteredAt = new Date();- await db.transaction(async (tx) => {- await notifyChatDeliveryWork(tx);- return tx- .update(chatDeliveries)- .set({- state: "filtered",- principalId: null,- nextAttemptAt: null,- processedAt: filteredAt,- redactedError:- "Provisional Teams setup reply could not be hydrated from a current provider event",- updatedAt: filteredAt,- })- .where(- and(- eq(chatDeliveries.id, delivery.id),- inArray(chatDeliveries.state, [- "received",- "retry",- "processing",- ]),- ),- );- });- continue;- }- const endpointRuntime = await runtimeFor(endpoint);- const deliveryRuntimeFence = lifecycleRuntimeFence(delivery);- const currentRuntimeContext = runtimeContexts.get(- endpointRuntime as object,- );- const thread = endpointRuntime.thread(threadId);- const reconstructed = messageFromDelivery(- delivery,- thread,- endpointRuntime,+ const filteredAt = new Date();+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ state: "filtered",+ normalizedEvent: redactedDestinationNormalized,+ principalId: null,+ nextAttemptAt: null,+ processedAt: filteredAt,+ redactedError: !mentionStillAllowed+ ? "Message did not @mention the bot"+ : endpointStillAllowed+ ? destinationStillAllowed+ ? currentPrincipalAuthorization.linkedDenied+ ? "Linked Paperclip account is not currently permitted"+ : currentEndpoint.allowUnlinkedPeople+ ? "Endpoint sponsor can no longer authorize external guests"+ : "External identity must be linked to a Paperclip account"+ : "Destination is not enabled in Paperclip"+ : "Connection is not active",+ updatedAt: filteredAt,+ })+ .where(+ and(+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.state, "processing"),+ ),);- if (!reconstructed) {- await db.transaction(async (tx) => {- await notifyChatDeliveryWork(tx);- return tx- .update(chatDeliveries)- .set({- state: "failed",- redactedError: "Normalized delivery is incomplete",- updatedAt: new Date(),- })- .where(eq(chatDeliveries.id, delivery.id));- });- continue;- }- await processMessage(- endpoint,- thread,- reconstructed.message,- reconstructed.trigger,- false,- reconstructed.providerUrl,- deliveryRuntimeFence- ? {- ...deliveryRuntimeFence,- endpointRuntime,- }- : currentRuntimeContext,- undefined,- delivery.id,- reconstructed.receiptReactionSupported,- undefined,- false,- reconstructed.suppressSetupDestinationActivation,+ // A principal first observed only by this now-revoked event must not+ // survive as a side-channel. Preserve established or linked+ // identities referenced by any other durable record.+ await tx+ .delete(chatExternalPrincipals)+ .where(+ and(+ eq(chatExternalPrincipals.id, principalResolution.principal.id),+ notExists(+ tx+ .select({ id: chatDeliveries.id })+ .from(chatDeliveries)+ .where(+ eq(+ chatDeliveries.principalId,+ principalResolution.principal.id,+ ),+ ),+ ),+ notExists(+ tx+ .select({ id: chatIdentityLinks.id })+ .from(chatIdentityLinks)+ .where(+ eq(+ chatIdentityLinks.principalId,+ principalResolution.principal.id,+ ),+ ),+ ),+ notExists(+ tx+ .select({ id: chatActions.id })+ .from(chatActions)+ .where(+ eq(+ chatActions.principalId,+ principalResolution.principal.id,+ ),+ ),+ ),+ ),);- }- } catch (error) {- logger.warn(- {- endpointId,- deliveryId: delivery.id,- error: redactError(error),- },- "external chat delivery will retry in receipt order",- );- }-- const state = await db- .select({ state: chatDeliveries.state })- .from(chatDeliveries)- .where(eq(chatDeliveries.id, delivery.id))- .then((rows) => rows[0]?.state ?? null);- if (- state === "processed" ||- state === "filtered" ||- state === "failed"- ) {- if (state !== "processed")- await settleRejectedInboundWakeups(delivery.id);- liveInboundMessages.delete(delivery.id);- continue;+ return null;}- // A retry delay or another still-live processing claim is a strict- // head-of-line barrier; later replies may not overtake it.- break;+ // Close completion takes this endpoint lock in its receipt transaction.+ // Recheck after the lock: an old input held between precheck and task+ // mutation must not create work after that control commits.+ if (await filterPreControlSource(tx)) return null;+ return persistTaskMutation(+ tx,+ currentPrincipalAuthorization.sponsorUserId ? { ...currentEndpoint, sponsorUserId: currentPrincipalAuthorization.sponsorUserId } : currentEndpoint,+ currentPrincipalAuthorization.userId,+ );+ });+ if (!taskMutation) return;+ // The open task can fetch the comment immediately, before attachments+ // finish preparing or the agent starts. Never publish an uncommitted row.+ for (const publication of inboundActivityPublications) {+ publishActivity(publication);}- } finally {- clearInterval(renewTimer);- await renewal;- await releaseConversationDeliveryLease({ endpointId, ...lease });+ const { actorUserId, comment, conversation, issue } = taskMutation;+ const attachmentResult = await ingestAttachments({+ endpoint,+ endpointRuntime,+ deliveryId: activeDelivery.id,+ issueId: conversation.issueId,+ issueCommentId: comment.id,+ attachments: nativeInboundAttachments,+ attachmentLimitOmissions: githubAttachmentLimitOmissions(message),+ unavailableReferenceCount: unavailableTeamsReferences,+ actorUserId,+ });+ if (+ await settleTelegramAttachmentOnlyFailure({+ activeDelivery,+ attachmentResult,+ commentId: comment.id,+ conversationId: conversation.id,+ endpoint,+ message,+ principalId: principalResolution.principal.id,+ resourceId: resource.id,+ runtimeContext,+ thread,+ })+ ) {+ return;+ }+ // Do not discard a subscription failure after marking the delivery+ // processed. A retry reuses the committed message link above and tries+ // this idempotent subscription again before completing the delivery.+ if (addressed && !thread.isDM) await thread.subscribe();+ await acceptInboundWakeup(activeDelivery.id, attachmentResult);+ if (!(await processInboundWakeup(activeDelivery.id))) return;+ const acceptedWake = await db+ .select({ status: chatActions.status })+ .from(chatActions)+ .where(+ and(+ eq(chatActions.deliveryId, activeDelivery.id),+ eq(chatActions.kind, "inbound_wakeup"),+ ),+ )+ .limit(1)+ .then((rows) => rows[0] ?? null);+ if (acceptedWake?.status !== "processed") return;+ // Provider-visible acknowledgement begins only after the task, external+ // comment, durable wakeup request, delivery state, and message link commit.+ await Promise.allSettled([+ receiptReactionSupported+ ? addReceiptReaction({+ deliveryId: activeDelivery.id,+ endpoint,+ message,+ runtimeContext,+ thread,+ })+ : Promise.resolve(),+ // Slack implements this through assistant.threads.setStatus, which+ // requires assistant:write. The least-privilege Paperclip manifest+ // deliberately does not request that scope; the coalesced lifecycle+ // reply below is the visible working state instead.+ endpoint.provider === "slack"+ ? Promise.resolve()+ : thread.startTyping("Working…"),+ ]);+ } catch (error) {+ const providerEffectAmbiguous =+ error !== null &&+ typeof error === "object" &&+ "code" in error &&+ error.code === "CHAT_PROVIDER_EFFECT_AMBIGUOUS";+ const terminal =+ providerEffectAmbiguous ||+ isExternalActionAuthorizationChange(error) ||+ activeDelivery.attempts >= 5;+ await db.transaction(async (tx) => {+ await notifyChatDeliveryWork(tx);+ return tx+ .update(chatDeliveries)+ .set({+ state: terminal ? "failed" : "retry",+ nextAttemptAt: terminal+ ? null+ : new Date(+ Date.now() ++ Math.min(60_000, 1000 * 2 ** activeDelivery.attempts),+ ),+ redactedError: redactError(error),+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.state, "processing"),+ ),+ );+ });+ if (terminal) await settleRejectedInboundWakeups(activeDelivery.id);+ throw error;}+ }++ function deliveryContentWasRedacted(normalizedEvent: unknown): boolean {+ if (+ !normalizedEvent ||+ typeof normalizedEvent !== "object" ||+ Array.isArray(normalizedEvent)+ )+ return false;+ const filtering = (normalizedEvent as { filtering?: unknown }).filtering;+ return (+ Boolean(filtering) &&+ typeof filtering === "object" &&+ !Array.isArray(filtering) &&+ (filtering as { contentRetained?: unknown }).contentRetained === false+ );+ }++ function setupDestinationActivationSuppressed(+ normalizedEvent: unknown,+ ): boolean {+ if (+ !normalizedEvent ||+ typeof normalizedEvent !== "object" ||+ Array.isArray(normalizedEvent)+ )+ return false;+ const normalized = normalizedEvent as {+ admission?: { origin?: unknown };+ admissionAuthorization?: { version?: unknown };+ };+ return (+ normalized.admission?.origin === "provider_confirmed_action" ||+ normalized.admissionAuthorization?.version === 1+ );+ }++ function normalizedDeliveryThreadId(delivery: Pick<DeliveryRow, "normalizedEvent">): string | null {+ const normalized = delivery.normalizedEvent as {+ conversation?: { externalThreadId?: unknown };+ };+ return typeof normalized.conversation?.externalThreadId === "string"+ ? normalized.conversation.externalThreadId+ : null;+ }++ function normalizedLifecycleTargetEventId(+ delivery: Pick<DeliveryRow, "eventKind" | "normalizedEvent">,+ ): string | null {+ if (+ delivery.eventKind !== "message_updated" &&+ delivery.eventKind !== "message_deleted" &&+ delivery.eventKind !== "message_restored"+ )+ return null;+ const normalized = delivery.normalizedEvent as {+ message?: { targetProviderEventId?: unknown; admissionDependencyEventId?: unknown };+ };+ // An edit can also introduce a new addressed request. Process that durable+ // admission before waiting for the old, potentially unadmitted source.+ if (typeof normalized.message?.admissionDependencyEventId === "string")+ return normalized.message.admissionDependencyEventId;+ return typeof normalized.message?.targetProviderEventId === "string"+ ? normalized.message.targetProviderEventId+ : null;+ }++ function normalizedLifecycleEffect(+ delivery: Pick<DeliveryRow, "normalizedEvent">,+ ): ChatProviderLifecycleEffect | null {+ const normalized = delivery.normalizedEvent as { lifecycle?: unknown };+ const value = normalized.lifecycle;+ if (!value || typeof value !== "object" || Array.isArray(value))+ return null;+ const effect = value as Record<string, unknown>;+ if (+ (effect.provider !== "slack" &&+ effect.provider !== "github" &&+ effect.provider !== "discord" &&+ effect.provider !== "microsoft-teams" &&+ effect.provider !== "telegram") ||+ typeof effect.providerEventId !== "string"+ )+ return null;+ if (+ effect.kind === "endpoint" &&+ (effect.availability === "available" ||+ effect.availability === "attention" ||+ effect.availability === "revoked") &&+ typeof effect.reason === "string"+ )+ return effect as ChatProviderLifecycleEffect;+ if (+ effect.kind === "resource" &&+ (effect.availability === "available" ||+ effect.availability === "unavailable" ||+ effect.availability === "removed") &&+ typeof effect.providerResourceId === "string" &&+ (effect.previousProviderResourceId === undefined ||+ typeof effect.previousProviderResourceId === "string") &&+ typeof effect.resourceType === "string" &&+ typeof effect.label === "string"+ )+ return effect as ChatProviderLifecycleEffect;+ return null;+ }- const next = await earliestOpenConversationDelivery(endpointId, threadId);- if (next?.state === "processed") {- const [ready] = await db- .select({ id: chatDeliveries.id })- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.id, next.id),- pendingInboundWakeupCondition(true),- ),- )- .limit(1);- return Boolean(ready);+ function deliveryReady(delivery: DeliveryRow, now: Date): boolean {+ // Accepted input may still own the conversation head through its wake+ // outbox. The action dispatcher checks its own retry/claim deadline.+ if (delivery.state === "processed") return true;+ if (delivery.state === "received")+ return !delivery.nextAttemptAt || delivery.nextAttemptAt <= now;+ if (delivery.state === "retry") {+ return !delivery.nextAttemptAt || delivery.nextAttemptAt <= now;}- return Boolean(next && deliveryReady(next, new Date()));+ return (+ delivery.state === "processing" &&+ delivery.updatedAt <=+ new Date(now.getTime() - DELIVERY_PROCESSING_STALE_MS)+ );}- async function handleSdkMessage(- event: ChatSdkMessageCallbackEvent,- runtimeContext?: RuntimeContext,- messageOptions: {- receiptReactionSupported?: boolean;- slackSlashControl?: boolean;- } = {},- ) {- if (- event.provider === "discord" &&- (!runtimeContext ||- !(await ensureDiscordGatewayRuntimeIsCurrent(- event.endpointId,- runtimeContext,- )))- ) {- return;- }- if (event.provider === "discord") {- await options.discordGatewayMessageAdmissionBarrier?.();- }- const record = await endpointRecord(event.endpointId);- if (!record) throw notFound("Chat endpoint not found");- const messages = [...(event.context?.skipped ?? []), event.message];- for (const message of messages)- await processMessage(- record.endpoint,- event.thread,- message,- message === event.message ? event.trigger : "subscribed_message",- event.provider === "imessage-photon" ||- options.deferWebhookProcessing === true,- null,- runtimeContext,- event.providerUpdateId,- null,- messageOptions.receiptReactionSupported !== false,- undefined,- false,- false,- messageOptions.slackSlashControl === true,- );+ function conversationDeliveryOrder() {+ return [+ asc(+ sql`coalesce(nullif(${chatDeliveries.normalizedEvent}->'message'->>'providerSentAt', '')::timestamptz, ${chatDeliveries.receivedAt})`,+ ),+ // GitHub timestamps and Telegram message dates have one-second+ // resolution. GitHub's numeric comment id and Telegram's message_id+ // are monotonic within one conversation, so use them before receipt+ // order. The Telegram update_id is a final provider-native tie-breaker+ // for unusual payloads that lack a usable message_id.+ asc(sql`coalesce(+ case+ when ${chatDeliveries.normalizedEvent}->'message'->>'providerMessageSequence' ~ '^[0-9]+$'+ then (${chatDeliveries.normalizedEvent}->'message'->>'providerMessageSequence')::numeric+ else null+ end,+ case+ when ${chatDeliveries.normalizedEvent}->'message'->>'providerMessageId' ~ '^[0-9]+$'+ then (${chatDeliveries.normalizedEvent}->'message'->>'providerMessageId')::numeric+ else null+ end+ )`),+ asc(sql`case+ when ${chatDeliveries.normalizedEvent}->'message'->>'providerUpdateId' ~ '^[0-9]+$'+ then (${chatDeliveries.normalizedEvent}->'message'->>'providerUpdateId')::numeric+ else null+ end`),+ // GitHub exposes no sortable webhook sequence. When an edit and delete+ // share its whole-second updated_at value, preserve the only valid+ // lifecycle state transition: update before delete. Provider-native+ // update ids (Telegram) remain the stronger preceding key.+ asc(sql`case ${chatDeliveries.eventKind}+ when 'message_updated' then 1+ when 'message_deleted' then 2+ when 'message_restored' then 3+ else 0+ end`),+ asc(chatDeliveries.receivedAt),+ asc(chatDeliveries.id),+ ];}- async function conversationForThread(endpointId: string, threadId: string) {- const exact = await db+ async function earliestOpenConversationDelivery(+ endpointId: string,+ threadId: string,+ ): Promise<DeliveryRow | null> {+ const externalThreadId = sql<string>`${chatDeliveries.normalizedEvent}->'conversation'->>'externalThreadId'`;+ const candidate = await db.select()- .from(chatConversations)+ .from(chatDeliveries).where(and(- eq(chatConversations.endpointId, endpointId),- eq(chatConversations.externalThreadId, threadId),+ eq(chatDeliveries.endpointId, endpointId),+ or(+ inArray(chatDeliveries.state, ["received", "retry", "processing"]),+ and(+ eq(chatDeliveries.state, "processed"),+ pendingInboundWakeupCondition(),+ ),+ ),+ notInArray(chatDeliveries.eventKind, [+ "reaction_added",+ "reaction_removed",+ ]),+ externalThreadIdentityCondition(externalThreadId, threadId),),)- .orderBy(desc(chatConversations.sessionGeneration))+ .orderBy(...conversationDeliveryOrder())+ .limit(1).then((rows) => rows[0] ?? null);- if (exact || !threadId.startsWith("teams:")) return exact;+ if (!candidate) return null;- // Before Paperclip made Teams route state independent, the adapter- // embedded the mutable Bot Connector serviceUrl in every thread id. Read- // those rows by the immutable conversation id so a regional route change- // continues the same task. New rows use the canonical route-free id.- if (!teamsConversationId(threadId)) return null;+ // A lifecycle callback can reach Paperclip before its create callback. If+ // the root becomes durable while the lifecycle row is waiting, always+ // return that exact dependency first even when a coarse or malformed+ // provider timestamp would otherwise put the edit/delete at the head.+ const targetProviderEventId = normalizedLifecycleTargetEventId(candidate);+ if (!targetProviderEventId) return candidate;return db.select()- .from(chatConversations)+ .from(chatDeliveries).where(and(- eq(chatConversations.endpointId, endpointId),- externalThreadIdentityCondition(- sql<string>`${chatConversations.externalThreadId}`,- threadId,- ),+ eq(chatDeliveries.endpointId, endpointId),+ eq(chatDeliveries.providerEventId, targetProviderEventId),+ inArray(chatDeliveries.state, ["received", "retry", "processing"]),),)- .orderBy(desc(chatConversations.sessionGeneration))- .then(- (rows) =>- rows.find((row) =>- sameTeamsThreadIdentity(row.externalThreadId, threadId),- ) ?? null,+ .limit(1)+ .then((rows) => rows[0] ?? candidate);+ }++ function pendingInboundWakeupCondition(readyOnly = false): SQL {+ return sql`exists (+ select 1 from ${chatActions}+ where ${chatActions.deliveryId} = ${chatDeliveries.id}+ and ${chatActions.endpointId} = ${chatDeliveries.endpointId}+ and ${chatActions.companyId} = ${chatDeliveries.companyId}+ and ${chatActions.kind} = 'inbound_wakeup'+ and ${chatActions.status} in ('issued', 'processing')+ ${+ readyOnly+ ? sql`and (+ (${chatActions.status} = 'issued' and (${chatActions.result}->>'retryAt' is null or (${chatActions.result}->>'retryAt')::timestamptz <= now()))+ or (${chatActions.status} = 'processing' and ${chatActions.updatedAt} <= ${new Date(Date.now() - DELIVERY_PROCESSING_STALE_MS).toISOString()}::timestamptz)+ )`+ : sql``+ }+ )`;+ }++ async function acquireConversationDeliveryLease(input: {+ companyId: string;+ endpointId: string;+ threadId: string;+ }): Promise<{ leaseKey: string; token: string } | null> {+ const now = new Date();+ const token = randomUUID();+ const leaseKey = `inbound:${createHash("sha256").update(durableExternalThreadIdentity(input.threadId)).digest("hex")}`;+ const expiresAt = new Date(now.getTime() + DELIVERY_LEASE_TTL_MS);+ const inserted = await db+ .insert(chatEndpointLeases)+ .values({+ companyId: input.companyId,+ endpointId: input.endpointId,+ leaseKey,+ token,+ expiresAt,+ })+ .onConflictDoNothing()+ .returning({ id: chatEndpointLeases.id });+ if (inserted.length > 0) return { leaseKey, token };+ const reclaimed = await db+ .update(chatEndpointLeases)+ .set({ token, expiresAt, updatedAt: now })+ .where(+ and(+ eq(chatEndpointLeases.companyId, input.companyId),+ eq(chatEndpointLeases.endpointId, input.endpointId),+ eq(chatEndpointLeases.leaseKey, leaseKey),+ lte(chatEndpointLeases.expiresAt, now),+ ),+ )+ .returning({ id: chatEndpointLeases.id });+ return reclaimed.length > 0 ? { leaseKey, token } : null;+ }++ async function releaseConversationDeliveryLease(input: {+ endpointId: string;+ leaseKey: string;+ token: string;+ }): Promise<void> {+ await db+ .delete(chatEndpointLeases)+ .where(+ and(+ eq(chatEndpointLeases.endpointId, input.endpointId),+ eq(chatEndpointLeases.leaseKey, input.leaseKey),+ eq(chatEndpointLeases.token, input.token),+ ),);}- async function recordLifecycleDelivery(- input: {- actor?: LifecycleActor;- isBotMessage?: true;- endpointId: string;- threadId: string;- messageId: string;- eventKind: "message_updated" | "message_deleted" | "message_restored";- text: string;- providerEventId?: string;- providerMessageSequence?: number | null;- providerSentAt?: string | null;- providerUpdateId?: number | null;- raw?: unknown;- revision?: string | null;- admissionDependencyEventId?: string;- },- runtimeContext?: RuntimeContext,- githubSourceMapped = false,- ) {- if (!githubSourceMapped && input.threadId.startsWith("github:") && /^[1-9][0-9]*$/.test(input.messageId)) {- const requests = await db.select({ id: chatDeliveries.id, messageId: sql<string>`${chatDeliveries.normalizedEvent}->'message'->>'providerMessageId'` })- .from(chatDeliveries).innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatDeliveries.endpointId), eq(chatEndpoints.companyId, chatDeliveries.companyId)))- .where(and(eq(chatDeliveries.endpointId, input.endpointId), eq(chatEndpoints.provider, "github"),- inArray(chatDeliveries.eventKind, ["mention", "message", "direct_message"]),- input.admissionDependencyEventId ? ne(chatDeliveries.providerEventId, input.admissionDependencyEventId) : undefined,- sql`${chatDeliveries.normalizedEvent}->'message'->>'sourceProviderMessageId' = ${input.messageId}`,- sql`${chatDeliveries.normalizedEvent}->'conversation'->>'externalThreadId' = ${input.threadId}`));- if (requests.length) {- for (const request of requests) await recordLifecycleDelivery({ ...input, messageId: request.messageId,- providerEventId: `${input.providerEventId ?? `${input.eventKind}:${input.threadId}:${input.messageId}:${input.revision ?? "once"}`}:${request.id}` }, runtimeContext, true);- return;- }- }- const durableThreadId = durableExternalThreadIdentity(input.threadId);- const providerEventId =- input.providerEventId ??- `${input.eventKind}:${durableThreadId}:${input.messageId}:${input.revision ?? "once"}`;- const targetProviderEventId = `${durableThreadId}:${input.messageId}`;- const admission = await db.transaction(async (tx) => {- const endpoint = await tx- .select()- .from(chatEndpoints)- .where(eq(chatEndpoints.id, input.endpointId))- .for("update")- .then((rows) => rows[0] ?? null);- if (!endpoint) throw notFound("Chat endpoint not found");- if (- runtimeContext &&- !(await runtimeCallbackEndpoint(tx, endpoint.id, runtimeContext, [- "verifying",- "active",- ]))- )- return null;- // A provider has already authenticated this callback. During setup the- // message can belong to the test conversation, so retain its correction.- // Paused or unhealthy connections acknowledge late callbacks without- // mutating the bound task or causing provider retry storms.- if (endpoint.status !== "verifying" && endpoint.status !== "active")+ function messageFromDelivery(+ delivery: DeliveryRow,+ thread: Thread,+ endpointRuntime: ChatEndpointRuntime,+ ): {+ message: Message;+ receiptReactionSupported: boolean;+ suppressSetupDestinationActivation: boolean;+ trigger: ChatSdkMessageCallbackEvent["trigger"];+ providerUrl: string | null;+ } | null {+ if (telegramDeliveryHasZeroMessageId(delivery, endpointRuntime.provider))+ return null;+ const normalized = delivery.normalizedEvent as {+ acknowledgement?: { receiptReactionSupported?: unknown };+ kind?: unknown;+ trigger?: unknown;+ principal?: {+ externalId?: unknown;+ displayName?: unknown;+ handle?: unknown;+ };+ message?: {+ providerMessageId?: unknown;+ sourceProviderMessageId?: unknown;+ text?: unknown;+ mentionedBot?: unknown;+ attachments?: Array<{+ name?: unknown;+ mimeType?: unknown;+ size?: unknown;+ recovery?: unknown;+ }>;+ attachmentLimitOmissions?: unknown;+ photonReply?: { guid?: unknown; part?: unknown };+ };+ conversation?: { providerUrl?: unknown };+ };+ const providerMessageId = normalized.message?.providerMessageId;+ const externalId = normalized.principal?.externalId;+ if (typeof providerMessageId !== "string" || typeof externalId !== "string")+ return null;+ const isTeams = endpointRuntime.provider === "microsoft-teams";+ const referenceOnlyTeamsAttachments = isTeams && !thread.isDM;+ const originFence = lifecycleRuntimeFence(delivery);+ const storedAttachments = normalized.message?.attachments ?? [];+ const attachments = (+ isTeams ? storedAttachments.slice(0, 20) : storedAttachments+ )+ .map((attachment) => {+ if (!attachment || typeof attachment !== "object") return null;+ const rehydrated =+ attachment.recovery &&+ (!referenceOnlyTeamsAttachments ||+ (typeof attachment.recovery === "object" &&+ attachment.recovery !== null &&+ "locator" in attachment.recovery &&+ typeof attachment.recovery.locator === "object" &&+ attachment.recovery.locator !== null &&+ "kind" in attachment.recovery.locator &&+ attachment.recovery.locator.kind === "teams_inline_image"))+ ? endpointRuntime.rehydrateAttachment(attachment.recovery, {+ threadId: thread.id,+ messageId: typeof normalized.message?.sourceProviderMessageId === "string" ? normalized.message.sourceProviderMessageId : providerMessageId,+ runtimeGeneration: originFence?.generation,+ credentialFingerprint: originFence?.credentialFingerprint,+ principalExternalId: externalId,+ isDirectMessage: thread.isDM,+ })+ : null;+ if (rehydrated) return rehydrated;+ if (+ isTeams ||+ endpointRuntime.provider === "imessage-photon" ||+ (endpointRuntime.provider === "telegram" &&+ typeof attachment.recovery === "object" &&+ attachment.recovery !== null &&+ "locator" in attachment.recovery &&+ typeof attachment.recovery.locator === "object" &&+ attachment.recovery.locator !== null &&+ "kind" in attachment.recovery.locator &&+ attachment.recovery.locator.kind === "telegram_media")+ ) {+ // Non-personal references and personal files whose safe download+ // capability did not survive restart still belong to this input.+ // Keep bounded metadata so ingestion records an explicit omission;+ // never persist bearer URLs or fabricate a download capability.+ // Even a legacy URL locator cannot enable non-personal downloads.+ // A Telegram media locator which fails its exact source proof also+ // remains an unavailable input, never an empty attachment-free turn.+ return {+ type: "file",+ name:+ sanitizeFilename(+ typeof attachment.name === "string"+ ? attachment.name+ : undefined,+ ) ?? undefined,+ mimeType: normalizeContentType(+ typeof attachment.mimeType === "string"+ ? attachment.mimeType+ : undefined,+ ).slice(0, 255),+ size:+ typeof attachment.size === "number" &&+ Number.isSafeInteger(attachment.size) &&+ attachment.size >= 0+ ? attachment.size+ : undefined,+ } as Attachment;+ }return null;- const reorderWindow = INGRESS_REORDER_WINDOW_MS[endpoint.provider];- const scheduledAt =- options.deferWebhookProcessing === true && reorderWindow- ? (scheduledConversationDrains.get(- conversationDrainKey(input.endpointId, input.threadId),- ) ?? Date.now() + reorderWindow)- : null;- await notifyChatDeliveryWork(tx);- const [delivery] = await tx- .insert(chatDeliveries)- .values({- companyId: endpoint.companyId,- endpointId: input.endpointId,- providerEventId,- deduplicationKey: createHash("sha256")- .update(providerEventId)- .digest("hex"),- eventKind: input.eventKind,- normalizedEvent: {- providerEventId,- kind: input.eventKind,- ...(runtimeContext- ? {- runtimeContext: {- credentialFingerprint: runtimeContext.credentialFingerprint,- generation: runtimeContext.generation,- },- }- : {}),- ...(input.actor ? { principal: input.actor } : {}),- conversation: { externalThreadId: input.threadId },- message: {- providerMessageId: input.messageId,- targetProviderEventId,- ...(input.admissionDependencyEventId ? { admissionDependencyEventId: input.admissionDependencyEventId } : {}),- ...(endpoint.provider === "github" && input.isBotMessage === true- ? { isBotMessage: true }- : {}),- providerMessageSequence: input.providerMessageSequence ?? null,- providerSentAt: input.providerSentAt ?? null,- providerUpdateId: input.providerUpdateId ?? null,- text: input.text,- },- },- state: "received",- nextAttemptAt: scheduledAt ? new Date(scheduledAt) : null,- })- .onConflictDoNothing()- .returning();- if (delivery) return { delivery, endpoint, scheduledAt };- const existing = await tx- .select()- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.endpointId, input.endpointId),- eq(chatDeliveries.providerEventId, providerEventId),- ),- )- .then((rows) => rows[0] ?? null);- return existing ? { delivery: existing, endpoint, scheduledAt } : null;- });- if (admission) {- // Lifecycle callbacks can carry a new regional Bot Connector route. Keep- // that provider-authenticated route current even when processing is- // deferred, but deliberately omit the raw activity here. Lifecycle- // callbacks never populate the adapter's user cache; the admitted root- // message already established the principal metadata they must match.- await recordCurrentMicrosoftTeamsRoute(- admission.endpoint,- runtimeContext,- input.threadId,- input.raw,- false,- );+ })+ .filter((attachment): attachment is Attachment => Boolean(attachment));+ const message = {+ id: providerMessageId,+ threadId: thread.id,+ text:+ typeof normalized.message?.text === "string"+ ? normalized.message.text+ : "",+ formatted: { type: "root", children: [] },+ raw:+ endpointRuntime.provider === "imessage-photon" &&+ typeof normalized.message?.photonReply?.guid === "string"+ ? {+ replyTargetGuid: normalized.message.photonReply.guid,+ threadOriginatorPart: normalized.message.photonReply.part,+ }+ : endpointRuntime.provider === "github" && typeof normalized.message?.sourceProviderMessageId === "string"+ ? { githubSourceMessageId: normalized.message.sourceProviderMessageId } : {},+ author: {+ userId: externalId,+ userName:+ typeof normalized.principal?.handle === "string"+ ? normalized.principal.handle+ : externalId,+ fullName:+ typeof normalized.principal?.displayName === "string"+ ? normalized.principal.displayName+ : externalId,+ isBot: false,+ isMe: false,+ isSystem: false,+ },+ metadata: { dateSent: delivery.receivedAt, edited: false },+ attachments,+ links: [],+ isMention: normalized.message?.mentionedBot === true,+ } as unknown as Message;+ const githubManual = delivery.normalizedEvent.githubManual;+ if (endpointRuntime.provider === "github" && githubManual && typeof githubManual === "object") githubManualMessages.set(message, githubManual as { policy: GitHubReviewPolicy; revision: number; event: "mention" | "comment" });+ const githubAutomatic = delivery.normalizedEvent.githubAutomatic;+ if (endpointRuntime.provider === "github" && githubAutomatic && typeof githubAutomatic === "object") {+ githubAutomaticMessages.set(message, githubAutomatic as { context: GitHubReviewEventContext; revision: number; policy: GitHubReviewPolicy });+ }+ const githubIssue = delivery.normalizedEvent.githubIssue;+ if (endpointRuntime.provider === "github" && githubIssue && typeof githubIssue === "object") {+ githubIssueMessages.set(message, githubIssue as { context: GitHubIssueEventContext; revision: number; policy: GitHubReviewPolicy });}if (- !admission ||- admission.delivery.state === "processed" ||- admission.delivery.state === "filtered" ||- admission.delivery.state === "failed"- )- return;- if (options.deferWebhookProcessing === true) {- scheduleConversationDrain(- input.endpointId,- input.threadId,- admission.scheduledAt ?? Date.now(),+ endpointRuntime.provider === "github" ||+ endpointRuntime.provider === "imessage-photon"+ ) {+ restoreGitHubAttachmentLimitOmissions(+ message,+ normalized.message?.attachmentLimitOmissions,);- return;}- await drainConversationDeliveries(input.endpointId, input.threadId);- }-- function lifecycleMessageFromDelivery(delivery: DeliveryRow): {- actor: LifecycleActor | null;- isBotMessage: boolean;- messageId: string;- providerSentAt: string | null;- targetProviderEventId: string;- text: string;- threadId: string;- } | null {- if (- delivery.eventKind !== "message_updated" &&- delivery.eventKind !== "message_deleted" &&- delivery.eventKind !== "message_restored"- )- return null;- const normalized = delivery.normalizedEvent as {- principal?: {- displayName?: unknown;- externalId?: unknown;- handle?: unknown;- };- message?: {- isBotMessage?: unknown;- providerMessageId?: unknown;- providerSentAt?: unknown;- targetProviderEventId?: unknown;- text?: unknown;- };+ const normalizedTrigger = normalized.trigger;+ const trigger: ChatSdkMessageCallbackEvent["trigger"] =+ normalizedTrigger === "direct_message" ||+ normalizedTrigger === "mention" ||+ normalizedTrigger === "subscribed_message" ||+ normalizedTrigger === "unaddressed_message"+ ? normalizedTrigger+ : normalized.kind === "direct_message"+ ? "direct_message"+ : normalized.kind === "mention"+ ? "mention"+ : "subscribed_message";+ return {+ message,+ // Legacy deliveries all originated from native provider messages and+ // therefore retain the historical default.+ receiptReactionSupported:+ normalized.acknowledgement?.receiptReactionSupported !== false,+ suppressSetupDestinationActivation: setupDestinationActivationSuppressed(+ delivery.normalizedEvent,+ ),+ trigger,+ providerUrl:+ typeof normalized.conversation?.providerUrl === "string"+ ? normalized.conversation.providerUrl+ : null,};- const messageId = normalized.message?.providerMessageId;- const targetProviderEventId = normalized.message?.targetProviderEventId;- const providerSentAt = normalized.message?.providerSentAt;- const text = normalized.message?.text;- const threadId = normalizedDeliveryThreadId(delivery);- const externalId = normalized.principal?.externalId;- const actor =- typeof externalId === "string" && externalId- ? {- externalId,- displayName:- typeof normalized.principal?.displayName === "string"- ? normalized.principal.displayName- : externalId,- handle:- typeof normalized.principal?.handle === "string"- ? normalized.principal.handle- : externalId,- }- : null;- return typeof messageId === "string" &&- typeof targetProviderEventId === "string" &&- typeof text === "string" &&- threadId !== null- ? {- actor,- isBotMessage: normalized.message?.isBotMessage === true,- messageId,- providerSentAt:- typeof providerSentAt === "string" ? providerSentAt : null,- targetProviderEventId,- text,- threadId,- }- : null;}- async function processLifecycleDelivery(- endpoint: EndpointRow,- candidate: DeliveryRow,- ): Promise<void> {- const lifecycle = lifecycleMessageFromDelivery(candidate);- if (!lifecycle) {- await db.transaction(async (tx) => {- await notifyChatDeliveryWork(tx);- return tx- .update(chatDeliveries)- .set({- state: "failed",- redactedError: "Normalized lifecycle delivery is incomplete",- updatedAt: new Date(),- })- .where(eq(chatDeliveries.id, candidate.id));- });- return;- }+ /**+ * Drain one external conversation in durable receipt order. The database+ * lease is endpoint + thread scoped, so separate server processes can work+ * on different conversations concurrently but can never mutate the same+ * Paperclip task from two inbound turns at once.+ */+ async function drainConversationDeliveries(+ endpointId: string,+ threadId: string,+ ): Promise<boolean> {+ const endpoint = await db+ .select()+ .from(chatEndpoints)+ .where(eq(chatEndpoints.id, endpointId))+ .then((rows) => rows[0] ?? null);+ if (!endpoint) return false;+ if (endpoint.status === "paused" || endpoint.status === "attention")+ return false;- const now = new Date();- const staleBefore = new Date(now.getTime() - DELIVERY_PROCESSING_STALE_MS);- const claimConditions = [- eq(chatDeliveries.id, candidate.id),- eq(chatDeliveries.state, candidate.state),- ];- if (candidate.state === "processing")- claimConditions.push(lte(chatDeliveries.updatedAt, staleBefore));- const [activeDelivery] = await db.transaction(async (tx) => {- await notifyChatDeliveryWork(tx);- return tx- .update(chatDeliveries)- .set({- state: "processing",- attempts: candidate.attempts + 1,- nextAttemptAt: null,- redactedError: null,- updatedAt: now,- })- .where(and(...claimConditions))- .returning();+ const lease = await acquireConversationDeliveryLease({+ companyId: endpoint.companyId,+ endpointId,+ threadId,});- if (!activeDelivery) return;+ if (!lease) return false;++ let leaseOwned = true;+ let renewal: Promise<void> | null = null;+ const renewTimer = setInterval(+ () => {+ if (!leaseOwned || renewal) return;+ const expiresAt = new Date(Date.now() + DELIVERY_LEASE_TTL_MS);+ renewal = Promise.resolve()+ .then(async () => {+ const renewed = options.renewConversationDeliveryLease+ ? await options.renewConversationDeliveryLease({+ endpointId,+ leaseKey: lease.leaseKey,+ token: lease.token,+ expiresAt,+ })+ : await db+ .update(chatEndpointLeases)+ .set({ expiresAt, updatedAt: new Date() })+ .where(+ and(+ eq(chatEndpointLeases.endpointId, endpointId),+ eq(chatEndpointLeases.leaseKey, lease.leaseKey),+ eq(chatEndpointLeases.token, lease.token),+ ),+ )+ .returning({ id: chatEndpointLeases.id })+ .then((rows) => rows.length > 0);+ if (!renewed) leaseOwned = false;+ })+ .catch((error) => {+ // A failed renewal has unknown durability. Stop this local drain at+ // the next delivery boundary so another worker can never overlap+ // later turns after the original lease expires or is reclaimed.+ leaseOwned = false;+ logger.warn(+ { endpointId, error: redactError(error) },+ "could not renew external chat conversation lease",+ );+ })+ .finally(() => {+ renewal = null;+ });+ },+ options.conversationLeaseRenewalIntervalMs ?? DELIVERY_LEASE_TTL_MS / 3,+ );+ renewTimer.unref?.();try {- await db.transaction(async (tx) => {- const admittedRuntimeContext = lifecycleRuntimeFence(activeDelivery);- const currentEndpoint = admittedRuntimeContext- ? await runtimeCallbackEndpoint(- tx,- endpoint.id,- admittedRuntimeContext,- ["verifying", "active"],- )- : null;- if (!admittedRuntimeContext || !currentEndpoint) {- const filteredAt = new Date();- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- state: "filtered",- nextAttemptAt: null,- processedAt: filteredAt,- redactedError:- "Message lifecycle callback belonged to a superseded runtime",- updatedAt: filteredAt,+ for (+ let processed = 0;+ processed < DELIVERY_DRAIN_LIMIT;+ processed += 1+ ) {+ if (!leaseOwned) break;+ const delivery = await earliestOpenConversationDelivery(+ endpointId,+ threadId,+ );+ if (!delivery || !deliveryReady(delivery, new Date())) break;+ if (delivery.state === "processed") {+ if (!(await processInboundWakeup(delivery.id))) break;+ continue;+ }+ if (telegramDeliveryHasZeroMessageId(delivery, endpoint.provider)) {+ const filtered = await db+ .transaction(async (tx) => {+ // Do not round-trip a PostgreSQL microsecond timestamp through+ // JS Date for a CAS. Lock the exact receipt, then revalidate the+ // current source and claim before changing it. A competing live+ // claim is a retry boundary, not permission to settle its work.+ const [current] = await tx+ .select()+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.id, delivery.id),+ eq(chatDeliveries.companyId, endpoint.companyId),+ eq(chatDeliveries.endpointId, endpoint.id),+ ),+ )+ .for("update", { noWait: true });+ const filteredAt = new Date();+ if (+ !current ||+ current.state !== delivery.state ||+ current.eventKind !== delivery.eventKind ||+ !["received", "retry", "processing"].includes(current.state) ||+ normalizedDeliveryThreadId(current) !== threadId ||+ !deliveryReady(current, filteredAt) ||+ !telegramDeliveryHasZeroMessageId(current, endpoint.provider)+ )+ return false;+ await notifyChatDeliveryWork(tx);+ const changed = await tx+ .update(chatDeliveries)+ .set({+ state: "filtered",+ nextAttemptAt: null,+ processedAt: filteredAt,+ updatedAt: filteredAt,+ redactedError:+ "Telegram message ID zero cannot authorize ordinary work",+ })+ .where(eq(chatDeliveries.id, current.id))+ .returning({ id: chatDeliveries.id });+ return changed.length === 1;})- .where(- and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.state, "processing"),- ),- );- return;+ .catch((error: unknown) => {+ if (isExternalChatWaitAuthorizationContention(error))+ return false;+ throw error;+ });+ if (!filtered) break;+ // Retain original evidence/comments; filtering adds no user content+ // and cannot hydrate attachments, invoke commands, or send feedback.+ await settleRejectedInboundWakeups(delivery.id);+ liveInboundMessages.delete(delivery.id);+ continue;}- let githubBotSourceEdit = false;- if (- currentEndpoint.provider === "github" &&- activeDelivery.eventKind === "message_updated"- ) {- // Bot callbacks can arrive before the outbound publication commits- // its message link. The Boolean comes only from GitHub's verified- // sender/comment-author type, never from comment text. Legacy rows- // lack it, so also recognize exact already-published outbound links.- const linkedMessages = await tx- .select({ direction: chatMessageLinks.direction })- .from(chatMessageLinks)- .innerJoin(- chatConversations,- and(- eq(chatConversations.id, chatMessageLinks.conversationId),- eq(chatConversations.companyId, chatMessageLinks.companyId),- eq(chatConversations.endpointId, chatMessageLinks.endpointId),- ),- )- .where(- and(- eq(chatMessageLinks.companyId, currentEndpoint.companyId),- eq(chatMessageLinks.endpointId, currentEndpoint.id),- eq(chatMessageLinks.providerMessageId, lifecycle.messageId),- eq(chatConversations.externalThreadId, lifecycle.threadId),- ),- );- const outbound = linkedMessages.some(- (row) => row.direction === "outbound",- );- // A bot editor can change an already-admitted human source. That- // authenticated change revokes the old source, but never admits the- // bot's new content. Unknown/self/outbound updates remain suppressed.- githubBotSourceEdit =- lifecycle.isBotMessage &&- !outbound &&- linkedMessages.some((row) => row.direction === "inbound");- if (outbound || (lifecycle.isBotMessage && !githubBotSourceEdit)) {- const filteredAt = new Date();+ if (endpoint.status === "archived" || endpoint.status === "revoked") {+ await db.transaction(async (tx) => {await notifyChatDeliveryWork(tx);- await tx+ return tx.update(chatDeliveries).set({state: "filtered",- principalId: null,- nextAttemptAt: null,- processedAt: filteredAt,- updatedAt: filteredAt,- redactedError:- "Provider bot or outbound message updates do not create inbound work",- normalizedEvent: {- providerEventId:- activeDelivery.normalizedEvent.providerEventId ??- activeDelivery.providerEventId,- kind: activeDelivery.eventKind,- conversation: { externalThreadId: lifecycle.threadId },- message: {- providerMessageId: lifecycle.messageId,- targetProviderEventId: lifecycle.targetProviderEventId,- },- filtering: { contentRetained: false },- },+ redactedError: "Connection was removed before processing",+ processedAt: new Date(),+ updatedAt: new Date(),})- .where(- and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.state, "processing"),- ),- );- return;- }+ .where(eq(chatDeliveries.id, delivery.id));+ });+ liveInboundMessages.delete(delivery.id);+ continue;}+if (- activeDelivery.eventKind === "message_updated" ||- activeDelivery.eventKind === "message_deleted" ||- activeDelivery.eventKind === "message_restored"+ endpoint.provider === "discord" &&+ discordRootThreadPending(delivery)) {- const latestDeleteTransition = await tx- .select({- eventKind: chatDeliveries.eventKind,- providerSentAt: sql<- string | null- >`nullif(${chatDeliveries.normalizedEvent}->'message'->>'providerSentAt', '')`,- })- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.companyId, activeDelivery.companyId),- eq(chatDeliveries.endpointId, endpoint.id),- inArray(chatDeliveries.eventKind, [- "message_deleted",- "message_restored",- ]),- eq(chatDeliveries.state, "processed"),- externalThreadIdentityCondition(- sql<string>`${chatDeliveries.normalizedEvent}->'conversation'->>'externalThreadId'`,- lifecycle.threadId,- ),- sql`${chatDeliveries.normalizedEvent}->'message'->>'targetProviderEventId' = ${lifecycle.targetProviderEventId}`,- ),- )- .orderBy(- desc(- sql`coalesce(nullif(${chatDeliveries.normalizedEvent}->'message'->>'providerSentAt', '')::timestamptz, ${chatDeliveries.processedAt})`,- ),- desc(sql`case ${chatDeliveries.eventKind}- when 'message_restored' then 2- when 'message_deleted' then 1- else 0- end`),- desc(chatDeliveries.processedAt),- desc(chatDeliveries.id),- )- .limit(1)- .then((rows) => rows[0] ?? null);- const latestTransitionAt = latestDeleteTransition?.providerSentAt- ? Date.parse(latestDeleteTransition.providerSentAt)- : Number.NaN;- const incomingTransitionAt = lifecycle.providerSentAt- ? Date.parse(lifecycle.providerSentAt)- : Number.NaN;- const incomingTransitionIsStale =- latestDeleteTransition !== null &&- Number.isFinite(latestTransitionAt) &&- Number.isFinite(incomingTransitionAt) &&- (incomingTransitionAt < latestTransitionAt ||- (incomingTransitionAt === latestTransitionAt &&- activeDelivery.eventKind === "message_deleted" &&- latestDeleteTransition.eventKind === "message_restored"));- const editTargetsDeletedMessage =- activeDelivery.eventKind === "message_updated" &&- latestDeleteTransition?.eventKind === "message_deleted";- const editPredatesRestore =- activeDelivery.eventKind === "message_updated" &&- latestDeleteTransition?.eventKind === "message_restored" &&- Number.isFinite(latestTransitionAt) &&- Number.isFinite(incomingTransitionAt) &&- incomingTransitionAt < latestTransitionAt;+ // This is the only recovery path for the narrow crash window after+ // pre-admission but before Chat's ordinary callback. A successful+ // read proves the root thread exists; an explicit 404/410 proves it+ // does not. Ambiguous transport and auth failures remain retryable.+ if (await reconcileDiscordRootThread(endpoint, delivery, threadId)) {+ continue;+ }+ break;+ }++ const live = liveInboundMessages.get(delivery.id);+ try {if (- incomingTransitionIsStale ||- editTargetsDeletedMessage ||- editPredatesRestore+ delivery.eventKind === "message_updated" ||+ delivery.eventKind === "message_deleted" ||+ delivery.eventKind === "message_restored") {- const filteredAt = new Date();- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- state: "filtered",- normalizedEvent: {- providerEventId:- activeDelivery.normalizedEvent.providerEventId ??- activeDelivery.providerEventId,- kind: activeDelivery.eventKind,- conversation: { externalThreadId: lifecycle.threadId },- message: {- providerMessageId: lifecycle.messageId,- targetProviderEventId: lifecycle.targetProviderEventId,- },- filtering: { contentRetained: false },- },- principalId: null,- nextAttemptAt: null,- processedAt: filteredAt,- redactedError: editTargetsDeletedMessage- ? "Message edit arrived after the provider message was deleted"- : "Message lifecycle callback was older than the current provider state",- updatedAt: filteredAt,- })- .where(- and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.state, "processing"),- ),- );- return;+ await processLifecycleDelivery(endpoint, delivery);+ } else if (live) {+ await processMessage(+ endpoint,+ live.thread,+ live.message,+ live.trigger,+ false,+ live.providerUrl,+ live.runtimeContext,+ undefined,+ delivery.id,+ live.receiptReactionSupported,+ undefined,+ false,+ setupDestinationActivationSuppressed(delivery.normalizedEvent),+ );+ } else {+ if (deliveryContentWasRedacted(delivery.normalizedEvent)) {+ const filteredAt = new Date();+ await db.transaction(async (tx) => {+ await notifyChatDeliveryWork(tx);+ return tx+ .update(chatDeliveries)+ .set({+ state: "filtered",+ principalId: null,+ nextAttemptAt: null,+ processedAt: filteredAt,+ redactedError:+ "Provisional Teams setup reply could not be hydrated from a current provider event",+ updatedAt: filteredAt,+ })+ .where(+ and(+ eq(chatDeliveries.id, delivery.id),+ inArray(chatDeliveries.state, [+ "received",+ "retry",+ "processing",+ ]),+ ),+ );+ });+ continue;+ }+ const endpointRuntime = await runtimeFor(endpoint);+ const deliveryRuntimeFence = lifecycleRuntimeFence(delivery);+ const currentRuntimeContext = runtimeContexts.get(+ endpointRuntime as object,+ );+ const thread = endpointRuntime.thread(threadId);+ const reconstructed = messageFromDelivery(+ delivery,+ thread,+ endpointRuntime,+ );+ if (!reconstructed) {+ await db.transaction(async (tx) => {+ await notifyChatDeliveryWork(tx);+ return tx+ .update(chatDeliveries)+ .set({+ state: "failed",+ redactedError: "Normalized delivery is incomplete",+ updatedAt: new Date(),+ })+ .where(eq(chatDeliveries.id, delivery.id));+ });+ continue;+ }+ await processMessage(+ endpoint,+ thread,+ reconstructed.message,+ reconstructed.trigger,+ false,+ reconstructed.providerUrl,+ deliveryRuntimeFence+ ? {+ ...deliveryRuntimeFence,+ endpointRuntime,+ }+ : currentRuntimeContext,+ undefined,+ delivery.id,+ reconstructed.receiptReactionSupported,+ undefined,+ false,+ reconstructed.suppressSetupDestinationActivation,+ );}+ } catch (error) {+ logger.warn(+ {+ endpointId,+ deliveryId: delivery.id,+ error: redactError(error),+ },+ "external chat delivery will retry in receipt order",+ );}- const originalDelivery = await tx++ const state = await db.select({ state: chatDeliveries.state }).from(chatDeliveries)- .where(- and(- eq(chatDeliveries.endpointId, endpoint.id),- eq(- chatDeliveries.providerEventId,- lifecycle.targetProviderEventId,- ),- ),- )- .then((rows) => rows[0] ?? null);- const linkedTargets = await tx- .select({- conversationId: chatConversations.id,- externalThreadId: chatConversations.externalThreadId,- issueId: chatConversations.issueId,- })- .from(chatMessageLinks)- .innerJoin(- chatConversations,- and(- eq(chatConversations.companyId, chatMessageLinks.companyId),- eq(chatConversations.id, chatMessageLinks.conversationId),- ),- )- .where(- and(- eq(chatMessageLinks.endpointId, endpoint.id),- eq(chatMessageLinks.providerMessageId, lifecycle.messageId),- eq(chatMessageLinks.direction, "inbound"),- ),- )- .orderBy(desc(chatConversations.sessionGeneration))- .then((rows) => rows);- const linkedTarget =- linkedTargets.find((candidate) =>- currentEndpoint.provider === "microsoft-teams"- ? sameTeamsThreadIdentity(- candidate.externalThreadId,- lifecycle.threadId,- )- : candidate.externalThreadId === lifecycle.threadId,- ) ?? null;+ .where(eq(chatDeliveries.id, delivery.id))+ .then((rows) => rows[0]?.state ?? null);+ if (+ state === "processed" ||+ state === "filtered" ||+ state === "failed"+ ) {+ if (state !== "processed")+ await settleRejectedInboundWakeups(delivery.id);+ liveInboundMessages.delete(delivery.id);+ continue;+ }+ // A retry delay or another still-live processing claim is a strict+ // head-of-line barrier; later replies may not overtake it.+ break;+ }+ } finally {+ clearInterval(renewTimer);+ await renewal;+ await releaseConversationDeliveryLease({ endpointId, ...lease });+ }++ const next = await earliestOpenConversationDelivery(endpointId, threadId);+ if (next?.state === "processed") {+ const [ready] = await db+ .select({ id: chatDeliveries.id })+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.id, next.id),+ pendingInboundWakeupCondition(true),+ ),+ )+ .limit(1);+ return Boolean(ready);+ }+ return Boolean(next && deliveryReady(next, new Date()));+ }++ async function handleSdkMessage(+ event: ChatSdkMessageCallbackEvent,+ runtimeContext?: RuntimeContext,+ messageOptions: {+ receiptReactionSupported?: boolean;+ slackSlashControl?: boolean;+ } = {},+ ) {+ if (+ event.provider === "discord" &&+ (!runtimeContext ||+ !(await ensureDiscordGatewayRuntimeIsCurrent(+ event.endpointId,+ runtimeContext,+ )))+ ) {+ return;+ }+ if (event.provider === "discord") {+ await options.discordGatewayMessageAdmissionBarrier?.();+ }+ const record = await endpointRecord(event.endpointId);+ if (!record) throw notFound("Chat endpoint not found");+ const messages = [...(event.context?.skipped ?? []), event.message];+ for (const message of messages)+ await processMessage(+ record.endpoint,+ event.thread,+ message,+ message === event.message ? event.trigger : "subscribed_message",+ event.provider === "imessage-photon" ||+ options.deferWebhookProcessing === true,+ null,+ runtimeContext,+ event.providerUpdateId,+ null,+ messageOptions.receiptReactionSupported !== false,+ undefined,+ false,+ false,+ messageOptions.slackSlashControl === true,+ );+ }- if (!linkedTarget) {- const originalIsOpen =- originalDelivery !== null &&- ["received", "processing", "retry"].includes(- originalDelivery.state,- );- const waitForRoot =- originalIsOpen ||- activeDelivery.attempts <= ORPHAN_FOLLOW_UP_MAX_ATTEMPTS;- const resolutionAt = new Date();- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set(- waitForRoot- ? {- state: "retry",- nextAttemptAt: new Date(- resolutionAt.getTime() + ORPHAN_FOLLOW_UP_GRACE_MS,- ),- redactedError: originalIsOpen- ? "Waiting for the original message to finish processing"- : "Waiting briefly for the original message",- updatedAt: resolutionAt,- }- : {- state: "filtered",- nextAttemptAt: null,- redactedError:- "Original message was not admitted to this conversation",- processedAt: resolutionAt,- updatedAt: resolutionAt,+ async function conversationForThread(endpointId: string, threadId: string) {+ const exact = await db+ .select()+ .from(chatConversations)+ .where(+ and(+ eq(chatConversations.endpointId, endpointId),+ eq(chatConversations.externalThreadId, threadId),+ ),+ )+ .orderBy(desc(chatConversations.sessionGeneration))+ .then((rows) => rows[0] ?? null);+ if (exact || !threadId.startsWith("teams:")) return exact;++ // Before Paperclip made Teams route state independent, the adapter+ // embedded the mutable Bot Connector serviceUrl in every thread id. Read+ // those rows by the immutable conversation id so a regional route change+ // continues the same task. New rows use the canonical route-free id.+ if (!teamsConversationId(threadId)) return null;+ return db+ .select()+ .from(chatConversations)+ .where(+ and(+ eq(chatConversations.endpointId, endpointId),+ externalThreadIdentityCondition(+ sql<string>`${chatConversations.externalThreadId}`,+ threadId,+ ),+ ),+ )+ .orderBy(desc(chatConversations.sessionGeneration))+ .then(+ (rows) =>+ rows.find((row) =>+ sameTeamsThreadIdentity(row.externalThreadId, threadId),+ ) ?? null,+ );+ }++ async function recordLifecycleDelivery(+ input: {+ actor?: LifecycleActor;+ isBotMessage?: true;+ endpointId: string;+ threadId: string;+ messageId: string;+ eventKind: "message_updated" | "message_deleted" | "message_restored";+ text: string;+ providerEventId?: string;+ providerMessageSequence?: number | null;+ providerSentAt?: string | null;+ providerUpdateId?: number | null;+ raw?: unknown;+ revision?: string | null;+ admissionDependencyEventId?: string;+ },+ runtimeContext?: RuntimeContext,+ githubSourceMapped = false,+ ) {+ if (!githubSourceMapped && input.threadId.startsWith("github:") && /^[1-9][0-9]*$/.test(input.messageId)) {+ const requests = await db.select({ id: chatDeliveries.id, messageId: sql<string>`${chatDeliveries.normalizedEvent}->'message'->>'providerMessageId'` })+ .from(chatDeliveries).innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatDeliveries.endpointId), eq(chatEndpoints.companyId, chatDeliveries.companyId)))+ .where(and(eq(chatDeliveries.endpointId, input.endpointId), eq(chatEndpoints.provider, "github"),+ inArray(chatDeliveries.eventKind, ["mention", "message", "direct_message"]),+ input.admissionDependencyEventId ? ne(chatDeliveries.providerEventId, input.admissionDependencyEventId) : undefined,+ sql`${chatDeliveries.normalizedEvent}->'message'->>'sourceProviderMessageId' = ${input.messageId}`,+ sql`${chatDeliveries.normalizedEvent}->'conversation'->>'externalThreadId' = ${input.threadId}`));+ if (requests.length) {+ for (const request of requests) await recordLifecycleDelivery({ ...input, messageId: request.messageId,+ providerEventId: `${input.providerEventId ?? `${input.eventKind}:${input.threadId}:${input.messageId}:${input.revision ?? "once"}`}:${request.id}` }, runtimeContext, true);+ return;+ }+ }+ const durableThreadId = durableExternalThreadIdentity(input.threadId);+ const providerEventId =+ input.providerEventId ??+ `${input.eventKind}:${durableThreadId}:${input.messageId}:${input.revision ?? "once"}`;+ const targetProviderEventId = `${durableThreadId}:${input.messageId}`;+ const admission = await db.transaction(async (tx) => {+ const endpoint = await tx+ .select()+ .from(chatEndpoints)+ .where(eq(chatEndpoints.id, input.endpointId))+ .for("update")+ .then((rows) => rows[0] ?? null);+ if (!endpoint) throw notFound("Chat endpoint not found");+ if (+ runtimeContext &&+ !(await runtimeCallbackEndpoint(tx, endpoint.id, runtimeContext, [+ "verifying",+ "active",+ ]))+ )+ return null;+ // A provider has already authenticated this callback. During setup the+ // message can belong to the test conversation, so retain its correction.+ // Paused or unhealthy connections acknowledge late callbacks without+ // mutating the bound task or causing provider retry storms.+ if (endpoint.status !== "verifying" && endpoint.status !== "active")+ return null;+ const reorderWindow = INGRESS_REORDER_WINDOW_MS[endpoint.provider];+ const scheduledAt =+ options.deferWebhookProcessing === true && reorderWindow+ ? (scheduledConversationDrains.get(+ conversationDrainKey(input.endpointId, input.threadId),+ ) ?? Date.now() + reorderWindow)+ : null;+ await notifyChatDeliveryWork(tx);+ const [delivery] = await tx+ .insert(chatDeliveries)+ .values({+ companyId: endpoint.companyId,+ endpointId: input.endpointId,+ providerEventId,+ deduplicationKey: createHash("sha256")+ .update(providerEventId)+ .digest("hex"),+ eventKind: input.eventKind,+ normalizedEvent: {+ providerEventId,+ kind: input.eventKind,+ ...(runtimeContext+ ? {+ runtimeContext: {+ credentialFingerprint: runtimeContext.credentialFingerprint,+ generation: runtimeContext.generation,},- )- .where(- and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.state, "processing"),- ),- );- return;+ }+ : {}),+ ...(input.actor ? { principal: input.actor } : {}),+ conversation: { externalThreadId: input.threadId },+ message: {+ providerMessageId: input.messageId,+ targetProviderEventId,+ ...(input.admissionDependencyEventId ? { admissionDependencyEventId: input.admissionDependencyEventId } : {}),+ ...(endpoint.provider === "github" && input.isBotMessage === true+ ? { isBotMessage: true }+ : {}),+ providerMessageSequence: input.providerMessageSequence ?? null,+ providerSentAt: input.providerSentAt ?? null,+ providerUpdateId: input.providerUpdateId ?? null,+ text: input.text,+ },+ },+ state: "received",+ nextAttemptAt: scheduledAt ? new Date(scheduledAt) : null,+ })+ .onConflictDoNothing()+ .returning();+ if (delivery) return { delivery, endpoint, scheduledAt };+ const existing = await tx+ .select()+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.endpointId, input.endpointId),+ eq(chatDeliveries.providerEventId, providerEventId),+ ),+ )+ .then((rows) => rows[0] ?? null);+ return existing ? { delivery: existing, endpoint, scheduledAt } : null;+ });+ if (admission) {+ // Lifecycle callbacks can carry a new regional Bot Connector route. Keep+ // that provider-authenticated route current even when processing is+ // deferred, but deliberately omit the raw activity here. Lifecycle+ // callbacks never populate the adapter's user cache; the admitted root+ // message already established the principal metadata they must match.+ await recordCurrentMicrosoftTeamsRoute(+ admission.endpoint,+ runtimeContext,+ input.threadId,+ input.raw,+ false,+ );+ }+ if (+ !admission ||+ admission.delivery.state === "processed" ||+ admission.delivery.state === "filtered" ||+ admission.delivery.state === "failed"+ )+ return;+ if (options.deferWebhookProcessing === true) {+ scheduleConversationDrain(+ input.endpointId,+ input.threadId,+ admission.scheduledAt ?? Date.now(),+ );+ return;+ }+ await drainConversationDeliveries(input.endpointId, input.threadId);+ }++ function lifecycleMessageFromDelivery(delivery: DeliveryRow): {+ actor: LifecycleActor | null;+ isBotMessage: boolean;+ messageId: string;+ providerSentAt: string | null;+ targetProviderEventId: string;+ text: string;+ threadId: string;+ } | null {+ if (+ delivery.eventKind !== "message_updated" &&+ delivery.eventKind !== "message_deleted" &&+ delivery.eventKind !== "message_restored"+ )+ return null;+ const normalized = delivery.normalizedEvent as {+ principal?: {+ displayName?: unknown;+ externalId?: unknown;+ handle?: unknown;+ };+ message?: {+ isBotMessage?: unknown;+ providerMessageId?: unknown;+ providerSentAt?: unknown;+ targetProviderEventId?: unknown;+ text?: unknown;+ };+ };+ const messageId = normalized.message?.providerMessageId;+ const targetProviderEventId = normalized.message?.targetProviderEventId;+ const providerSentAt = normalized.message?.providerSentAt;+ const text = normalized.message?.text;+ const threadId = normalizedDeliveryThreadId(delivery);+ const externalId = normalized.principal?.externalId;+ const actor =+ typeof externalId === "string" && externalId+ ? {+ externalId,+ displayName:+ typeof normalized.principal?.displayName === "string"+ ? normalized.principal.displayName+ : externalId,+ handle:+ typeof normalized.principal?.handle === "string"+ ? normalized.principal.handle+ : externalId,+ }+ : null;+ return typeof messageId === "string" &&+ typeof targetProviderEventId === "string" &&+ typeof text === "string" &&+ threadId !== null+ ? {+ actor,+ isBotMessage: normalized.message?.isBotMessage === true,+ messageId,+ providerSentAt:+ typeof providerSentAt === "string" ? providerSentAt : null,+ targetProviderEventId,+ text,+ threadId,}+ : null;+ }- const currentConversation = await tx- .select()- .from(chatConversations)- .where(- and(- eq(chatConversations.companyId, currentEndpoint.companyId),- eq(chatConversations.endpointId, currentEndpoint.id),- eq(chatConversations.id, linkedTarget.conversationId),- ),- )- .for("update")- .then((rows) => rows[0] ?? null);- const currentResource =- currentConversation?.resourceId &&- !currentConversation.isDirectMessage- ? await tx- .select()- .from(chatEndpointResources)- .where(- and(- eq(- chatEndpointResources.companyId,- currentEndpoint.companyId,- ),- eq(chatEndpointResources.endpointId, currentEndpoint.id),- eq(- chatEndpointResources.id,- currentConversation.resourceId,- ),- ),- )- .for("update")- .then((rows) => rows[0] ?? null)- : null;- const retainSourceInvalidation = async (- principalId: string | null,- reason: string,- ): Promise<boolean> => {- if (- !currentConversation ||- activeDelivery.eventKind !== "message_updated"- )- return false;- const invalidatedAt = new Date();- // Provider authentication proves the exact source changed. The- // editor's current Paperclip rights govern admitting new content,- // not whether a later regrant can resurrect the stale old source.- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- state: "processed",- conversationId: currentConversation.id,- principalId,- normalizedEvent: {- providerEventId:- activeDelivery.normalizedEvent.providerEventId ??- activeDelivery.providerEventId,- kind: activeDelivery.eventKind,- runtimeContext: {- generation: admittedRuntimeContext.generation,- credentialFingerprint:- admittedRuntimeContext.credentialFingerprint,- },- conversation: { externalThreadId: lifecycle.threadId },- message: {- providerMessageId: lifecycle.messageId,- targetProviderEventId: lifecycle.targetProviderEventId,- providerSentAt: lifecycle.providerSentAt,- },- filtering: { contentRetained: false },- },- nextAttemptAt: null,- processedAt: invalidatedAt,- redactedError: reason,- updatedAt: invalidatedAt,- })- .where(- and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.state, "processing"),- ),- );- return true;- };- if (- githubBotSourceEdit &&- (await retainSourceInvalidation(- null,- "Provider bot edit invalidated an existing source without admitting bot content",- ))- )- return;+ async function processLifecycleDelivery(+ endpoint: EndpointRow,+ candidate: DeliveryRow,+ ): Promise<void> {+ const lifecycle = lifecycleMessageFromDelivery(candidate);+ if (!lifecycle) {+ await db.transaction(async (tx) => {+ await notifyChatDeliveryWork(tx);+ return tx+ .update(chatDeliveries)+ .set({+ state: "failed",+ redactedError: "Normalized lifecycle delivery is incomplete",+ updatedAt: new Date(),+ })+ .where(eq(chatDeliveries.id, candidate.id));+ });+ return;+ }- let lifecyclePrincipalId: string | null = null;- const requiresLifecycleActorAuthorization =- (activeDelivery.eventKind === "message_updated" ||- activeDelivery.eventKind === "message_restored") &&- (lifecycle.actor !== null ||- currentEndpoint.provider === "github" ||- currentEndpoint.provider === "telegram" ||- currentEndpoint.provider === "microsoft-teams");- if (requiresLifecycleActorAuthorization) {- const lifecyclePrincipal = lifecycle.actor- ? await tx- .select({- id: chatExternalPrincipals.id,- isBot: chatExternalPrincipals.isBot,- kind: chatExternalPrincipals.kind,- })- .from(chatExternalPrincipals)- .where(- and(- eq(- chatExternalPrincipals.companyId,- currentEndpoint.companyId,- ),- eq(- chatExternalPrincipals.provider,- currentEndpoint.provider,- ),- eq(- chatExternalPrincipals.providerAccountId,- currentEndpoint.providerAccountId ?? "unknown",- ),- eq(- chatExternalPrincipals.externalId,- lifecycle.actor.externalId,- ),- ),- )- .for("update")- .then((rows) => rows[0] ?? null)- : null;- const authorization =- lifecyclePrincipal &&- lifecyclePrincipal.kind === "user" &&- !lifecyclePrincipal.isBot- ? await lockCurrentPrincipalAuthorization(- tx,- currentEndpoint,- lifecyclePrincipal.id,- )- : null;- const authorizedPrincipalId = authorization?.allowed- ? (lifecyclePrincipal?.id ?? null)- : null;- if (!authorizedPrincipalId) {- if (- await retainSourceInvalidation(- lifecyclePrincipal?.id ?? null,- "Provider edit invalidation retained without admitting content from an unauthorized actor",- )+ const now = new Date();+ const staleBefore = new Date(now.getTime() - DELIVERY_PROCESSING_STALE_MS);+ const claimConditions = [+ eq(chatDeliveries.id, candidate.id),+ eq(chatDeliveries.state, candidate.state),+ ];+ if (candidate.state === "processing")+ claimConditions.push(lte(chatDeliveries.updatedAt, staleBefore));+ const [activeDelivery] = await db.transaction(async (tx) => {+ await notifyChatDeliveryWork(tx);+ return tx+ .update(chatDeliveries)+ .set({+ state: "processing",+ attempts: candidate.attempts + 1,+ nextAttemptAt: null,+ redactedError: null,+ updatedAt: now,+ })+ .where(and(...claimConditions))+ .returning();+ });+ if (!activeDelivery) return;++ try {+ await db.transaction(async (tx) => {+ const admittedRuntimeContext = lifecycleRuntimeFence(activeDelivery);+ const currentEndpoint = admittedRuntimeContext+ ? await runtimeCallbackEndpoint(+ tx,+ endpoint.id,+ admittedRuntimeContext,+ ["verifying", "active"],)- return;+ : null;+ if (!admittedRuntimeContext || !currentEndpoint) {+ const filteredAt = new Date();+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ state: "filtered",+ nextAttemptAt: null,+ processedAt: filteredAt,+ redactedError:+ "Message lifecycle callback belonged to a superseded runtime",+ updatedAt: filteredAt,+ })+ .where(+ and(+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.state, "processing"),+ ),+ );+ return;+ }+ let githubBotSourceEdit = false;+ if (+ currentEndpoint.provider === "github" &&+ activeDelivery.eventKind === "message_updated"+ ) {+ // Bot callbacks can arrive before the outbound publication commits+ // its message link. The Boolean comes only from GitHub's verified+ // sender/comment-author type, never from comment text. Legacy rows+ // lack it, so also recognize exact already-published outbound links.+ const linkedMessages = await tx+ .select({ direction: chatMessageLinks.direction })+ .from(chatMessageLinks)+ .innerJoin(+ chatConversations,+ and(+ eq(chatConversations.id, chatMessageLinks.conversationId),+ eq(chatConversations.companyId, chatMessageLinks.companyId),+ eq(chatConversations.endpointId, chatMessageLinks.endpointId),+ ),+ )+ .where(+ and(+ eq(chatMessageLinks.companyId, currentEndpoint.companyId),+ eq(chatMessageLinks.endpointId, currentEndpoint.id),+ eq(chatMessageLinks.providerMessageId, lifecycle.messageId),+ eq(chatConversations.externalThreadId, lifecycle.threadId),+ ),+ );+ const outbound = linkedMessages.some(+ (row) => row.direction === "outbound",+ );+ // A bot editor can change an already-admitted human source. That+ // authenticated change revokes the old source, but never admits the+ // bot's new content. Unknown/self/outbound updates remain suppressed.+ githubBotSourceEdit =+ lifecycle.isBotMessage &&+ !outbound &&+ linkedMessages.some((row) => row.direction === "inbound");+ if (outbound || (lifecycle.isBotMessage && !githubBotSourceEdit)) {const filteredAt = new Date();await notifyChatDeliveryWork(tx);await tx.update(chatDeliveries).set({- principalId: lifecyclePrincipal?.id ?? null,state: "filtered",+ principalId: null,+ nextAttemptAt: null,+ processedAt: filteredAt,+ updatedAt: filteredAt,+ redactedError:+ "Provider bot or outbound message updates do not create inbound work",normalizedEvent: {providerEventId:activeDelivery.normalizedEvent.providerEventId ??@@ -13950,11 +10041,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {},filtering: { contentRetained: false },},- nextAttemptAt: null,- processedAt: filteredAt,- redactedError:- "External message actor is no longer authorized for lifecycle events",- updatedAt: filteredAt,}).where(and(@@ -13964,676 +10050,587 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {);return;}- lifecyclePrincipalId = authorizedPrincipalId;}-- const destinationAllowed =- currentConversation !== null &&- ["active", "waiting"].includes(currentConversation.state) &&- (currentConversation.isDirectMessage- ? currentEndpoint.allowDirectMessages- : nonDirectDestinationAllowed(currentEndpoint, currentResource));- if (!destinationAllowed) {- const filteredAt = new Date();- // A verified deletion or authorized edit still revokes the exactly- // linked source while reach is disabled. Re-enabling access must not- // revive stale files. Keep only the invalidation, never the new- // content: no task comment, attachment import or wake is allowed.- const retainInvalidation =- currentConversation !== null &&- (activeDelivery.eventKind === "message_deleted" ||- (activeDelivery.eventKind === "message_updated" &&- lifecyclePrincipalId !== null));- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- state: retainInvalidation ? "processed" : "filtered",- ...(retainInvalidation- ? {- conversationId: currentConversation.id,- principalId: lifecyclePrincipalId,- }- : {}),- normalizedEvent: {- providerEventId:- activeDelivery.normalizedEvent.providerEventId ??- activeDelivery.providerEventId,- kind: activeDelivery.eventKind,- ...(retainInvalidation- ? {- runtimeContext: {- generation: admittedRuntimeContext.generation,- credentialFingerprint:- admittedRuntimeContext.credentialFingerprint,- },- }- : {}),- conversation: { externalThreadId: lifecycle.threadId },- message: {- providerMessageId: lifecycle.messageId,- targetProviderEventId: lifecycle.targetProviderEventId,- ...(retainInvalidation- ? { providerSentAt: lifecycle.providerSentAt }- : {}),- },- filtering: { contentRetained: false },- },- nextAttemptAt: null,- processedAt: filteredAt,- redactedError: retainInvalidation- ? activeDelivery.eventKind === "message_deleted"- ? "Provider deletion retained without task content while destination access is disabled"- : "Provider edit invalidation retained without task content while destination access is disabled"- : "Destination is no longer enabled for message lifecycle events",- updatedAt: filteredAt,+ if (+ activeDelivery.eventKind === "message_updated" ||+ activeDelivery.eventKind === "message_deleted" ||+ activeDelivery.eventKind === "message_restored"+ ) {+ const latestDeleteTransition = await tx+ .select({+ eventKind: chatDeliveries.eventKind,+ providerSentAt: sql<+ string | null+ >`nullif(${chatDeliveries.normalizedEvent}->'message'->>'providerSentAt', '')`,})+ .from(chatDeliveries).where(and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.state, "processing"),+ eq(chatDeliveries.companyId, activeDelivery.companyId),+ eq(chatDeliveries.endpointId, endpoint.id),+ inArray(chatDeliveries.eventKind, [+ "message_deleted",+ "message_restored",+ ]),+ eq(chatDeliveries.state, "processed"),+ externalThreadIdentityCondition(+ sql<string>`${chatDeliveries.normalizedEvent}->'conversation'->>'externalThreadId'`,+ lifecycle.threadId,+ ),+ sql`${chatDeliveries.normalizedEvent}->'message'->>'targetProviderEventId' = ${lifecycle.targetProviderEventId}`,),- );- return;- }-- await issuesSvc.addComment(- linkedTarget.issueId,- lifecycle.text,- {},- { authorType: "system" },- tx,- );- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- conversationId: linkedTarget.conversationId,- principalId: lifecyclePrincipalId,- state: "processed",- processedAt: new Date(),- redactedError: null,- updatedAt: new Date(),- })+ )+ .orderBy(+ desc(+ sql`coalesce(nullif(${chatDeliveries.normalizedEvent}->'message'->>'providerSentAt', '')::timestamptz, ${chatDeliveries.processedAt})`,+ ),+ desc(sql`case ${chatDeliveries.eventKind}+ when 'message_restored' then 2+ when 'message_deleted' then 1+ else 0+ end`),+ desc(chatDeliveries.processedAt),+ desc(chatDeliveries.id),+ )+ .limit(1)+ .then((rows) => rows[0] ?? null);+ const latestTransitionAt = latestDeleteTransition?.providerSentAt+ ? Date.parse(latestDeleteTransition.providerSentAt)+ : Number.NaN;+ const incomingTransitionAt = lifecycle.providerSentAt+ ? Date.parse(lifecycle.providerSentAt)+ : Number.NaN;+ const incomingTransitionIsStale =+ latestDeleteTransition !== null &&+ Number.isFinite(latestTransitionAt) &&+ Number.isFinite(incomingTransitionAt) &&+ (incomingTransitionAt < latestTransitionAt ||+ (incomingTransitionAt === latestTransitionAt &&+ activeDelivery.eventKind === "message_deleted" &&+ latestDeleteTransition.eventKind === "message_restored"));+ const editTargetsDeletedMessage =+ activeDelivery.eventKind === "message_updated" &&+ latestDeleteTransition?.eventKind === "message_deleted";+ const editPredatesRestore =+ activeDelivery.eventKind === "message_updated" &&+ latestDeleteTransition?.eventKind === "message_restored" &&+ Number.isFinite(latestTransitionAt) &&+ Number.isFinite(incomingTransitionAt) &&+ incomingTransitionAt < latestTransitionAt;+ if (+ incomingTransitionIsStale ||+ editTargetsDeletedMessage ||+ editPredatesRestore+ ) {+ const filteredAt = new Date();+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ state: "filtered",+ normalizedEvent: {+ providerEventId:+ activeDelivery.normalizedEvent.providerEventId ??+ activeDelivery.providerEventId,+ kind: activeDelivery.eventKind,+ conversation: { externalThreadId: lifecycle.threadId },+ message: {+ providerMessageId: lifecycle.messageId,+ targetProviderEventId: lifecycle.targetProviderEventId,+ },+ filtering: { contentRetained: false },+ },+ principalId: null,+ nextAttemptAt: null,+ processedAt: filteredAt,+ redactedError: editTargetsDeletedMessage+ ? "Message edit arrived after the provider message was deleted"+ : "Message lifecycle callback was older than the current provider state",+ updatedAt: filteredAt,+ })+ .where(+ and(+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.state, "processing"),+ ),+ );+ return;+ }+ }+ const originalDelivery = await tx+ .select({ state: chatDeliveries.state })+ .from(chatDeliveries).where(and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.state, "processing"),+ eq(chatDeliveries.endpointId, endpoint.id),+ eq(+ chatDeliveries.providerEventId,+ lifecycle.targetProviderEventId,+ ),),- );- });- } catch (error) {- const terminal = activeDelivery.attempts >= 5;- await db.transaction(async (tx) => {- await notifyChatDeliveryWork(tx);- return tx- .update(chatDeliveries)- .set({- state: terminal ? "failed" : "retry",- nextAttemptAt: terminal- ? null- : new Date(- Date.now() +- Math.min(60_000, 1000 * 2 ** activeDelivery.attempts),- ),- redactedError: redactError(error),- updatedAt: new Date(),+ )+ .then((rows) => rows[0] ?? null);+ const linkedTargets = await tx+ .select({+ conversationId: chatConversations.id,+ externalThreadId: chatConversations.externalThreadId,+ issueId: chatConversations.issueId,})- .where(+ .from(chatMessageLinks)+ .innerJoin(+ chatConversations,and(- eq(chatDeliveries.id, activeDelivery.id),- eq(chatDeliveries.state, "processing"),+ eq(chatConversations.companyId, chatMessageLinks.companyId),+ eq(chatConversations.id, chatMessageLinks.conversationId),),- );- });- throw error;- }- }-- async function handleMessageUpdated(- event: ChatSdkMessageUpdatedCallbackEvent,- runtimeContext: RuntimeContext,- ) {- if (- event.provider === "discord" &&- !(await ensureDiscordGatewayRuntimeIsCurrent(- event.endpointId,- runtimeContext,- ))- ) {- return;- }- const text = `An external message was edited:\n\n${event.message.text.slice(0, MAX_INBOUND_TEXT)}`;- const telegramRich =- event.provider === "telegram"- ? normalizeTelegramRichMessage(event.message.raw)- : null;- await recordLifecycleDelivery(- {- actor: lifecycleActorFromAuthor(- event.provider,- event.message.author,- event.message.raw,- ),- endpointId: event.endpointId,- threadId: event.thread.id,- messageId: event.message.id,- eventKind: "message_updated",- text,- providerMessageSequence:- event.provider === "telegram"- ? telegramMessageSequence(event.message.raw)- : null,- providerSentAt:- (- event.message.metadata.editedAt ?? event.message.metadata.dateSent- )?.toISOString() ?? null,- raw: event.message.raw,- revision: `${event.message.metadata.editedAt?.toISOString() ?? "unknown"}:${createHash("sha256").update(event.message.text).digest("hex")}${event.provider === "slack" ? `:${slackLifecycleFilesDigest(event.message.raw)}` : event.provider === "discord" ? `:${discordLifecycleFilesDigest(event.message.raw)}` : telegramRich ? `:${telegramRich.mediaDigest}` : ""}`,- },- runtimeContext,- );- }-- async function handleMessageDeleted(- event: ChatSdkCallbackEvent<MessageDeletedEvent>,- runtimeContext: RuntimeContext,- ) {- if (- event.provider === "discord" &&- !(await ensureDiscordGatewayRuntimeIsCurrent(- event.endpointId,- runtimeContext,- ))- ) {- return;- }- await recordLifecycleDelivery(- {- endpointId: event.endpointId,- threadId: event.event.threadId,- messageId: event.event.messageId,- eventKind: "message_deleted",- text: "An external message in this conversation was deleted.",- providerSentAt: event.event.deletedAt?.toISOString() ?? null,- raw: event.event.raw,- revision: event.event.deletedAt?.toISOString() ?? null,- },- runtimeContext,- );- }-- function reactionConversationThreadCondition(- provider: ChatProvider,- threadId: string,- ): SQL | undefined {- const exact = externalThreadIdentityCondition(- sql<string>`${chatConversations.externalThreadId}`,- threadId,- );- const slackDmChannel =- provider === "slack" ? slackThreadChannelId(threadId) : null;- return slackDmChannel && /^D[A-Z0-9-]*$/i.test(slackDmChannel)- ? or(- exact,- and(- eq(chatConversations.isDirectMessage, true),- eq(chatConversations.externalThreadId, `slack:${slackDmChannel}:`),- ),- )- : exact;- }-- async function reactionConversationForMessage(- database: DbOrTransaction,- endpoint: EndpointRow,- threadId: string,- providerMessageId: string,- direction?: "outbound",- ): Promise<ConversationRow | null> {- return database- .select({ conversation: chatConversations })- .from(chatMessageLinks)- .innerJoin(- chatConversations,- and(- eq(chatConversations.companyId, chatMessageLinks.companyId),- eq(chatConversations.endpointId, chatMessageLinks.endpointId),- eq(chatConversations.id, chatMessageLinks.conversationId),- ),- )- .where(- and(- eq(chatMessageLinks.companyId, endpoint.companyId),- eq(chatMessageLinks.endpointId, endpoint.id),- eq(chatMessageLinks.providerMessageId, providerMessageId),- direction ? eq(chatMessageLinks.direction, direction) : undefined,- reactionConversationThreadCondition(endpoint.provider, threadId),- ),- )- .orderBy(desc(chatConversations.sessionGeneration))- .limit(1)- .then((rows) => rows[0]?.conversation ?? null);- }-- async function lockReactionConversationForMessage(- tx: DbTransaction,- endpoint: EndpointRow,- threadId: string,- providerMessageId: string,- direction?: "outbound",- ): Promise<ConversationRow | null> {- const candidate = await reactionConversationForMessage(- tx,- endpoint,- threadId,- providerMessageId,- direction,- );- if (!candidate) return null;- const current = await tx- .select()- .from(chatConversations)- .where(- and(- eq(chatConversations.companyId, endpoint.companyId),- eq(chatConversations.endpointId, endpoint.id),- eq(chatConversations.id, candidate.id),- ),- )- // Publication settlement inserts the outbound message link before it- // updates the endpoint. NO KEY UPDATE serializes state changes while- // remaining compatible with that link's conversation FK KEY SHARE.- .for("no key update")- .then((rows) => rows[0] ?? null);- if (- !current ||- !(current.isDirectMessage- ? ["active", "waiting", "completed"].includes(current.state)- : ["active", "waiting"].includes(current.state))- ) {- return null;- }- const linkStillExists = await tx- .select({ id: chatMessageLinks.id })- .from(chatMessageLinks)- .where(- and(- eq(chatMessageLinks.companyId, endpoint.companyId),- eq(chatMessageLinks.endpointId, endpoint.id),- eq(chatMessageLinks.conversationId, current.id),- eq(chatMessageLinks.providerMessageId, providerMessageId),- direction ? eq(chatMessageLinks.direction, direction) : undefined,- ),- )- .limit(1)- .then((rows) => rows.length > 0);- return linkStillExists ? current : null;- }-- async function streamingReactionConversation(- database: DbOrTransaction,- endpoint: EndpointRow,- threadId: string,- ): Promise<ConversationRow | null> {- const candidates = await database- .selectDistinct({- conversation: chatConversations,- sessionGeneration: chatConversations.sessionGeneration,- })- .from(chatConversations)- .innerJoin(- chatPublications,- and(- eq(chatPublications.companyId, chatConversations.companyId),- eq(chatPublications.endpointId, chatConversations.endpointId),- eq(chatPublications.conversationId, chatConversations.id),- ),- )- .where(- and(- eq(chatConversations.companyId, endpoint.companyId),- eq(chatConversations.endpointId, endpoint.id),- or(- inArray(chatConversations.state, ["active", "waiting"]),+ )+ .where(and(- eq(chatConversations.isDirectMessage, true),- eq(chatConversations.state, "completed"),+ eq(chatMessageLinks.endpointId, endpoint.id),+ eq(chatMessageLinks.providerMessageId, lifecycle.messageId),+ eq(chatMessageLinks.direction, "inbound"),),- ),- reactionConversationThreadCondition(endpoint.provider, threadId),- eq(chatPublications.state, "streaming"),- ),- )- .orderBy(desc(chatConversations.sessionGeneration))- .limit(2);- if (candidates.length !== 1) return null;- return candidates[0]!.conversation;- }+ )+ .orderBy(desc(chatConversations.sessionGeneration))+ .then((rows) => rows);+ const linkedTarget =+ linkedTargets.find((candidate) =>+ currentEndpoint.provider === "microsoft-teams"+ ? sameTeamsThreadIdentity(+ candidate.externalThreadId,+ lifecycle.threadId,+ )+ : candidate.externalThreadId === lifecycle.threadId,+ ) ?? null;++ if (!linkedTarget) {+ const originalIsOpen =+ originalDelivery !== null &&+ ["received", "processing", "retry"].includes(+ originalDelivery.state,+ );+ const waitForRoot =+ originalIsOpen ||+ activeDelivery.attempts <= ORPHAN_FOLLOW_UP_MAX_ATTEMPTS;+ const resolutionAt = new Date();+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set(+ waitForRoot+ ? {+ state: "retry",+ nextAttemptAt: new Date(+ resolutionAt.getTime() + ORPHAN_FOLLOW_UP_GRACE_MS,+ ),+ redactedError: originalIsOpen+ ? "Waiting for the original message to finish processing"+ : "Waiting briefly for the original message",+ updatedAt: resolutionAt,+ }+ : {+ state: "filtered",+ nextAttemptAt: null,+ redactedError:+ "Original message was not admitted to this conversation",+ processedAt: resolutionAt,+ updatedAt: resolutionAt,+ },+ )+ .where(+ and(+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.state, "processing"),+ ),+ );+ return;+ }- async function lockStreamingReactionConversation(- tx: DbTransaction,- endpoint: EndpointRow,- threadId: string,- ): Promise<ConversationRow | null> {- const candidate = await streamingReactionConversation(- tx,- endpoint,- threadId,- );- if (!candidate) return null;- const current = await tx- .select()- .from(chatConversations)- .where(- and(- eq(chatConversations.companyId, endpoint.companyId),- eq(chatConversations.endpointId, endpoint.id),- eq(chatConversations.id, candidate.id),- or(- inArray(chatConversations.state, ["active", "waiting"]),+ const currentConversation = await tx+ .select()+ .from(chatConversations)+ .where(and(- eq(chatConversations.isDirectMessage, true),- eq(chatConversations.state, "completed"),+ eq(chatConversations.companyId, currentEndpoint.companyId),+ eq(chatConversations.endpointId, currentEndpoint.id),+ eq(chatConversations.id, linkedTarget.conversationId),),- ),- ),- )- // Keep the same lock strength/order as the exact-link path above so an- // in-flight message-link insert cannot deadlock reaction admission.- .for("no key update")- .then((rows) => rows[0] ?? null);- if (!current) return null;- const stillStreaming = await tx- .select({ id: chatPublications.id })- .from(chatPublications)- .where(- and(- eq(chatPublications.companyId, endpoint.companyId),- eq(chatPublications.endpointId, endpoint.id),- eq(chatPublications.conversationId, current.id),- eq(chatPublications.state, "streaming"),- ),- )- .limit(1)- .then((rows) => rows.length > 0);- return stillStreaming ? current : null;- }+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ const currentResource =+ currentConversation?.resourceId &&+ !currentConversation.isDirectMessage+ ? await tx+ .select()+ .from(chatEndpointResources)+ .where(+ and(+ eq(+ chatEndpointResources.companyId,+ currentEndpoint.companyId,+ ),+ eq(chatEndpointResources.endpointId, currentEndpoint.id),+ eq(+ chatEndpointResources.id,+ currentConversation.resourceId,+ ),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null)+ : null;+ const retainSourceInvalidation = async (+ principalId: string | null,+ reason: string,+ ): Promise<boolean> => {+ if (+ !currentConversation ||+ activeDelivery.eventKind !== "message_updated"+ )+ return false;+ const invalidatedAt = new Date();+ // Provider authentication proves the exact source changed. The+ // editor's current Paperclip rights govern admitting new content,+ // not whether a later regrant can resurrect the stale old source.+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ state: "processed",+ conversationId: currentConversation.id,+ principalId,+ normalizedEvent: {+ providerEventId:+ activeDelivery.normalizedEvent.providerEventId ??+ activeDelivery.providerEventId,+ kind: activeDelivery.eventKind,+ runtimeContext: {+ generation: admittedRuntimeContext.generation,+ credentialFingerprint:+ admittedRuntimeContext.credentialFingerprint,+ },+ conversation: { externalThreadId: lifecycle.threadId },+ message: {+ providerMessageId: lifecycle.messageId,+ targetProviderEventId: lifecycle.targetProviderEventId,+ providerSentAt: lifecycle.providerSentAt,+ },+ filtering: { contentRetained: false },+ },+ nextAttemptAt: null,+ processedAt: invalidatedAt,+ redactedError: reason,+ updatedAt: invalidatedAt,+ })+ .where(+ and(+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.state, "processing"),+ ),+ );+ return true;+ };+ if (+ githubBotSourceEdit &&+ (await retainSourceInvalidation(+ null,+ "Provider bot edit invalidated an existing source without admitting bot content",+ ))+ )+ return;- async function authorizeReactionConversation(- tx: DbTransaction,- endpoint: EndpointRow,- conversation: ConversationRow,- principalId: string,- ): Promise<boolean> {- const resource =- conversation.resourceId && !conversation.isDirectMessage- ? await tx- .select()- .from(chatEndpointResources)+ let lifecyclePrincipalId: string | null = null;+ const requiresLifecycleActorAuthorization =+ (activeDelivery.eventKind === "message_updated" ||+ activeDelivery.eventKind === "message_restored") &&+ (lifecycle.actor !== null ||+ currentEndpoint.provider === "github" ||+ currentEndpoint.provider === "telegram" ||+ currentEndpoint.provider === "microsoft-teams");+ if (requiresLifecycleActorAuthorization) {+ const lifecyclePrincipal = lifecycle.actor+ ? await tx+ .select({+ id: chatExternalPrincipals.id,+ isBot: chatExternalPrincipals.isBot,+ kind: chatExternalPrincipals.kind,+ })+ .from(chatExternalPrincipals)+ .where(+ and(+ eq(+ chatExternalPrincipals.companyId,+ currentEndpoint.companyId,+ ),+ eq(+ chatExternalPrincipals.provider,+ currentEndpoint.provider,+ ),+ eq(+ chatExternalPrincipals.providerAccountId,+ currentEndpoint.providerAccountId ?? "unknown",+ ),+ eq(+ chatExternalPrincipals.externalId,+ lifecycle.actor.externalId,+ ),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null)+ : null;+ const authorization =+ lifecyclePrincipal &&+ lifecyclePrincipal.kind === "user" &&+ !lifecyclePrincipal.isBot+ ? await lockCurrentPrincipalAuthorization(+ tx,+ currentEndpoint,+ lifecyclePrincipal.id,+ )+ : null;+ const authorizedPrincipalId = authorization?.allowed+ ? (lifecyclePrincipal?.id ?? null)+ : null;+ if (!authorizedPrincipalId) {+ if (+ await retainSourceInvalidation(+ lifecyclePrincipal?.id ?? null,+ "Provider edit invalidation retained without admitting content from an unauthorized actor",+ )+ )+ return;+ const filteredAt = new Date();+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ principalId: lifecyclePrincipal?.id ?? null,+ state: "filtered",+ normalizedEvent: {+ providerEventId:+ activeDelivery.normalizedEvent.providerEventId ??+ activeDelivery.providerEventId,+ kind: activeDelivery.eventKind,+ conversation: { externalThreadId: lifecycle.threadId },+ message: {+ providerMessageId: lifecycle.messageId,+ targetProviderEventId: lifecycle.targetProviderEventId,+ },+ filtering: { contentRetained: false },+ },+ nextAttemptAt: null,+ processedAt: filteredAt,+ redactedError:+ "External message actor is no longer authorized for lifecycle events",+ updatedAt: filteredAt,+ })+ .where(+ and(+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.state, "processing"),+ ),+ );+ return;+ }+ lifecyclePrincipalId = authorizedPrincipalId;+ }++ const destinationAllowed =+ currentConversation !== null &&+ ["active", "waiting"].includes(currentConversation.state) &&+ (currentConversation.isDirectMessage+ ? currentEndpoint.allowDirectMessages+ : nonDirectDestinationAllowed(currentEndpoint, currentResource));+ if (!destinationAllowed) {+ const filteredAt = new Date();+ // A verified deletion or authorized edit still revokes the exactly+ // linked source while reach is disabled. Re-enabling access must not+ // revive stale files. Keep only the invalidation, never the new+ // content: no task comment, attachment import or wake is allowed.+ const retainInvalidation =+ currentConversation !== null &&+ (activeDelivery.eventKind === "message_deleted" ||+ (activeDelivery.eventKind === "message_updated" &&+ lifecyclePrincipalId !== null));+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ state: retainInvalidation ? "processed" : "filtered",+ ...(retainInvalidation+ ? {+ conversationId: currentConversation.id,+ principalId: lifecyclePrincipalId,+ }+ : {}),+ normalizedEvent: {+ providerEventId:+ activeDelivery.normalizedEvent.providerEventId ??+ activeDelivery.providerEventId,+ kind: activeDelivery.eventKind,+ ...(retainInvalidation+ ? {+ runtimeContext: {+ generation: admittedRuntimeContext.generation,+ credentialFingerprint:+ admittedRuntimeContext.credentialFingerprint,+ },+ }+ : {}),+ conversation: { externalThreadId: lifecycle.threadId },+ message: {+ providerMessageId: lifecycle.messageId,+ targetProviderEventId: lifecycle.targetProviderEventId,+ ...(retainInvalidation+ ? { providerSentAt: lifecycle.providerSentAt }+ : {}),+ },+ filtering: { contentRetained: false },+ },+ nextAttemptAt: null,+ processedAt: filteredAt,+ redactedError: retainInvalidation+ ? activeDelivery.eventKind === "message_deleted"+ ? "Provider deletion retained without task content while destination access is disabled"+ : "Provider edit invalidation retained without task content while destination access is disabled"+ : "Destination is no longer enabled for message lifecycle events",+ updatedAt: filteredAt,+ }).where(and(- eq(chatEndpointResources.companyId, endpoint.companyId),- eq(chatEndpointResources.endpointId, endpoint.id),- eq(chatEndpointResources.id, conversation.resourceId),+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.state, "processing"),),- )- .for("update")- .then((rows) => rows[0] ?? null)- : null;- const destinationAllowed = conversation.isDirectMessage- ? endpoint.allowDirectMessages- : nonDirectDestinationAllowed(endpoint, resource);- if (!destinationAllowed) return false;- return (await lockCurrentPrincipalAuthorization(tx, endpoint, principalId))- .allowed;- }-- async function handleReaction(- event: ChatSdkCallbackEvent<ReactionEvent>,- runtimeContext: RuntimeContext,- ) {- const record = await runtimeCallbackRecord(- event.endpointId,- runtimeContext,- ["active"],- );- if (- !record ||- record.endpoint.status !== "active" ||- record.endpoint.provider !== event.provider ||- record.endpoint.capabilities.reactions !== true ||- event.event.user.isMe ||- event.event.user.isBot === true ||- event.event.user.isSystem- ) {- return;- }- // A DM can have a newer task generation while this reaction still belongs- // to an older linked message. Resolve its exact lineage before choosing a- // generation; never attach it to the latest task merely sharing the chat.- // A just-sent provider message can be visible before its publication/link- // transaction commits. Only that exact thread's streaming publication is- // enough evidence to stage an otherwise-unbound reaction for replay.- let conversation = await reactionConversationForMessage(- db,- record.endpoint,- event.event.threadId,- event.event.messageId,- );- await options.reactionLinkPreflightBarrier?.();- const plausibleStreamingConversation = conversation- ? null- : await streamingReactionConversation(- db,- record.endpoint,- event.event.threadId,- );- if (!conversation && !plausibleStreamingConversation) {- // Settlement can commit between the first exact-link lookup and the- // streaming-publication lookup. Recheck the durable link before treating- // the callback as an arbitrary unknown message.- conversation = await reactionConversationForMessage(- db,- record.endpoint,- event.event.threadId,- event.event.messageId,- );- if (!conversation) return;- }+ );+ return;+ }- const principal = await ensurePrincipal(- record.endpoint,- event.event.user,- event.event.raw,- );- let rawFingerprint: string;- try {- rawFingerprint = createHash("sha256")- .update(JSON.stringify(event.event.raw ?? null))- .digest("hex")- .slice(0, 24);- } catch {- rawFingerprint = "unavailable";- }- const eventKind: ChatEventKind = event.event.added- ? "reaction_added"- : "reaction_removed";- const providerEventId = [- eventKind,- durableExternalThreadIdentity(event.event.threadId),- event.event.messageId,- stableExternalPrincipalId(- record.endpoint.provider,- event.event.user,- event.event.raw,- ),- event.event.rawEmoji,- rawFingerprint,- ].join(":");- const normalizedEvent = {- providerEventId,- kind: eventKind,- conversation: { externalThreadId: event.event.threadId },- message: { providerMessageId: event.event.messageId },- reaction: {- emoji: event.event.emoji.name,- rawEmoji: event.event.rawEmoji,- added: event.event.added,- },- runtimeContext: {- generation: runtimeContext.generation,- credentialFingerprint: runtimeContext.credentialFingerprint,- },- };- const admitted = await db.transaction(async (tx) => {- const currentEndpoint = await runtimeCallbackEndpoint(- tx,- event.endpointId,- runtimeContext,- ["active"],- );- if (!currentEndpoint) return false;- const linkedConversation = await lockReactionConversationForMessage(- tx,- currentEndpoint,- event.event.threadId,- event.event.messageId,- );- const currentConversation =- linkedConversation ??- (await lockStreamingReactionConversation(- tx,- currentEndpoint,- event.event.threadId,- ));- if (- !currentConversation ||- !(await authorizeReactionConversation(+ await issuesSvc.addComment(+ linkedTarget.issueId,+ lifecycle.text,+ {},+ { authorType: "system" },tx,- currentEndpoint,- currentConversation,- principal.principal.id,- ))- ) {- return false;- }- const now = new Date();- if (linkedConversation) {- const expiryCutoff = new Date(now.getTime() - REACTION_LINK_MAX_AGE_MS);- const hasOutboundLink = await tx- .select({ id: chatMessageLinks.id })- .from(chatMessageLinks)+ );+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ conversationId: linkedTarget.conversationId,+ principalId: lifecyclePrincipalId,+ state: "processed",+ processedAt: new Date(),+ redactedError: null,+ updatedAt: new Date(),+ }).where(and(- eq(chatMessageLinks.companyId, currentEndpoint.companyId),- eq(chatMessageLinks.endpointId, currentEndpoint.id),- eq(chatMessageLinks.conversationId, linkedConversation.id),- eq(chatMessageLinks.providerMessageId, event.event.messageId),- eq(chatMessageLinks.direction, "outbound"),+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.state, "processing"),),- )- .limit(1)- .then((rows) => rows.length > 0);- await notifyChatDeliveryWork(tx);- const reconciled = hasOutboundLink- ? await tx- .update(chatDeliveries)- .set({- conversationId: linkedConversation.id,- state: "processed",- attempts: sql`${chatDeliveries.attempts} + 1`,- nextAttemptAt: null,- processedAt: now,- redactedError: null,- updatedAt: now,- })- .where(- and(- eq(chatDeliveries.endpointId, currentEndpoint.id),- eq(chatDeliveries.providerEventId, providerEventId),- inArray(chatDeliveries.state, ["received", "retry"]),- gt(chatDeliveries.receivedAt, expiryCutoff),- lt(chatDeliveries.attempts, REACTION_LINK_MAX_ATTEMPTS),- sql`${chatDeliveries.normalizedEvent}->'runtimeContext'->>'generation' = ${String(runtimeContext.generation)}`,- sql`${chatDeliveries.normalizedEvent}->'runtimeContext'->>'credentialFingerprint' = ${runtimeContext.credentialFingerprint}`,- ),- )- .returning({ id: chatDeliveries.id })- : [];- if (reconciled.length > 0) return true;+ );+ });+ } catch (error) {+ const terminal = activeDelivery.attempts >= 5;+ await db.transaction(async (tx) => {await notifyChatDeliveryWork(tx);- const expired = await tx+ return tx.update(chatDeliveries).set({- state: "filtered",- nextAttemptAt: null,- processedAt: now,- redactedError:- "Reaction target did not become linked before replay expiry",- updatedAt: now,+ state: terminal ? "failed" : "retry",+ nextAttemptAt: terminal+ ? null+ : new Date(+ Date.now() ++ Math.min(60_000, 1000 * 2 ** activeDelivery.attempts),+ ),+ redactedError: redactError(error),+ updatedAt: new Date(),}).where(and(- eq(chatDeliveries.endpointId, currentEndpoint.id),- eq(chatDeliveries.providerEventId, providerEventId),- inArray(chatDeliveries.state, ["received", "retry"]),- or(- lte(chatDeliveries.receivedAt, expiryCutoff),- gte(chatDeliveries.attempts, REACTION_LINK_MAX_ATTEMPTS),- ),- sql`${chatDeliveries.normalizedEvent}->'runtimeContext'->>'generation' = ${String(runtimeContext.generation)}`,- sql`${chatDeliveries.normalizedEvent}->'runtimeContext'->>'credentialFingerprint' = ${runtimeContext.credentialFingerprint}`,+ eq(chatDeliveries.id, activeDelivery.id),+ eq(chatDeliveries.state, "processing"),),- )- .returning({ id: chatDeliveries.id });- if (expired.length > 0) return false;- }- await notifyChatDeliveryWork(tx);- const inserted = await tx- .insert(chatDeliveries)- .values({- companyId: currentEndpoint.companyId,- endpointId: currentEndpoint.id,- conversationId: linkedConversation?.id ?? null,- principalId: principal.principal.id,- providerEventId,- deduplicationKey: createHash("sha256")- .update(providerEventId)- .digest("hex"),- eventKind,- normalizedEvent,- state: linkedConversation ? "processed" : "received",- attempts: linkedConversation ? 1 : 0,- nextAttemptAt: linkedConversation- ? null- : new Date(now.getTime() + REACTION_LINK_RETRY_DELAY_MS),- processedAt: linkedConversation ? now : null,- })- .onConflictDoNothing()- .returning({ id: chatDeliveries.id });- if (inserted.length > 0) return true;- return tx- .select({ id: chatDeliveries.id })- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.endpointId, currentEndpoint.id),- eq(chatDeliveries.providerEventId, providerEventId),- inArray(chatDeliveries.state, ["received", "retry", "processed"]),- ),- )- .limit(1)- .then((rows) => rows.length > 0);- });- if (admitted) {- await recordCurrentMicrosoftTeamsRoute(- record.endpoint,+ );+ });+ throw error;+ }+ }++ async function handleMessageUpdated(+ event: ChatSdkMessageUpdatedCallbackEvent,+ runtimeContext: RuntimeContext,+ ) {+ if (+ event.provider === "discord" &&+ !(await ensureDiscordGatewayRuntimeIsCurrent(+ event.endpointId,+ runtimeContext,+ ))+ ) {+ return;+ }+ const text = `An external message was edited:\n\n${event.message.text.slice(0, MAX_INBOUND_TEXT)}`;+ const telegramRich =+ event.provider === "telegram"+ ? normalizeTelegramRichMessage(event.message.raw)+ : null;+ await recordLifecycleDelivery(+ {+ actor: lifecycleActorFromAuthor(+ event.provider,+ event.message.author,+ event.message.raw,+ ),+ endpointId: event.endpointId,+ threadId: event.thread.id,+ messageId: event.message.id,+ eventKind: "message_updated",+ text,+ providerMessageSequence:+ event.provider === "telegram"+ ? telegramMessageSequence(event.message.raw)+ : null,+ providerSentAt:+ (+ event.message.metadata.editedAt ?? event.message.metadata.dateSent+ )?.toISOString() ?? null,+ raw: event.message.raw,+ revision: `${event.message.metadata.editedAt?.toISOString() ?? "unknown"}:${createHash("sha256").update(event.message.text).digest("hex")}${event.provider === "slack" ? `:${slackLifecycleFilesDigest(event.message.raw)}` : event.provider === "discord" ? `:${discordLifecycleFilesDigest(event.message.raw)}` : telegramRich ? `:${telegramRich.mediaDigest}` : ""}`,+ },+ runtimeContext,+ );+ }++ async function handleMessageDeleted(+ event: ChatSdkCallbackEvent<MessageDeletedEvent>,+ runtimeContext: RuntimeContext,+ ) {+ if (+ event.provider === "discord" &&+ !(await ensureDiscordGatewayRuntimeIsCurrent(+ event.endpointId,runtimeContext,- event.event.threadId,- event.event.raw,- );+ ))+ ) {+ return;}+ await recordLifecycleDelivery(+ {+ endpointId: event.endpointId,+ threadId: event.event.threadId,+ messageId: event.event.messageId,+ eventKind: "message_deleted",+ text: "An external message in this conversation was deleted.",+ providerSentAt: event.event.deletedAt?.toISOString() ?? null,+ raw: event.event.raw,+ revision: event.event.deletedAt?.toISOString() ?? null,+ },+ runtimeContext,+ );}async function denyExternalAction(@@ -18629,56 +14626,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {}}- async function verifySlackRequestUrl(endpoint: EndpointRow, request: Request): Promise<Response | null> {- const callback = await inspectSlackCallback(request.clone());- if (!callback?.isUrlVerification) return null;- const body = await request.clone().text();- let notifyAccount = false;- // URL verification needs only the signing secret. Do not initialize the- // SDK (which calls Slack auth.test), wait for OAuth, or acquire the creation- // lease: Slack can deliver this check while app setup still owns that lease.- const response = await db.transaction(async tx => {- const [current] = await tx.select().from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)).for("no key update");- if (!current || ["archived", "paused", "revoked"].includes(current.status)) return new Response("ignored", { status: 200 });- const [connection] = await tx.select({ status: toolConnections.status, refs: toolConnections.credentialSecretRefs }).from(toolConnections)- .where(and(eq(toolConnections.id, current.connectionId), eq(toolConnections.companyId, current.companyId)));- if (!connection || connection.status === "archived") return new Response("ignored", { status: 200 });- let secret = (await resolveCredentialRefs(current, connection.refs.filter(ref => ref.configPath.replace(/^credentials\./, "") === "signingSecret"), tx)).signingSecret;- if (!secret && isProvisionedSlackSetup(current.setup.slackSetupMethod)) {- const [registration] = await tx.select().from(chatSlackRegistrations)- .where(and(eq(chatSlackRegistrations.endpointId, current.id), eq(chatSlackRegistrations.companyId, current.companyId)));- if (registration?.status !== "removed" && registration?.secretIds.signingSecret) {- secret = await secretService(tx as unknown as Db).resolveSecretValue(current.companyId, registration.secretIds.signingSecret, "latest", {- accessContext: { consumerType: "system", consumerId: `slack-registration:${current.id}`, configPath: "slack_registration.signingSecret", actorType: "system" },- });- }- }- if (!secret) return new Response("Slack signing secret is not ready yet", { status: 503 });- if (!slackRequestSignatureIsValid(request, body, secret)) return new Response("Invalid signature", { status: 401 });- const workspaceId = slackRequestWorkspaceId(body, request.headers.get("content-type") ?? "");- if (workspaceId && current.providerAccountId && workspaceId !== current.providerAccountId) return new Response("ignored", { status: 200 });- const observedAt = new Date();- const setup = current.setup as InternalSetupState;- const matchesCurrentUrl = slackCallbackMatchesPublicUrl(callback.url, `${getWebhookPublicBaseUrl()}/api/chat-webhooks/${current.publicId}/slack`);- await notifyChatVerificationWork(tx);- await tx.update(chatEndpoints).set({ setup: {- ...setup,- ...(matchesCurrentUrl ? { webhookVerifiedAt: setup.webhookVerifiedAt ?? observedAt.toISOString(),- slackVerificationSigningFingerprint: createHash("sha256").update(secret).digest("hex") } : {}),- slackCallbackSurfaces: { ...setup.slackCallbackSurfaces, events: { url: callback.url, observedAt: observedAt.toISOString() } },- ...(matchesCurrentUrl && setup.slackAccount?.status === "linked" && !setup.slackAccount.verificationStatus- ? { slackAccount: { ...setup.slackAccount, verificationStatus: "pending" as const } } : {}),- } as InternalSetupState, ...(matchesCurrentUrl ? { healthMessage: "Slack Events Request URL verified" } : {}), updatedAt: observedAt }).where(eq(chatEndpoints.id, current.id));- if (matchesCurrentUrl && !setup.webhookVerifiedAt) await logActivity(tx as unknown as Db, { companyId: current.companyId, actorType: "system", actorId: "slack-webhook",- action: "chat_endpoint.webhook_verified", entityType: "tool_connection", entityId: current.connectionId,- details: { endpointId: current.id, provider: "slack" } });- notifyAccount = matchesCurrentUrl && setup.slackAccount?.status === "linked" && !setup.slackAccount.verificationStatus;- return Response.json({ challenge: (JSON.parse(body) as { challenge: string }).challenge });- });- if (notifyAccount) scheduleMessageProcessing(() => slackRegistration.notifyVerified(endpoint.id));- return response;- }-async function handleWebhook(publicId: string,provider: ChatSdkProvider,@@ -19305,392 +15252,64 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {.where(eq(chatEndpoints.id, endpoint.id));if (connectionProved) await logActivity(tx as unknown as Db, {companyId: current.companyId, actorType: "system", actorId: "slack-webhook",- action: "chat_endpoint.webhook_verified", entityType: "tool_connection", entityId: current.connectionId,- details: { endpointId: current.id, provider: "slack", evidence: "authenticated_event" },- });- });- if (connectionProved) scheduleMessageProcessing(() => slackRegistration.notifyVerified(endpoint.id));- }- }- if (githubInspection && response.ok) {- let lifecycle: GitHubLifecycleEvent | null = null;- try {- lifecycle = await githubLifecycleEventFromRequest(githubInspection);- } catch {- // Ignore only malformed or unsupported supplemental payloads. Once an- // event is recognized, its durable persistence failure must escape.- }- if (lifecycle) {- await recordLifecycleDelivery(- {- endpointId: endpoint.id,- ...lifecycle,- },- runtimeContext,- );- }- }- if (provider === "telegram" && response.ok && lifecyclePayload) {- const lifecycle = telegramLifecycleEventFromPayload(lifecyclePayload);- if (lifecycle) {- await recordLifecycleDelivery(- {- endpointId: endpoint.id,- ...lifecycle,- },- runtimeContext,- );- }- }- if (- provider === "microsoft-teams" &&- response.ok &&- lifecyclePayload &&- endpointRuntime.acceptsProviderScope(lifecyclePayload)- ) {- const lifecycle = microsoftTeamsLifecycleEventFromPayload(- lifecyclePayload,- endpointRuntime,- );- if (lifecycle) {- await recordLifecycleDelivery(- {- endpointId: endpoint.id,- ...lifecycle,- },- runtimeContext,- );- }- }- return response;- }-- function normalizedPendingReaction(delivery: DeliveryRow): {- added: boolean;- emoji: string;- messageId: string;- rawEmoji: string;- runtimeContext: LifecycleRuntimeFence;- threadId: string;- } | null {- if (- delivery.eventKind !== "reaction_added" &&- delivery.eventKind !== "reaction_removed"- ) {- return null;- }- const normalized = delivery.normalizedEvent;- if (- !normalized ||- typeof normalized !== "object" ||- Array.isArray(normalized)- ) {- return null;- }- const value = normalized as Record<string, unknown>;- const conversation = value.conversation;- const message = value.message;- const reaction = value.reaction;- const runtimeContext = lifecycleRuntimeFence(delivery);- if (- !conversation ||- typeof conversation !== "object" ||- Array.isArray(conversation) ||- !message ||- typeof message !== "object" ||- Array.isArray(message) ||- !reaction ||- typeof reaction !== "object" ||- Array.isArray(reaction) ||- !runtimeContext- ) {- return null;- }- const threadId = (conversation as Record<string, unknown>).externalThreadId;- const messageId = (message as Record<string, unknown>).providerMessageId;- const reactionRecord = reaction as Record<string, unknown>;- const added = reactionRecord.added;- const emoji = reactionRecord.emoji;- const rawEmoji = reactionRecord.rawEmoji;- return typeof threadId === "string" &&- threadId.length > 0 &&- typeof messageId === "string" &&- messageId.length > 0 &&- typeof added === "boolean" &&- added === (delivery.eventKind === "reaction_added") &&- typeof emoji === "string" &&- emoji.length > 0 &&- typeof rawEmoji === "string" &&- rawEmoji.length > 0- ? { added, emoji, messageId, rawEmoji, runtimeContext, threadId }- : null;- }-- async function processPendingReactionDelivery(- candidate: DeliveryRow,- ): Promise<void> {- const reaction = normalizedPendingReaction(candidate);- if (!reaction || !candidate.principalId) {- const now = new Date();- await db.transaction(async (tx) => {- await notifyChatDeliveryWork(tx);- return tx- .update(chatDeliveries)- .set({- state: "failed",- nextAttemptAt: null,- processedAt: now,- redactedError: "Normalized reaction delivery is incomplete",- updatedAt: now,- })- .where(- and(- eq(chatDeliveries.id, candidate.id),- inArray(chatDeliveries.state, ["received", "retry"]),- ),- );- });- return;- }- const principalId = candidate.principalId;-- await db.transaction(async (tx) => {- const currentEndpoint = await runtimeCallbackEndpoint(- tx,- candidate.endpointId,- reaction.runtimeContext,- ["active"],- );- let conversation: ConversationRow | null = null;- let disposition:- | { kind: "processed"; conversationId: string }- | { kind: "retry" }- | { kind: "filtered"; reason: string };-- if (!currentEndpoint) {- disposition = {- kind: "filtered",- reason: "Reaction callback belonged to an unavailable runtime",- };- } else {- await options.reactionReplayEndpointLockBarrier?.();- conversation = await lockReactionConversationForMessage(- tx,- currentEndpoint,- reaction.threadId,- reaction.messageId,- "outbound",- );- if (conversation) {- await options.reactionReplayConversationLockBarrier?.();- }- if (conversation) {- disposition = (await authorizeReactionConversation(- tx,- currentEndpoint,- conversation,- principalId,- ))- ? { kind: "processed", conversationId: conversation.id }- : {- kind: "filtered",- reason:- "Reaction destination or principal is no longer authorized",- };- } else {- conversation = await lockStreamingReactionConversation(- tx,- currentEndpoint,- reaction.threadId,- );- if (conversation) {- await options.reactionReplayConversationLockBarrier?.();- }- if (!conversation) {- disposition = {- kind: "filtered",- reason: "Reaction target was not linked to a sent message",- };- } else {- disposition = (await authorizeReactionConversation(- tx,- currentEndpoint,- conversation,- principalId,- ))- ? { kind: "retry" }- : {- kind: "filtered",- reason:- "Reaction destination or principal is no longer authorized",- };- }- }- }-- // Endpoint, conversation, destination and identity locks are acquired- // before the delivery row so pause/revoke and replay use one lock order.- const locked = await tx- .select()- .from(chatDeliveries)- .where(- and(- eq(chatDeliveries.id, candidate.id),- inArray(chatDeliveries.state, ["received", "retry"]),- ),- )- .for("update")- .then((rows) => rows[0] ?? null);- // Authorization locks may wait behind a concurrent lifecycle mutation.- // Sample the expiry clock only after this delivery is exclusively held.- const decisionAt = new Date();- if (!locked || !deliveryReady(locked, decisionAt)) return;- const lockedReaction = normalizedPendingReaction(locked);- if (- !lockedReaction ||- lockedReaction.runtimeContext.generation !==- reaction.runtimeContext.generation ||- lockedReaction.runtimeContext.credentialFingerprint !==- reaction.runtimeContext.credentialFingerprint- ) {- disposition = {- kind: "filtered",- reason: "Reaction delivery identity changed before replay",- };- }-- const nextAttempts = locked.attempts + 1;- const expired =- decisionAt.getTime() - locked.receivedAt.getTime() >=- REACTION_LINK_MAX_AGE_MS;- if (expired || locked.attempts >= REACTION_LINK_MAX_ATTEMPTS) {- disposition = {- kind: "filtered",- reason: "Reaction target did not become linked before replay expiry",- };- }- if (disposition.kind === "retry" && !expired) {- if (nextAttempts < REACTION_LINK_MAX_ATTEMPTS) {- const delay = Math.min(- REACTION_LINK_RETRY_DELAY_MS *- 2 ** Math.min(Math.max(locked.attempts, 0), 5),- REACTION_LINK_MAX_DELAY_MS,- );- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set({- state: "retry",- attempts: nextAttempts,- nextAttemptAt: new Date(decisionAt.getTime() + delay),- redactedError: "Waiting for the sent message link",- updatedAt: decisionAt,- })- .where(- and(- eq(chatDeliveries.id, locked.id),- eq(chatDeliveries.state, locked.state),- eq(chatDeliveries.attempts, locked.attempts),- ),- );- return;- }- disposition = {- kind: "filtered",- reason: "Reaction target did not become linked before retry expiry",- };- } else if (disposition.kind === "retry") {- disposition = {- kind: "filtered",- reason: "Reaction target did not become linked before age expiry",- };- }-- const processedAt = new Date();- await notifyChatDeliveryWork(tx);- await tx- .update(chatDeliveries)- .set(- disposition.kind === "processed"- ? {- conversationId: disposition.conversationId,- state: "processed",- attempts: nextAttempts,- nextAttemptAt: null,- processedAt,- redactedError: null,- updatedAt: processedAt,- }- : {- state: "filtered",- attempts: nextAttempts,- nextAttemptAt: null,- processedAt,- redactedError: disposition.reason,- updatedAt: processedAt,- },- )- .where(- and(- eq(chatDeliveries.id, locked.id),- eq(chatDeliveries.state, locked.state),- eq(chatDeliveries.attempts, locked.attempts),- ),- );- });- }-- async function processPendingReactionDeliveries(- limit: number,- onlyDeliveryId?: string,- ): Promise<number> {- const now = new Date();- const candidates = await db- .select()- .from(chatDeliveries)- .where(- and(- sql`not exists (select 1 from chat_endpoints e where e.id = ${chatDeliveries.endpointId} and e.provider = 'agentmail')`,- onlyDeliveryId ? eq(chatDeliveries.id, onlyDeliveryId) : undefined,- inArray(chatDeliveries.eventKind, [- "reaction_added",- "reaction_removed",- ]),- or(- and(- eq(chatDeliveries.state, "received"),- or(- isNull(chatDeliveries.nextAttemptAt),- lte(chatDeliveries.nextAttemptAt, now),- ),- ),- and(- eq(chatDeliveries.state, "retry"),- or(- isNull(chatDeliveries.nextAttemptAt),- lte(chatDeliveries.nextAttemptAt, now),- ),- ),- ),- ),- )- .orderBy(asc(chatDeliveries.receivedAt), asc(chatDeliveries.id))- .limit(limit);- for (const candidate of candidates) {+ action: "chat_endpoint.webhook_verified", entityType: "tool_connection", entityId: current.connectionId,+ details: { endpointId: current.id, provider: "slack", evidence: "authenticated_event" },+ });+ });+ if (connectionProved) scheduleMessageProcessing(() => slackRegistration.notifyVerified(endpoint.id));+ }+ }+ if (githubInspection && response.ok) {+ let lifecycle: GitHubLifecycleEvent | null = null;try {- await processPendingReactionDelivery(candidate);- } catch (error) {- logger.warn(+ lifecycle = await githubLifecycleEventFromRequest(githubInspection);+ } catch {+ // Ignore only malformed or unsupported supplemental payloads. Once an+ // event is recognized, its durable persistence failure must escape.+ }+ if (lifecycle) {+ await recordLifecycleDelivery({- endpointId: candidate.endpointId,- deliveryId: candidate.id,- error: redactError(error),+ endpointId: endpoint.id,+ ...lifecycle,+ },+ runtimeContext,+ );+ }+ }+ if (provider === "telegram" && response.ok && lifecyclePayload) {+ const lifecycle = telegramLifecycleEventFromPayload(lifecyclePayload);+ if (lifecycle) {+ await recordLifecycleDelivery(+ {+ endpointId: endpoint.id,+ ...lifecycle,+ },+ runtimeContext,+ );+ }+ }+ if (+ provider === "microsoft-teams" &&+ response.ok &&+ lifecyclePayload &&+ endpointRuntime.acceptsProviderScope(lifecyclePayload)+ ) {+ const lifecycle = microsoftTeamsLifecycleEventFromPayload(+ lifecyclePayload,+ endpointRuntime,+ );+ if (lifecycle) {+ await recordLifecycleDelivery(+ {+ endpointId: endpoint.id,+ ...lifecycle,},- "chat reaction-link reconciliation failed",+ runtimeContext,);}}- return candidates.length;+ return response;}/**@@ -19926,96 +15545,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {return reactionCount + rows.length;}- async function listConversations(endpointId: string) {- const record = await endpointRecord(endpointId);- if (!record) throw notFound("Chat endpoint not found");- const conversations = await db- .select()- .from(chatConversations)- .where(eq(chatConversations.endpointId, endpointId))- .orderBy(- desc(chatConversations.lastActivityAt),- desc(chatConversations.createdAt),- );- if (!conversations.length) return [];- const issueRows = await db- .select({- id: issues.id,- identifier: issues.identifier,- title: issues.title,- status: issues.status,- updatedAt: issues.updatedAt,- })- .from(issues)- .where(- inArray(- issues.id,- conversations.map((row) => row.issueId),- ),- );- const publications = await db- .select()- .from(chatPublications)- .where(eq(chatPublications.endpointId, endpointId))- .orderBy(desc(chatPublications.createdAt));- const issueById = new Map(issueRows.map((row) => [row.id, row]));- const lastPublication = new Map<- string,- typeof chatPublications.$inferSelect- >();- for (const publication of publications)- if (!lastPublication.has(publication.conversationId))- lastPublication.set(publication.conversationId, publication);- return conversations.map((conversation) => {- const issue = issueById.get(conversation.issueId);- const externalUrl =- record.endpoint.provider === "telegram" && conversation.isDirectMessage- ? chatProviderConversationUrl({- provider: "telegram",- botUsername: record.endpoint.botUsername,- threadId: conversation.externalThreadId,- providerMessageId: "",- raw: { chat: { type: "private" } },- })- : (conversation.providerUrl ??- (record.endpoint.provider === "slack"- ? chatProviderConversationUrl({- provider: "slack",- providerAccountId: record.endpoint.providerAccountId,- threadId: conversation.externalThreadId,- providerMessageId: "",- })- : null));- return {- id: conversation.id,- companyId: conversation.companyId,- endpointId: conversation.endpointId,- resourceId: conversation.resourceId,- externalLabel: conversation.externalLabel,- externalUrl,- externalConversationId: conversation.externalConversationId,- externalThreadId: conversation.externalThreadId,- sessionGeneration: conversation.sessionGeneration,- issueId: conversation.issueId,- issueIdentifier: issue?.identifier ?? null,- issueTitle: issue?.title ?? null,- isDirectMessage: conversation.isDirectMessage,- state:- record.endpoint.provider !== "imessage-photon" &&- (issue?.status === "done" || issue?.status === "cancelled")- ? "completed"- : conversation.state,- lastActivityAt: conversation.lastActivityAt?.toISOString() ?? null,- createdAt: conversation.createdAt.toISOString(),- updatedAt: (- conversation.lastActivityAt ?? conversation.updatedAt- ).toISOString(),- lastPublicationStatus:- lastPublication.get(conversation.id)?.state ?? null,- };- });- }-async function recordGitHubAutomaticSkip(endpoint: EndpointRow, deliveryId: string, event: string, reason: string | undefined, runtimeContext: LifecycleRuntimeFence,) {@@ -20043,457 +15572,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {});}- async function listActivity(endpointId: string, page?: { limit: number; before?: { createdAt: string; id: string } }) {- const limit = page ? page.limit + 1 : 100;- // Match the millisecond precision of the public timestamp and use a UUID- // tie-breaker so equal timestamps never skip records between pages.- const before = (date: AnyPgColumn, id: AnyPgColumn) => page?.before- ? sql`(date_trunc('milliseconds', ${date}), ${id}) < (${page.before.createdAt}::timestamptz, ${page.before.id}::uuid)`- : undefined;- const recoveryIngress = alias(chatActions, "github_recovery_ingress");- const [- deliveries,- publications,- slashActions,- providerEffects,- githubIngressFailures,- slackSessionActions,- githubRecoveries,- githubRecoveryScans,- ] = await Promise.all([- db- .select()- .from(chatDeliveries)- .where(and(eq(chatDeliveries.endpointId, endpointId), before(chatDeliveries.createdAt, chatDeliveries.id)))- .orderBy(desc(sql`date_trunc('milliseconds', ${chatDeliveries.createdAt})`), desc(chatDeliveries.id))- .limit(limit),- db- .select()- .from(chatPublications)- .where(and(eq(chatPublications.endpointId, endpointId), before(chatPublications.createdAt, chatPublications.id)))- .orderBy(desc(sql`date_trunc('milliseconds', ${chatPublications.createdAt})`), desc(chatPublications.id))- .limit(limit),- db- .select()- .from(chatActions)- .where(- and(- eq(chatActions.endpointId, endpointId),- before(chatActions.createdAt, chatActions.id),- eq(chatActions.kind, "slash_task_start"),- ),- )- .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.createdAt})`), desc(chatActions.id))- .limit(limit),- db- .select()- .from(chatActions)- .where(- and(- eq(chatActions.endpointId, endpointId),- before(chatActions.createdAt, chatActions.id),- eq(chatActions.kind, "provider_effect"),- eq(chatActions.status, "delivery_unknown"),- ),- )- .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.createdAt})`), desc(chatActions.id))- .limit(limit),- db- .select()- .from(chatActions)- .where(- and(- eq(chatActions.endpointId, endpointId),- before(chatActions.createdAt, chatActions.id),- eq(chatActions.kind, "github_webhook_ingress"),- eq(chatActions.status, "failed"),- sql`coalesce(${chatActions.result}->>'retryable', 'false') = 'false'`,- ),- )- .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.createdAt})`), desc(chatActions.id))- .limit(limit),- db- .select()- .from(chatActions)- .where(- and(- eq(chatActions.endpointId, endpointId),- before(chatActions.updatedAt, chatActions.id),- inArray(chatActions.kind, [- "slack_session_sync",- "slack_session_stop",- ]),- ),- )- .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.updatedAt})`), desc(chatActions.id))- .limit(limit),- db- .select({- action: chatActions,- ingressStatus: recoveryIngress.status,- })- .from(chatActions)- .leftJoin(- recoveryIngress,- and(- eq(recoveryIngress.companyId, chatActions.companyId),- eq(recoveryIngress.endpointId, chatActions.endpointId),- eq(recoveryIngress.kind, "github_webhook_ingress"),- sql`${recoveryIngress.providerActionId} = 'github_webhook_ingress:' || (${chatActions.payload}#>>'{original,guid}')`,- ),- )- .where(- and(- eq(chatActions.endpointId, endpointId),- before(chatActions.updatedAt, chatActions.id),- eq(chatActions.kind, "github_webhook_recovery"),- ),- )- .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.updatedAt})`), desc(chatActions.id))- .limit(limit),- db- .select()- .from(chatSdkState)- .where(- and(- eq(chatSdkState.endpointId, endpointId),- before(chatSdkState.updatedAt, chatSdkState.id),- eq(chatSdkState.stateKey, GITHUB_RECOVERY_STATE_KEY),- ),- )- .limit(1),- ]);- // A provider effect can be on another page. Replay safety must still- // consider every unresolved effect associated with these deliveries.- const ambiguousEffects = deliveries.length ? await db.select({ deliveryId: chatActions.deliveryId })- .from(chatActions).where(and(- eq(chatActions.endpointId, endpointId),- eq(chatActions.kind, "provider_effect"),- eq(chatActions.status, "delivery_unknown"),- inArray(chatActions.deliveryId, deliveries.map((row) => row.id)),- )) : [];- const ambiguousProviderEffectDeliveryIds = new Set(ambiguousEffects.map((row) => row.deliveryId));- const transferRows = publications.length- ? await db- .select(fileTransferProjectionColumns)- .from(chatTeamsFileTransfers)- .innerJoin(- chatPublications,- and(- eq(chatPublications.id, chatTeamsFileTransfers.publicationId),- eq(chatPublications.companyId, chatTeamsFileTransfers.companyId),- eq(- chatPublications.endpointId,- chatTeamsFileTransfers.endpointId,- ),- eq(- chatPublications.conversationId,- chatTeamsFileTransfers.conversationId,- ),- ),- )- .where(- and(- eq(chatTeamsFileTransfers.companyId, publications[0]!.companyId),- eq(chatTeamsFileTransfers.endpointId, endpointId),- inArray(- chatTeamsFileTransfers.publicationId,- publications.map((row) => row.id),- ),- ),- )- : [];- const transfers = new Map(- transferRows.map((row) => [row.publicationId, row]),- );- const cancellableConflicts = new Map<string, number>();- for (const transfer of transferRows) {- if (transfer.phase !== "conflict") continue;- const publication = publications.find(- (row) => row.id === transfer.publicationId,- );- if (!publication?.conversationId) continue;- if (- await teamsTransferProtocol().canCancelConflict({- companyId: publication.companyId,- endpointId,- conversationId: publication.conversationId,- publicationId: publication.id,- version: transfer.version,- })- )- cancellableConflicts.set(publication.id, transfer.version);- }- return [- ...deliveries.map((row) => {- const normalized =- row.normalizedEvent &&- typeof row.normalizedEvent === "object" &&- !Array.isArray(row.normalizedEvent)- ? (row.normalizedEvent as Record<string, unknown>)- : {};- const deduplication =- normalized.deduplication &&- typeof normalized.deduplication === "object" &&- !Array.isArray(normalized.deduplication)- ? (normalized.deduplication as Record<string, unknown>)- : null;- const duplicateCount =- typeof deduplication?.duplicateCount === "number"- ? deduplication.duplicateCount- : 0;- const label = row.eventKind.replaceAll("_", " ");- const outcome =- row.state === "filtered"- ? "ignored"- : row.state === "processed"- ? "processed"- : row.state;- return {- id: row.id,- kind: "delivery" as const,- status: row.state,- summary: `${label} ${outcome}${duplicateCount ? ` · ${duplicateCount} duplicate${duplicateCount === 1 ? "" : "s"} ignored` : ""}`,- detail: row.redactedError,- createdAt: row.createdAt.toISOString(),- replayable:- row.state === "failed" &&- Boolean(row.conversationId) &&- !ambiguousProviderEffectDeliveryIds.has(row.id),- resolutionActions: [],- };- }),- ...publications.map((row) => {- const transfer = transfers.get(row.id);- const projected = projectChatFileTransfer(- publicationSummary(row),- transfer,- );- const payload = row.payload as Partial<SafeChatPublicationPayload>;- const summary = payload.progressState- ? `${payload.progressState.replaceAll("_", " ")} update`- : payload.interactionId- ? "Interactive question"- : "Response to external conversation";- return {- id: row.id,- kind: "publication" as const,- status: projected.state,- summary,- detail: projected.redactedError ?? null,- createdAt: row.createdAt.toISOString(),- replayable: !transfer && row.state === "failed",- ...(projected.fileTransfer- ? { fileTransfer: projected.fileTransfer }- : {}),- resolutionActions: transfer- ? chatFileTransferResolutionActions(- projected,- cancellableConflicts.has(row.id)- ? {- publicationId: row.id,- version: cancellableConflicts.get(row.id)!,- }- : undefined,- )- : row.state === "delivery_unknown"- ? (["mark_delivered", "retry_anyway", "cancel"] as const)- : [],- };- }),- ...slashActions.map((row) => {- const recovery = slackSlashTaskRecoveryPayload(row.payload);- // Keep this GET read-only while still surfacing a crashed attempt as- // actionable. The resolution POST persists the derived quarantine- // before it applies the operator's audited decision.- const status = slackTaskStartActivityStatus(row);- return {- id: row.id,- kind: "action" as const,- actionType: "slash_task_start" as const,- status,- summary: `Slack slash-command task start ${status.replaceAll("_", " ")}`,- detail:- status === "delivery_unknown"- ? recovery- ? "Slack may have accepted the task-start message, so Paperclip will not replay it automatically. Check Slack first; an explicit retry can create a duplicate starter message and task."- : "Slack may have accepted the task-start message. This older action lacks the context required for a safe explicit retry, so check Slack and cancel it here before submitting a new command."- : status === "provider_confirmed"- ? "Slack accepted the task-start message. Paperclip is completing durable task admission without sending another Slack message."- : status === "admitting"- ? "Slack accepted the task-start message. A Paperclip worker is admitting the task without replaying the Slack send."- : status === "failed"- ? "Slack rejected the task-start message. Submit the command again to retry."- : status === "cancelled"- ? "An operator cancelled this unconfirmed task start."- : null,- createdAt: row.createdAt.toISOString(),- replayable: false,- resolutionActions:- status === "delivery_unknown"- ? recovery- ? (["retry_anyway", "cancel"] as const)- : (["cancel"] as const)- : [],- };- }),- ...providerEffects.map((row) => {- const payload = providerEffectPayload(row.payload);- return {- id: row.id,- kind: "action" as const,- actionType: "provider_effect" as const,- status: row.status,- summary: "Provider reply delivery unknown",- detail: payload?.completeConversationId- ? "The provider may have accepted this reply, but Paperclip could not confirm it or close the task conversation. Check the provider first. Marking it delivered closes the conversation; retrying can create a duplicate message."- : "The provider may have accepted this reply, but Paperclip could not confirm it. Check the provider first. Retrying can create a duplicate message.",- createdAt: row.createdAt.toISOString(),- replayable: false,- resolutionActions: [- "mark_delivered",- "retry_anyway",- "cancel",- ] as const,- };- }),- ...slackSessionActions.map((row) => {- const isSync = row.kind === "slack_session_sync";- const retrying =- row.status === "received" &&- row.result?.code === "slack_session_sync_retry";- return {- id: row.id,- kind: "action" as const,- actionType: isSync- ? ("slack_session_sync" as const)- : ("slack_session_stop" as const),- status: retrying ? "retry" : row.status,- summary: isSync ? "Slack session status" : "Slack Stop request",- detail: isSync- ? row.result?.outcome === "unavailable"- ? "Slack has not enabled native session status for this destination. Message delivery continues."- : row.result?.code === "slack_session_sync_rejected"- ? "Slack rejected the session indicator update. Check app permissions and channel access; message delivery is tracked separately."- : retrying- ? "The Slack session indicator is waiting to sync. Paperclip will not resend the response."- : row.result?.sessionStatus === "processing"- ? "Working status is refreshed automatically while the run remains active."- : null- : row.status === "processed"- ? "Paperclip stopped the work authorized by this request."- : row.status === "cancelled"- ? "No work was stopped: this request was no longer authorized or its target was no longer current."- : row.status === "failed"- ? row.result?.retryable === true- ? "The Stop request could not finish yet. Paperclip will retry against the original work only."- : "The Stop request could not be completed. Check the task's current run before trying again."- : "Paperclip is processing this Stop request against its original task and run.",- createdAt: row.updatedAt.toISOString(),- replayable: false,- resolutionActions: [],- };- }),- ...githubIngressFailures.map((row) => {- const deliveryId =- typeof row.payload.deliveryId === "string"- ? row.payload.deliveryId- : null;- return {- id: row.id,- kind: "action" as const,- actionType: "github_webhook_ingress" as const,- status: row.status,- summary: "GitHub webhook could not be processed",- detail: deliveryId- ? `GitHub delivery ${deliveryId} was authenticated, but Paperclip could not finish processing it. Fix the connection or destination, then redeliver this delivery from the GitHub App's Recent Deliveries page.`- : "An authenticated GitHub webhook could not be processed. Fix the connection or destination, then redeliver it from the GitHub App's Recent Deliveries page.",- createdAt: row.createdAt.toISOString(),- replayable: false,- resolutionActions: [],- };- }),- ...githubRecoveries.map(({ action: row, ingressStatus }) => ({- id: row.id,- kind: "repair" as const,- status:- row.status === "cancelled"- ? "cancelled"- : ingressStatus- ? "received"- : "pending",- summary:- row.status === "cancelled"- ? "GitHub webhook recovery skipped"- : ingressStatus- ? "GitHub webhook received after recovery request"- : "GitHub webhook redelivery requested",- detail:- row.status === "cancelled"- ? row.result?.code === "source_changed_or_unavailable"- ? "The original comment changed or is no longer available. Paperclip did not replay its old contents."- : "This callback was not an eligible current user comment. Paperclip did not replay it."- : ingressStatus- ? "Paperclip received this callback. Its normal access checks and processing still apply."- : "Paperclip asked GitHub to resend a recent missed message. This does not yet confirm receipt or a reply. Automatic requests are limited; if it remains unanswered, check the App's Recent Deliveries and send your request again in the current conversation.",- createdAt: row.updatedAt.toISOString(),- replayable: false,- resolutionActions: [],- })),- ...githubRecoveryScans.flatMap((row) => {- const value = row.value as { outcome?: string } | null;- const detail =- value?.outcome === "history_limit_reached"- ? "Recent webhook volume exceeded automatic recovery's bounded scan. No partial history was replayed. Check the App's Recent Deliveries for missed messages."- : value?.outcome === "callback_mismatch"- ? "The GitHub App's callback no longer matches this connection. Reconnect the App to repair it; repository access will not change."- : value?.outcome === "scan_failed"- ? "Paperclip could not check GitHub's failed deliveries. The check will retry with backoff; normal callbacks are still processed."- : null;- return detail- ? [- {- id: row.id,- kind: "health" as const,- status: "attention",- summary: "GitHub webhook recovery needs attention",- detail,- createdAt: row.updatedAt.toISOString(),- replayable: false,- resolutionActions: [],- },- ]- : [];- }),- ]- .sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id))- .slice(0, limit);- }-- async function listActivityPage(endpointId: string, limit = 25, cursor?: string) {- if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw badRequest("Activity limit must be between 1 and 100");- let before: { createdAt: string; id: string } | undefined;- if (cursor !== undefined) {- try {- if (cursor.length > 256) throw new Error("Invalid cursor");- const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));- if (!Array.isArray(value) || value.length !== 2- || typeof value[0] !== "string" || new Date(value[0]).toISOString() !== value[0]- || typeof value[1] !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value[1])) throw new Error("Invalid cursor");- before = { createdAt: value[0], id: value[1] };- } catch { throw badRequest("Invalid activity cursor"); }- }- const rows = await listActivity(endpointId, { limit, before });- const items = rows.slice(0, limit);- const last = items.at(-1);- return {- items,- nextCursor: rows.length > limit && last- ? Buffer.from(JSON.stringify([last.createdAt, last.id])).toString("base64url")- : null,- };- }-async function replayDelivery(endpointId: string, deliveryId: string) {const delivery = await db.select()@@ -22685,118 +17763,6 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {});}- async function publicationFiles(- publication: typeof chatPublications.$inferSelect,- payload: SafeChatPublicationPayload,- preparation: { teamsInlineImagesOnly?: boolean } = {},- ): Promise<FileUpload[]> {- if (!payload.attachmentIds?.length) return [];- try {- const rows = await db- .select({- id: issueAttachments.id,- issueId: issueAttachments.issueId,- issueCommentId: issueAttachments.issueCommentId,- objectKey: assets.objectKey,- contentType: assets.contentType,- byteSize: assets.byteSize,- sha256: assets.sha256,- originalFilename: assets.originalFilename,- })- .from(issueAttachments)- .innerJoin(assets, eq(issueAttachments.assetId, assets.id))- .where(- and(- eq(issueAttachments.companyId, publication.companyId),- eq(issueAttachments.issueId, publication.issueId),- inArray(issueAttachments.id, payload.attachmentIds),- ),- );- const byId = new Map(rows.map((row) => [row.id, row]));- const orderedRows = payload.attachmentIds.map((attachmentId) => {- const row = byId.get(attachmentId);- if (- !row ||- (publication.commentId &&- row.issueCommentId !== publication.commentId) ||- row.byteSize <= 0 ||- row.byteSize > MAX_ATTACHMENT_BYTES ||- !row.objectKey.trim() ||- !/^[0-9a-f]{64}$/iu.test(row.sha256) ||- !isAllowedContentType(row.contentType)- )- throw new OutboundAttachmentValidationError(- "Chat publication attachment is invalid or outside its authorized task comment",- );- return row;- });- // Picture messages have a different Teams contract from arbitrary files.- // Preserve the normal scope/metadata checks above, but never hydrate a- // document or oversized image just to discover it needs a task link.- if (- preparation.teamsInlineImagesOnly &&- orderedRows.some(- (row) =>- row.byteSize > TEAMS_INLINE_IMAGE_MAX_BYTES ||- !isTeamsInlineImageContentType(row.contentType),- )- ) {- return [];- }- // Authorization and persisted metadata must fail definitively even when- // storage is unavailable; do not mask an invalid file as a transient outage.- if (!options.storage)- throw new OutboundAttachmentHydrationError(- "Attachment storage is unavailable for chat publication",- );- const files: FileUpload[] = [];- for (const row of orderedRows) {- files.push(- await hydrateOutboundAttachment({- storage: options.storage,- companyId: publication.companyId,- objectKey: row.objectKey,- byteSize: row.byteSize,- sha256: row.sha256,- filename: row.originalFilename ?? `attachment-${row.id}`,- mimeType: row.contentType,- }),- );- }- return files;- } catch (error) {- if (- isOutboundAttachmentHydrationError(error) ||- isOutboundAttachmentValidationError(error)- ) {- throw error;- }- throw new OutboundAttachmentHydrationError(- "Chat publication attachment preparation failed",- error,- );- }- }-- function discordMarkdownAttachment(text: string): FileUpload {- return {- data: Buffer.from(text, "utf8"),- filename: "paperclip-response.md",- mimeType: "text/markdown; charset=utf-8",- };- }-- function telegramMarkdownAttachment(text: string): Attachment {- const data = Buffer.from(text, "utf8");- return {- data,- mimeType: "text/markdown; charset=utf-8",- name: "paperclip-response.md",- size: data.byteLength,- type: "file",- };- }-async function recordExactOutboundPublicationLink(tx: DbOrTransaction,input: {@@ -26176,6 +21142,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) {}, lease, actor.userId);},});+ const { verifySlackRequestUrl } = createSlackCallbackVerification(db, { resolveCredentialRefs, getWebhookPublicBaseUrl, scheduleMessageProcessing, slackRegistration });const sendSlackTestMessage = slackTestMessageService(db, {fetch: fetchImpl,diff --git a/server/src/services/chat-channels/activity.ts b/server/src/services/chat-channels/activity.tsnew file mode 100644index 0000000000..0a9824ae57--- /dev/null+++ b/server/src/services/chat-channels/activity.ts@@ -0,0 +1,616 @@+import { providerEffectPayload } from "./provider-effects.js";++import { slackSlashTaskRecoveryPayload } from "./slack/task-start.js";+import { GITHUB_RECOVERY_STATE_KEY } from "./github/webhook-ingress.js";++import {+ and,+ desc,+ eq,+ inArray,+ sql,+} from "drizzle-orm";+import { alias, type AnyPgColumn } from "drizzle-orm/pg-core";++import type { Db } from "@paperclipai/db";++import {+ chatActions,+ chatConversations,+ chatDeliveries,+ chatPublications,+ chatSdkState,+ chatTeamsFileTransfers,+ issues,+} from "@paperclipai/db";+import type {+ ChatPublicationSummary,+ SafeChatPublicationPayload,+} from "@paperclipai/shared";++import {+ teamsFileTransferService,+} from "../chat-teams-file-transfers.js";++import {+ chatFileTransferResolutionActions,+ projectChatFileTransfer,+} from "../chat-publication-batches.js";++import {+ badRequest,+ notFound,+} from "../../errors.js";++import { chatProviderConversationUrl } from "../chat-provider-links.js";++import type { EndpointRecord } from "./runtime-types.js";+import { slackTaskStartActivityStatus } from "./slack/task-start.js";+import { fileTransferProjectionColumns } from "./microsoft-teams/file-transfer-projection.js";++function publicationSummary(+ row: typeof chatPublications.$inferSelect,+): ChatPublicationSummary {+ return {+ id: row.id,+ state: row.state,+ providerUrl: row.providerUrl,+ attempts: row.attempts,+ redactedError: row.redactedError,+ nextAttemptAt: row.nextAttemptAt?.toISOString() ?? null,+ publishedAt: row.publishedAt?.toISOString() ?? null,+ };+}+export { publicationSummary };++type ChatActivityOptions = {+ endpointRecord: (endpointId: string) => Promise<EndpointRecord | null>;+ teamsTransferProtocol: () => Pick<ReturnType<typeof teamsFileTransferService>, "canCancelConflict">;+};++export function createChatActivity(db: Db, options: ChatActivityOptions) {+ const { endpointRecord, teamsTransferProtocol } = options;+++ async function listConversations(endpointId: string) {+ const record = await endpointRecord(endpointId);+ if (!record) throw notFound("Chat endpoint not found");+ const conversations = await db+ .select()+ .from(chatConversations)+ .where(eq(chatConversations.endpointId, endpointId))+ .orderBy(+ desc(chatConversations.lastActivityAt),+ desc(chatConversations.createdAt),+ );+ if (!conversations.length) return [];+ const issueRows = await db+ .select({+ id: issues.id,+ identifier: issues.identifier,+ title: issues.title,+ status: issues.status,+ updatedAt: issues.updatedAt,+ })+ .from(issues)+ .where(+ inArray(+ issues.id,+ conversations.map((row) => row.issueId),+ ),+ );+ const publications = await db+ .select()+ .from(chatPublications)+ .where(eq(chatPublications.endpointId, endpointId))+ .orderBy(desc(chatPublications.createdAt));+ const issueById = new Map(issueRows.map((row) => [row.id, row]));+ const lastPublication = new Map<+ string,+ typeof chatPublications.$inferSelect+ >();+ for (const publication of publications)+ if (!lastPublication.has(publication.conversationId))+ lastPublication.set(publication.conversationId, publication);+ return conversations.map((conversation) => {+ const issue = issueById.get(conversation.issueId);+ const externalUrl =+ record.endpoint.provider === "telegram" && conversation.isDirectMessage+ ? chatProviderConversationUrl({+ provider: "telegram",+ botUsername: record.endpoint.botUsername,+ threadId: conversation.externalThreadId,+ providerMessageId: "",+ raw: { chat: { type: "private" } },+ })+ : (conversation.providerUrl ??+ (record.endpoint.provider === "slack"+ ? chatProviderConversationUrl({+ provider: "slack",+ providerAccountId: record.endpoint.providerAccountId,+ threadId: conversation.externalThreadId,+ providerMessageId: "",+ })+ : null));+ return {+ id: conversation.id,+ companyId: conversation.companyId,+ endpointId: conversation.endpointId,+ resourceId: conversation.resourceId,+ externalLabel: conversation.externalLabel,+ externalUrl,+ externalConversationId: conversation.externalConversationId,+ externalThreadId: conversation.externalThreadId,+ sessionGeneration: conversation.sessionGeneration,+ issueId: conversation.issueId,+ issueIdentifier: issue?.identifier ?? null,+ issueTitle: issue?.title ?? null,+ isDirectMessage: conversation.isDirectMessage,+ state:+ record.endpoint.provider !== "imessage-photon" &&+ (issue?.status === "done" || issue?.status === "cancelled")+ ? "completed"+ : conversation.state,+ lastActivityAt: conversation.lastActivityAt?.toISOString() ?? null,+ createdAt: conversation.createdAt.toISOString(),+ updatedAt: (+ conversation.lastActivityAt ?? conversation.updatedAt+ ).toISOString(),+ lastPublicationStatus:+ lastPublication.get(conversation.id)?.state ?? null,+ };+ });+ }++ async function listActivity(endpointId: string, page?: { limit: number; before?: { createdAt: string; id: string } }) {+ const limit = page ? page.limit + 1 : 100;+ // Match the millisecond precision of the public timestamp and use a UUID+ // tie-breaker so equal timestamps never skip records between pages.+ const before = (date: AnyPgColumn, id: AnyPgColumn) => page?.before+ ? sql`(date_trunc('milliseconds', ${date}), ${id}) < (${page.before.createdAt}::timestamptz, ${page.before.id}::uuid)`+ : undefined;+ const recoveryIngress = alias(chatActions, "github_recovery_ingress");+ const [+ deliveries,+ publications,+ slashActions,+ providerEffects,+ githubIngressFailures,+ slackSessionActions,+ githubRecoveries,+ githubRecoveryScans,+ ] = await Promise.all([+ db+ .select()+ .from(chatDeliveries)+ .where(and(eq(chatDeliveries.endpointId, endpointId), before(chatDeliveries.createdAt, chatDeliveries.id)))+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatDeliveries.createdAt})`), desc(chatDeliveries.id))+ .limit(limit),+ db+ .select()+ .from(chatPublications)+ .where(and(eq(chatPublications.endpointId, endpointId), before(chatPublications.createdAt, chatPublications.id)))+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatPublications.createdAt})`), desc(chatPublications.id))+ .limit(limit),+ db+ .select()+ .from(chatActions)+ .where(+ and(+ eq(chatActions.endpointId, endpointId),+ before(chatActions.createdAt, chatActions.id),+ eq(chatActions.kind, "slash_task_start"),+ ),+ )+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.createdAt})`), desc(chatActions.id))+ .limit(limit),+ db+ .select()+ .from(chatActions)+ .where(+ and(+ eq(chatActions.endpointId, endpointId),+ before(chatActions.createdAt, chatActions.id),+ eq(chatActions.kind, "provider_effect"),+ eq(chatActions.status, "delivery_unknown"),+ ),+ )+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.createdAt})`), desc(chatActions.id))+ .limit(limit),+ db+ .select()+ .from(chatActions)+ .where(+ and(+ eq(chatActions.endpointId, endpointId),+ before(chatActions.createdAt, chatActions.id),+ eq(chatActions.kind, "github_webhook_ingress"),+ eq(chatActions.status, "failed"),+ sql`coalesce(${chatActions.result}->>'retryable', 'false') = 'false'`,+ ),+ )+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.createdAt})`), desc(chatActions.id))+ .limit(limit),+ db+ .select()+ .from(chatActions)+ .where(+ and(+ eq(chatActions.endpointId, endpointId),+ before(chatActions.updatedAt, chatActions.id),+ inArray(chatActions.kind, [+ "slack_session_sync",+ "slack_session_stop",+ ]),+ ),+ )+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.updatedAt})`), desc(chatActions.id))+ .limit(limit),+ db+ .select({+ action: chatActions,+ ingressStatus: recoveryIngress.status,+ })+ .from(chatActions)+ .leftJoin(+ recoveryIngress,+ and(+ eq(recoveryIngress.companyId, chatActions.companyId),+ eq(recoveryIngress.endpointId, chatActions.endpointId),+ eq(recoveryIngress.kind, "github_webhook_ingress"),+ sql`${recoveryIngress.providerActionId} = 'github_webhook_ingress:' || (${chatActions.payload}#>>'{original,guid}')`,+ ),+ )+ .where(+ and(+ eq(chatActions.endpointId, endpointId),+ before(chatActions.updatedAt, chatActions.id),+ eq(chatActions.kind, "github_webhook_recovery"),+ ),+ )+ .orderBy(desc(sql`date_trunc('milliseconds', ${chatActions.updatedAt})`), desc(chatActions.id))+ .limit(limit),+ db+ .select()+ .from(chatSdkState)+ .where(+ and(+ eq(chatSdkState.endpointId, endpointId),+ before(chatSdkState.updatedAt, chatSdkState.id),+ eq(chatSdkState.stateKey, GITHUB_RECOVERY_STATE_KEY),+ ),+ )+ .limit(1),+ ]);+ // A provider effect can be on another page. Replay safety must still+ // consider every unresolved effect associated with these deliveries.+ const ambiguousEffects = deliveries.length ? await db.select({ deliveryId: chatActions.deliveryId })+ .from(chatActions).where(and(+ eq(chatActions.endpointId, endpointId),+ eq(chatActions.kind, "provider_effect"),+ eq(chatActions.status, "delivery_unknown"),+ inArray(chatActions.deliveryId, deliveries.map((row) => row.id)),+ )) : [];+ const ambiguousProviderEffectDeliveryIds = new Set(ambiguousEffects.map((row) => row.deliveryId));+ const transferRows = publications.length+ ? await db+ .select(fileTransferProjectionColumns)+ .from(chatTeamsFileTransfers)+ .innerJoin(+ chatPublications,+ and(+ eq(chatPublications.id, chatTeamsFileTransfers.publicationId),+ eq(chatPublications.companyId, chatTeamsFileTransfers.companyId),+ eq(+ chatPublications.endpointId,+ chatTeamsFileTransfers.endpointId,+ ),+ eq(+ chatPublications.conversationId,+ chatTeamsFileTransfers.conversationId,+ ),+ ),+ )+ .where(+ and(+ eq(chatTeamsFileTransfers.companyId, publications[0]!.companyId),+ eq(chatTeamsFileTransfers.endpointId, endpointId),+ inArray(+ chatTeamsFileTransfers.publicationId,+ publications.map((row) => row.id),+ ),+ ),+ )+ : [];+ const transfers = new Map(+ transferRows.map((row) => [row.publicationId, row]),+ );+ const cancellableConflicts = new Map<string, number>();+ for (const transfer of transferRows) {+ if (transfer.phase !== "conflict") continue;+ const publication = publications.find(+ (row) => row.id === transfer.publicationId,+ );+ if (!publication?.conversationId) continue;+ if (+ await teamsTransferProtocol().canCancelConflict({+ companyId: publication.companyId,+ endpointId,+ conversationId: publication.conversationId,+ publicationId: publication.id,+ version: transfer.version,+ })+ )+ cancellableConflicts.set(publication.id, transfer.version);+ }+ return [+ ...deliveries.map((row) => {+ const normalized =+ row.normalizedEvent &&+ typeof row.normalizedEvent === "object" &&+ !Array.isArray(row.normalizedEvent)+ ? (row.normalizedEvent as Record<string, unknown>)+ : {};+ const deduplication =+ normalized.deduplication &&+ typeof normalized.deduplication === "object" &&+ !Array.isArray(normalized.deduplication)+ ? (normalized.deduplication as Record<string, unknown>)+ : null;+ const duplicateCount =+ typeof deduplication?.duplicateCount === "number"+ ? deduplication.duplicateCount+ : 0;+ const label = row.eventKind.replaceAll("_", " ");+ const outcome =+ row.state === "filtered"+ ? "ignored"+ : row.state === "processed"+ ? "processed"+ : row.state;+ return {+ id: row.id,+ kind: "delivery" as const,+ status: row.state,+ summary: `${label} ${outcome}${duplicateCount ? ` · ${duplicateCount} duplicate${duplicateCount === 1 ? "" : "s"} ignored` : ""}`,+ detail: row.redactedError,+ createdAt: row.createdAt.toISOString(),+ replayable:+ row.state === "failed" &&+ Boolean(row.conversationId) &&+ !ambiguousProviderEffectDeliveryIds.has(row.id),+ resolutionActions: [],+ };+ }),+ ...publications.map((row) => {+ const transfer = transfers.get(row.id);+ const projected = projectChatFileTransfer(+ publicationSummary(row),+ transfer,+ );+ const payload = row.payload as Partial<SafeChatPublicationPayload>;+ const summary = payload.progressState+ ? `${payload.progressState.replaceAll("_", " ")} update`+ : payload.interactionId+ ? "Interactive question"+ : "Response to external conversation";+ return {+ id: row.id,+ kind: "publication" as const,+ status: projected.state,+ summary,+ detail: projected.redactedError ?? null,+ createdAt: row.createdAt.toISOString(),+ replayable: !transfer && row.state === "failed",+ ...(projected.fileTransfer+ ? { fileTransfer: projected.fileTransfer }+ : {}),+ resolutionActions: transfer+ ? chatFileTransferResolutionActions(+ projected,+ cancellableConflicts.has(row.id)+ ? {+ publicationId: row.id,+ version: cancellableConflicts.get(row.id)!,+ }+ : undefined,+ )+ : row.state === "delivery_unknown"+ ? (["mark_delivered", "retry_anyway", "cancel"] as const)+ : [],+ };+ }),+ ...slashActions.map((row) => {+ const recovery = slackSlashTaskRecoveryPayload(row.payload);+ // Keep this GET read-only while still surfacing a crashed attempt as+ // actionable. The resolution POST persists the derived quarantine+ // before it applies the operator's audited decision.+ const status = slackTaskStartActivityStatus(row);+ return {+ id: row.id,+ kind: "action" as const,+ actionType: "slash_task_start" as const,+ status,+ summary: `Slack slash-command task start ${status.replaceAll("_", " ")}`,+ detail:+ status === "delivery_unknown"+ ? recovery+ ? "Slack may have accepted the task-start message, so Paperclip will not replay it automatically. Check Slack first; an explicit retry can create a duplicate starter message and task."+ : "Slack may have accepted the task-start message. This older action lacks the context required for a safe explicit retry, so check Slack and cancel it here before submitting a new command."+ : status === "provider_confirmed"+ ? "Slack accepted the task-start message. Paperclip is completing durable task admission without sending another Slack message."+ : status === "admitting"+ ? "Slack accepted the task-start message. A Paperclip worker is admitting the task without replaying the Slack send."+ : status === "failed"+ ? "Slack rejected the task-start message. Submit the command again to retry."+ : status === "cancelled"+ ? "An operator cancelled this unconfirmed task start."+ : null,+ createdAt: row.createdAt.toISOString(),+ replayable: false,+ resolutionActions:+ status === "delivery_unknown"+ ? recovery+ ? (["retry_anyway", "cancel"] as const)+ : (["cancel"] as const)+ : [],+ };+ }),+ ...providerEffects.map((row) => {+ const payload = providerEffectPayload(row.payload);+ return {+ id: row.id,+ kind: "action" as const,+ actionType: "provider_effect" as const,+ status: row.status,+ summary: "Provider reply delivery unknown",+ detail: payload?.completeConversationId+ ? "The provider may have accepted this reply, but Paperclip could not confirm it or close the task conversation. Check the provider first. Marking it delivered closes the conversation; retrying can create a duplicate message."+ : "The provider may have accepted this reply, but Paperclip could not confirm it. Check the provider first. Retrying can create a duplicate message.",+ createdAt: row.createdAt.toISOString(),+ replayable: false,+ resolutionActions: [+ "mark_delivered",+ "retry_anyway",+ "cancel",+ ] as const,+ };+ }),+ ...slackSessionActions.map((row) => {+ const isSync = row.kind === "slack_session_sync";+ const retrying =+ row.status === "received" &&+ row.result?.code === "slack_session_sync_retry";+ return {+ id: row.id,+ kind: "action" as const,+ actionType: isSync+ ? ("slack_session_sync" as const)+ : ("slack_session_stop" as const),+ status: retrying ? "retry" : row.status,+ summary: isSync ? "Slack session status" : "Slack Stop request",+ detail: isSync+ ? row.result?.outcome === "unavailable"+ ? "Slack has not enabled native session status for this destination. Message delivery continues."+ : row.result?.code === "slack_session_sync_rejected"+ ? "Slack rejected the session indicator update. Check app permissions and channel access; message delivery is tracked separately."+ : retrying+ ? "The Slack session indicator is waiting to sync. Paperclip will not resend the response."+ : row.result?.sessionStatus === "processing"+ ? "Working status is refreshed automatically while the run remains active."+ : null+ : row.status === "processed"+ ? "Paperclip stopped the work authorized by this request."+ : row.status === "cancelled"+ ? "No work was stopped: this request was no longer authorized or its target was no longer current."+ : row.status === "failed"+ ? row.result?.retryable === true+ ? "The Stop request could not finish yet. Paperclip will retry against the original work only."+ : "The Stop request could not be completed. Check the task's current run before trying again."+ : "Paperclip is processing this Stop request against its original task and run.",+ createdAt: row.updatedAt.toISOString(),+ replayable: false,+ resolutionActions: [],+ };+ }),+ ...githubIngressFailures.map((row) => {+ const deliveryId =+ typeof row.payload.deliveryId === "string"+ ? row.payload.deliveryId+ : null;+ return {+ id: row.id,+ kind: "action" as const,+ actionType: "github_webhook_ingress" as const,+ status: row.status,+ summary: "GitHub webhook could not be processed",+ detail: deliveryId+ ? `GitHub delivery ${deliveryId} was authenticated, but Paperclip could not finish processing it. Fix the connection or destination, then redeliver this delivery from the GitHub App's Recent Deliveries page.`+ : "An authenticated GitHub webhook could not be processed. Fix the connection or destination, then redeliver it from the GitHub App's Recent Deliveries page.",+ createdAt: row.createdAt.toISOString(),+ replayable: false,+ resolutionActions: [],+ };+ }),+ ...githubRecoveries.map(({ action: row, ingressStatus }) => ({+ id: row.id,+ kind: "repair" as const,+ status:+ row.status === "cancelled"+ ? "cancelled"+ : ingressStatus+ ? "received"+ : "pending",+ summary:+ row.status === "cancelled"+ ? "GitHub webhook recovery skipped"+ : ingressStatus+ ? "GitHub webhook received after recovery request"+ : "GitHub webhook redelivery requested",+ detail:+ row.status === "cancelled"+ ? row.result?.code === "source_changed_or_unavailable"+ ? "The original comment changed or is no longer available. Paperclip did not replay its old contents."+ : "This callback was not an eligible current user comment. Paperclip did not replay it."+ : ingressStatus+ ? "Paperclip received this callback. Its normal access checks and processing still apply."+ : "Paperclip asked GitHub to resend a recent missed message. This does not yet confirm receipt or a reply. Automatic requests are limited; if it remains unanswered, check the App's Recent Deliveries and send your request again in the current conversation.",+ createdAt: row.updatedAt.toISOString(),+ replayable: false,+ resolutionActions: [],+ })),+ ...githubRecoveryScans.flatMap((row) => {+ const value = row.value as { outcome?: string } | null;+ const detail =+ value?.outcome === "history_limit_reached"+ ? "Recent webhook volume exceeded automatic recovery's bounded scan. No partial history was replayed. Check the App's Recent Deliveries for missed messages."+ : value?.outcome === "callback_mismatch"+ ? "The GitHub App's callback no longer matches this connection. Reconnect the App to repair it; repository access will not change."+ : value?.outcome === "scan_failed"+ ? "Paperclip could not check GitHub's failed deliveries. The check will retry with backoff; normal callbacks are still processed."+ : null;+ return detail+ ? [+ {+ id: row.id,+ kind: "health" as const,+ status: "attention",+ summary: "GitHub webhook recovery needs attention",+ detail,+ createdAt: row.updatedAt.toISOString(),+ replayable: false,+ resolutionActions: [],+ },+ ]+ : [];+ }),+ ]+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id))+ .slice(0, limit);+ }++ async function listActivityPage(endpointId: string, limit = 25, cursor?: string) {+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw badRequest("Activity limit must be between 1 and 100");+ let before: { createdAt: string; id: string } | undefined;+ if (cursor !== undefined) {+ try {+ if (cursor.length > 256) throw new Error("Invalid cursor");+ const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));+ if (!Array.isArray(value) || value.length !== 2+ || typeof value[0] !== "string" || new Date(value[0]).toISOString() !== value[0]+ || typeof value[1] !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value[1])) throw new Error("Invalid cursor");+ before = { createdAt: value[0], id: value[1] };+ } catch { throw badRequest("Invalid activity cursor"); }+ }+ const rows = await listActivity(endpointId, { limit, before });+ const items = rows.slice(0, limit);+ const last = items.at(-1);+ return {+ items,+ nextCursor: rows.length > limit && last+ ? Buffer.from(JSON.stringify([last.createdAt, last.id])).toString("base64url")+ : null,+ };+ }+ return { listConversations, listActivity, listActivityPage };+}diff --git a/server/src/services/chat-channels/discord/gateway-events.ts b/server/src/services/chat-channels/discord/gateway-events.tsnew file mode 100644index 0000000000..e283fdc863--- /dev/null+++ b/server/src/services/chat-channels/discord/gateway-events.ts@@ -0,0 +1,253 @@+import type { EndpointRow, DbTransaction, RuntimeContext, LifecycleRuntimeFence, InternalSetupState } from "../runtime-types.js";++import { notifyChatEndpointWork } from "../../chat-work-notifications.js";++import {+ and,+ eq,+ inArray,+} from "drizzle-orm";++import type { Db } from "@paperclipai/db";++import {+ chatConversations,+ chatEndpointResources,+ chatEndpoints,+ toolConnections,+} from "@paperclipai/db";+import type {+ ChatEndpointSetupState,+} from "@paperclipai/shared";++import {+ type DiscordGatewayCallbackEvent,+} from "../../chat-sdk-runtime.js";++import {+ type ChatProviderLifecycleEffect,+} from "../../chat-provider-lifecycle.js";++import type { EndpointRecord } from "../runtime-types.js";++type DiscordGatewayEventsOptions = {+ ensureDiscordGatewayRuntimeIsCurrent: (endpointId: string, context: RuntimeContext) => Promise<boolean>;+ discordGatewayRuntimeIsCurrent: (endpointId: string, context: RuntimeContext) => boolean;+ runtimeCallbackRecord: (endpointId: string, context: RuntimeContext, statuses: EndpointRow["status"][]) => Promise<EndpointRecord | null>;+ runtimeCallbackEndpoint: (tx: DbTransaction, endpointId: string, context: LifecycleRuntimeFence, statuses: EndpointRow["status"][]) => Promise<EndpointRow | null>;+ applyProviderLifecycleEffect: (endpoint: EndpointRow, effect: ChatProviderLifecycleEffect, context?: RuntimeContext) => Promise<boolean>;+ runtimeGeneration: (setup: ChatEndpointSetupState) => number;+ discordGatewayEventBarrier?: (event: DiscordGatewayCallbackEvent) => Promise<void>;+};++export function createDiscordGatewayEvents(db: Db, options: DiscordGatewayEventsOptions) {+ const { ensureDiscordGatewayRuntimeIsCurrent, discordGatewayRuntimeIsCurrent, runtimeCallbackRecord, runtimeCallbackEndpoint, applyProviderLifecycleEffect, runtimeGeneration } = options;+++ function discordGatewayFailureDetail(+ event: DiscordGatewayCallbackEvent["event"],+ ): string {+ if (event.type === "guild_removed") {+ return "Discord bot was removed from the configured server";+ }+ if (event.type === "guild_unavailable") {+ return "Discord server is temporarily unavailable; reconnecting";+ }+ if (event.type === "disconnected") {+ return `Discord Gateway disconnected${event.code === undefined ? "" : ` (code ${event.code})`}; reconnecting`;+ }+ if (event.type === "failure") {+ const code = event.error.code ?? event.error.status;+ return `Discord Gateway failed${code === undefined ? "" : ` (${String(code).slice(0, 64)})`}; ${event.fatal ? "credentials or privileged intents need attention" : "reconnecting"}`;+ }+ return "Discord Gateway connection needs attention";+ }++ function handleDiscordGatewayEvent(+ callback: DiscordGatewayCallbackEvent,+ context: RuntimeContext,+ ): Promise<void> {+ const pending = (context.discordGatewayEventQueue ?? Promise.resolve())+ .catch(() => undefined)+ .then(() => processDiscordGatewayEvent(callback, context));+ context.discordGatewayEventQueue = pending;+ return pending;+ }++ async function processDiscordGatewayEvent(+ callback: DiscordGatewayCallbackEvent,+ context: RuntimeContext,+ ): Promise<void> {+ if (+ !(await ensureDiscordGatewayRuntimeIsCurrent(+ callback.endpointId,+ context,+ ))+ )+ return;+ if (callback.sequence <= (context.discordGatewaySequence ?? 0)) return;+ context.discordGatewaySequence = callback.sequence;+ await options.discordGatewayEventBarrier?.(callback);+ const record = await runtimeCallbackRecord(callback.endpointId, context, [+ "verifying",+ "active",+ "attention",+ ]);+ if (!record || record.endpoint.provider !== "discord") return;+ const event = callback.event;+ if (event.type === "channel_removed") {+ await applyProviderLifecycleEffect(+ record.endpoint,+ {+ kind: "resource",+ provider: "discord",+ providerEventId: `gateway:channel_removed:${event.channelId}`,+ providerResourceId: event.channelId,+ resourceType: "channel",+ label: event.label?.trim() || event.channelId,+ availability: "removed",+ metadata: { source: "discord_gateway" },+ },+ context,+ );+ return;+ }++ await db.transaction(async (tx) => {+ const current = await runtimeCallbackEndpoint(+ tx,+ callback.endpointId,+ context,+ ["verifying", "active", "attention"],+ );+ if (+ !current ||+ current.provider !== "discord" ||+ !discordGatewayRuntimeIsCurrent(callback.endpointId, context)+ ) {+ return;+ }+ const now = new Date();+ if (event.type === "connecting") {+ await tx+ .update(chatEndpoints)+ .set({+ healthMessage: "Discord Gateway connecting",+ lastError: null,+ lastEventAt: now,+ updatedAt: now,+ })+ .where(eq(chatEndpoints.id, current.id));+ await tx+ .update(toolConnections)+ .set({+ healthStatus: "unchecked",+ healthMessage: "Discord Gateway connecting",+ lastError: null,+ healthCheckedAt: now,+ updatedAt: now,+ })+ .where(eq(toolConnections.id, current.connectionId));+ return;+ }+ if (event.type === "ready" || event.type === "guild_available") {+ const gatewayOwnedAttention =+ current.status === "attention" &&+ current.healthMessage?.startsWith("Discord ") === true;+ if (current.status === "attention" && !gatewayOwnedAttention) return;+ const status =+ current.setup.step === "complete" ? "active" : "verifying";+ if (status !== current.status) await notifyChatEndpointWork(tx);+ await tx+ .update(chatEndpoints)+ .set({+ status,+ healthMessage:+ status === "active"+ ? "Connected"+ : "Waiting for a test conversation",+ lastError: null,+ lastEventAt: now,+ updatedAt: now,+ })+ .where(eq(chatEndpoints.id, current.id));+ await tx+ .update(toolConnections)+ .set({+ status: "active",+ enabled: true,+ healthStatus: "healthy",+ healthMessage: "Connected",+ lastError: null,+ healthCheckedAt: now,+ updatedAt: now,+ })+ .where(eq(toolConnections.id, current.connectionId));+ return;+ }++ const detail = discordGatewayFailureDetail(event);+ const transientGuildOutage = event.type === "guild_unavailable";+ const terminal =+ event.type === "guild_removed" ||+ ((event.type === "failure" || event.type === "disconnected") &&+ event.fatal);+ await tx+ .update(chatEndpoints)+ .set({+ status: transientGuildOutage+ ? current.status+ : event.type === "guild_removed"+ ? "revoked"+ : "attention",+ healthMessage: detail,+ lastError: detail,+ lastEventAt: now,+ ...(terminal+ ? {+ setup: {+ ...current.setup,+ runtimeGeneration: runtimeGeneration(current.setup) + 1,+ } as InternalSetupState,+ }+ : {}),+ updatedAt: now,+ })+ .where(eq(chatEndpoints.id, current.id));+ await tx+ .update(toolConnections)+ .set({+ status: terminal ? "disabled" : "active",+ enabled: !terminal,+ healthStatus: event.type === "guild_removed" ? "failed" : "degraded",+ healthMessage: detail,+ lastError: detail,+ healthCheckedAt: now,+ updatedAt: now,+ })+ .where(eq(toolConnections.id, current.connectionId));+ if (event.type === "guild_removed") {+ await tx+ .update(chatEndpointResources)+ .set({ availability: "unavailable", updatedAt: now })+ .where(+ and(+ eq(chatEndpointResources.companyId, current.companyId),+ eq(chatEndpointResources.endpointId, current.id),+ ),+ );+ await tx+ .update(chatConversations)+ .set({ state: "unavailable", updatedAt: now })+ .where(+ and(+ eq(chatConversations.companyId, current.companyId),+ eq(chatConversations.endpointId, current.id),+ inArray(chatConversations.state, ["active", "waiting"]),+ ),+ );+ }+ });+ }+ return { handleDiscordGatewayEvent };+}diff --git a/server/src/services/chat-channels/discord/messages.ts b/server/src/services/chat-channels/discord/messages.tsindex f61b2a2e8e..61582abed2 100644--- a/server/src/services/chat-channels/discord/messages.ts+++ b/server/src/services/chat-channels/discord/messages.ts@@ -1,3 +1,4 @@+import type { FileUpload } from "chat";import { createHash } from "node:crypto";@@ -28,3 +29,11 @@ export function discordLifecycleFilesDigest(raw: unknown): string {: [];return createHash("sha256").update(JSON.stringify(projection)).digest("hex");}++export function discordMarkdownAttachment(text: string): FileUpload {+ return {+ data: Buffer.from(text, "utf8"),+ filename: "paperclip-response.md",+ mimeType: "text/markdown; charset=utf-8",+ };+ }diff --git a/server/src/services/chat-channels/discord/root-threads.ts b/server/src/services/chat-channels/discord/root-threads.tsnew file mode 100644index 0000000000..1772ce375b--- /dev/null+++ b/server/src/services/chat-channels/discord/root-threads.ts@@ -0,0 +1,570 @@+import type { EndpointRow, DbTransaction, DbOrTransaction, RuntimeContext, LifecycleRuntimeFence, InboundRuntimeContext } from "../runtime-types.js";++import { notifyChatDeliveryWork } from "../../chat-work-notifications.js";++import type { ChatEndpointRuntime } from "../../voice/voice-runtime.js";++import { chatCredentialMutationLease } from "../../chat-credential-mutation-lease.js";++import {+ createHash,+} from "node:crypto";+import {+ and,+ eq,+ inArray,+ sql,+} from "drizzle-orm";++import type { Db } from "@paperclipai/db";++import {+ chatConversations,+ chatDeliveries,+ chatEndpointResources,+ chatEndpoints,+ chatExternalPrincipals,+ companyMemberships,+} from "@paperclipai/db";++import {+ conflict,+} from "../../../errors.js";+import { logger } from "../../../middleware/logger.js";++import {+ DiscordAdapterCompatibilityError,+ type ChatSdkMessageCallbackEvent,+ type DiscordRootMentionAdmissionEvent,+} from "../../chat-sdk-runtime.js";++import { classifyChatPublicationError } from "../../chat-publication-errors.js";++import type {+ Message,+ Thread,+} from "chat";++type DeliveryRow = typeof chatDeliveries.$inferSelect;++type DiscordRootThreadsOptions = {+ ensureDiscordGatewayRuntimeIsCurrent: (endpointId: string, context: RuntimeContext) => Promise<boolean>;+ withCredentialMutationLease: ReturnType<typeof chatCredentialMutationLease>;+ runtimeCallbackEndpoint: (tx: DbTransaction, endpointId: string, context: LifecycleRuntimeFence, statuses: EndpointRow["status"][]) => Promise<EndpointRow | null>;+ lockCurrentPrincipalAuthorization: (tx: DbOrTransaction, endpoint: EndpointRow, principalId: string) => Promise<{ allowed: boolean; linkedDenied: boolean }>;+ processMessage: (endpoint: EndpointRow, thread: Thread, message: Message, trigger: ChatSdkMessageCallbackEvent["trigger"], ingressOnly?: boolean, recoveredProviderUrl?: string | null, runtimeContext?: InboundRuntimeContext, providerUpdateId?: number, admittedDeliveryId?: string | null, receiptReactionSupported?: boolean, preauthorizedUserId?: string | null, deferDrainUntilFollowup?: boolean) => Promise<void>;+ redactError: (error: unknown) => string;+ scheduleConversationDrain: (endpointId: string, threadId: string) => void;+ lifecycleRuntimeFence: (delivery: DeliveryRow) => LifecycleRuntimeFence | null;+ runtimeFor: (endpoint: EndpointRow) => Promise<ChatEndpointRuntime>;+ DISCORD_ROOT_THREAD_CONFIRMATION_DELAY_MS: number;+ discordRootThreadTransportBarrier?: () => Promise<void>;+};++export function createDiscordRootThreads(db: Db, options: DiscordRootThreadsOptions) {+ const { ensureDiscordGatewayRuntimeIsCurrent, withCredentialMutationLease, runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, processMessage, redactError, scheduleConversationDrain, lifecycleRuntimeFence, runtimeFor, DISCORD_ROOT_THREAD_CONFIRMATION_DELAY_MS } = options;+++ async function admitDiscordRootMention(+ configuredEndpoint: EndpointRow,+ event: DiscordRootMentionAdmissionEvent,+ context: RuntimeContext,+ ): Promise<boolean> {+ if (+ !(await ensureDiscordGatewayRuntimeIsCurrent(+ configuredEndpoint.id,+ context,+ ))+ ) {+ return false;+ }+ return withCredentialMutationLease(+ configuredEndpoint,+ async (credentialLease) => {+ const threadId = `discord:${event.guildId}:${event.channelId}:${event.messageId}`;+ const providerEventId = `${threadId}:${event.messageId}`;+ const allowed = await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ const endpoint = await runtimeCallbackEndpoint(+ tx,+ configuredEndpoint.id,+ context,+ ["verifying", "active"],+ );+ const existing = await tx+ .select({ state: chatDeliveries.state })+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.endpointId, configuredEndpoint.id),+ eq(chatDeliveries.providerEventId, providerEventId),+ ),+ )+ .then((rows) => rows[0] ?? null);+ if (+ existing &&+ ["processed", "filtered", "failed"].includes(existing.state)+ )+ return false;++ let reason: string | null = null;+ if (!endpoint || endpoint.providerAccountId !== event.guildId) {+ reason = "Connection is not active";+ }+ const resource = endpoint+ ? await tx+ .select()+ .from(chatEndpointResources)+ .where(+ and(+ eq(chatEndpointResources.endpointId, endpoint.id),+ eq(chatEndpointResources.type, "channel"),+ eq(+ chatEndpointResources.providerResourceId,+ event.channelId,+ ),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null)+ : null;+ const enabledCount =+ endpoint?.status === "verifying"+ ? await tx+ .select({ count: sql<number>`count(*)::int` })+ .from(chatEndpointResources)+ .where(+ and(+ eq(chatEndpointResources.endpointId, endpoint.id),+ eq(chatEndpointResources.type, "channel"),+ eq(chatEndpointResources.enabled, true),+ eq(chatEndpointResources.availability, "available"),+ ),+ )+ .then((rows) => rows[0]?.count ?? 0)+ : 0;+ const setupDestination =+ endpoint?.status === "verifying" &&+ enabledCount === 0 &&+ resource?.availability === "available";+ if (+ !reason &&+ !(+ endpoint?.allowGroupChats &&+ resource?.availability === "available" &&+ (resource.enabled || setupDestination)+ )+ ) {+ reason = "Destination is not enabled in Paperclip";+ }++ if (!reason && endpoint) {+ const principal = await tx+ .select({ id: chatExternalPrincipals.id })+ .from(chatExternalPrincipals)+ .where(+ and(+ eq(chatExternalPrincipals.companyId, endpoint.companyId),+ eq(chatExternalPrincipals.provider, "discord"),+ eq(chatExternalPrincipals.providerAccountId, event.guildId),+ eq(chatExternalPrincipals.externalId, event.userId),+ ),+ )+ .then((rows) => rows[0] ?? null);+ let allowed: boolean;+ let linkedDenied = false;+ if (principal) {+ const authorization = await lockCurrentPrincipalAuthorization(+ tx,+ endpoint,+ principal.id,+ );+ allowed = authorization.allowed;+ linkedDenied = authorization.linkedDenied;+ } else if (!endpoint.allowUnlinkedPeople) {+ allowed = false;+ } else if (!endpoint.sponsorUserId) {+ allowed = true;+ } else {+ const sponsor = await tx+ .select({+ status: companyMemberships.status,+ membershipRole: companyMemberships.membershipRole,+ })+ .from(companyMemberships)+ .where(+ and(+ eq(companyMemberships.companyId, endpoint.companyId),+ eq(companyMemberships.principalType, "user"),+ eq(companyMemberships.principalId, endpoint.sponsorUserId),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ allowed =+ sponsor?.status === "active" &&+ sponsor.membershipRole !== "viewer";+ }+ if (!allowed) {+ reason = linkedDenied+ ? "Linked Paperclip account is not currently permitted"+ : endpoint.allowUnlinkedPeople+ ? "Endpoint sponsor can no longer authorize external guests"+ : "External identity must be linked to a Paperclip account";+ }+ }+ if (!reason) {+ await credentialLease.assertOwned(tx);+ return true;+ }++ const filteredAt = new Date();+ const normalizedEvent = {+ providerEventId,+ kind: "mention",+ trigger: "mention",+ resource: {+ type: "channel",+ providerResourceId: event.channelId,+ },+ conversation: { externalThreadId: threadId },+ message: { providerMessageId: event.messageId },+ filtering: { contentRetained: false, providerThreadCreated: false },+ };+ await notifyChatDeliveryWork(tx);+ await tx+ .insert(chatDeliveries)+ .values({+ companyId: configuredEndpoint.companyId,+ endpointId: configuredEndpoint.id,+ providerEventId,+ deduplicationKey: createHash("sha256")+ .update(providerEventId)+ .digest("hex"),+ eventKind: "mention",+ normalizedEvent,+ state: "filtered",+ redactedError: reason,+ processedAt: filteredAt,+ })+ .onConflictDoUpdate({+ target: [+ chatDeliveries.endpointId,+ chatDeliveries.providerEventId,+ ],+ set: {+ normalizedEvent,+ principalId: null,+ state: "filtered",+ nextAttemptAt: null,+ redactedError: reason,+ processedAt: filteredAt,+ updatedAt: filteredAt,+ },+ });+ await tx+ .update(chatEndpoints)+ .set({ lastEventAt: filteredAt, updatedAt: filteredAt })+ .where(eq(chatEndpoints.id, configuredEndpoint.id));+ await credentialLease.assertOwned(tx);+ return false;+ });+ if (!allowed || !event.message || !context.endpointRuntime) {+ return false;+ }+ const thread = context.endpointRuntime.thread(event.threadId);+ await processMessage(+ configuredEndpoint,+ thread,+ event.message,+ "mention",+ true,+ null,+ context,+ undefined,+ null,+ true,+ undefined,+ true,+ );+ const staged = await db+ .select({ state: chatDeliveries.state })+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.endpointId, configuredEndpoint.id),+ eq(chatDeliveries.providerEventId, providerEventId),+ ),+ )+ .then((rows) => rows[0] ?? null);+ if (+ !staged ||+ !["received", "retry", "processing"].includes(staged.state)+ ) {+ return false;+ }++ await options.discordRootThreadTransportBarrier?.();+ await credentialLease.assertOwned();+ if (+ !(await ensureDiscordGatewayRuntimeIsCurrent(+ configuredEndpoint.id,+ context,+ ))+ ) {+ return false;+ }+ try {+ await context.endpointRuntime.ensureDiscordRootThread({+ channelId: event.channelId,+ content: event.message.text,+ messageId: event.messageId,+ });+ } catch (error) {+ // The durable provisional receipt owns recovery. Do not let a+ // transient REST failure escape the Gateway event handler or ask the+ // adapter to create the same thread outside Paperclip's lifecycle+ // fence.+ logger.warn(+ {+ endpointId: configuredEndpoint.id,+ error: redactError(error),+ providerEventId,+ },+ "Discord root thread creation will be retried from the durable receipt",+ );+ return false;+ }+ const promoted = await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ const current = await runtimeCallbackEndpoint(+ tx,+ configuredEndpoint.id,+ context,+ ["verifying", "active"],+ );+ if (!current) return false;+ await notifyChatDeliveryWork(tx);+ const [row] = await tx+ .update(chatDeliveries)+ .set({+ state: "received",+ normalizedEvent: sql`${chatDeliveries.normalizedEvent} - 'providerThreadPending'`,+ nextAttemptAt: null,+ redactedError: null,+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatDeliveries.endpointId, configuredEndpoint.id),+ eq(chatDeliveries.providerEventId, providerEventId),+ eq(chatDeliveries.state, "retry"),+ sql`${chatDeliveries.normalizedEvent}->>'providerThreadPending' = 'true'`,+ ),+ )+ .returning({ id: chatDeliveries.id });+ await credentialLease.assertOwned(tx);+ return Boolean(row);+ });+ if (promoted)+ scheduleConversationDrain(configuredEndpoint.id, threadId);+ // Paperclip created the provider thread inside its credential/reach+ // lease. Returning false prevents the adapter from creating it again;+ // the durable drain owns the remaining task mutation.+ return false;+ },+ );+ }++ function discordRootThreadPending(+ delivery: Pick<DeliveryRow, "normalizedEvent">,+ ): boolean {+ return (+ Boolean(delivery.normalizedEvent) &&+ typeof delivery.normalizedEvent === "object" &&+ !Array.isArray(delivery.normalizedEvent) &&+ (delivery.normalizedEvent as { providerThreadPending?: unknown })+ .providerThreadPending === true+ );+ }++ async function reconcileDiscordRootThread(+ endpoint: EndpointRow,+ delivery: DeliveryRow,+ threadId: string,+ ): Promise<boolean> {+ try {+ const normalized = delivery.normalizedEvent as {+ message?: { providerMessageId?: unknown; text?: unknown };+ resource?: { providerResourceId?: unknown };+ };+ const discordThreadParts = threadId.split(":");+ const channelId =+ discordThreadParts[0] === "discord" && discordThreadParts.length >= 4+ ? discordThreadParts[2]+ : normalized.resource?.providerResourceId;+ const messageId = normalized.message?.providerMessageId;+ if (typeof channelId !== "string" || typeof messageId !== "string") {+ throw new DiscordAdapterCompatibilityError(+ "the provisional root receipt is missing its channel or message id",+ );+ }+ const runtimeFence = lifecycleRuntimeFence(delivery);+ if (!runtimeFence) {+ throw new DiscordAdapterCompatibilityError(+ "the provisional root receipt is missing its runtime fence",+ );+ }+ return await withCredentialMutationLease(+ endpoint,+ async (credentialLease) => {+ const currentEndpoint = await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ const current = await runtimeCallbackEndpoint(+ tx,+ endpoint.id,+ runtimeFence,+ ["verifying", "active"],+ );+ await credentialLease.assertOwned(tx);+ return current;+ });+ if (!currentEndpoint) {+ throw conflict(+ "Discord root thread credentials or connection state changed before recovery",+ { code: "chat_endpoint_runtime_superseded" },+ );+ }+ const endpointRuntime = await runtimeFor(currentEndpoint);+ await credentialLease.assertOwned();+ await endpointRuntime.ensureDiscordRootThread({+ channelId,+ messageId,+ content:+ typeof normalized.message?.text === "string"+ ? normalized.message.text+ : "Paperclip task",+ });+ return await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ const current = await runtimeCallbackEndpoint(+ tx,+ endpoint.id,+ runtimeFence,+ ["verifying", "active"],+ );+ if (!current) return false;+ await notifyChatDeliveryWork(tx);+ const [promoted] = await tx+ .update(chatDeliveries)+ .set({+ state: "received",+ normalizedEvent: sql`${chatDeliveries.normalizedEvent} - 'providerThreadPending'`,+ nextAttemptAt: null,+ redactedError: null,+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatDeliveries.id, delivery.id),+ eq(chatDeliveries.state, "retry"),+ sql`${chatDeliveries.normalizedEvent}->>'providerThreadPending' = 'true'`,+ ),+ )+ .returning({ id: chatDeliveries.id });+ await credentialLease.assertOwned(tx);+ return Boolean(promoted);+ });+ },+ );+ } catch (error) {+ const disposition = classifyChatPublicationError(+ error,+ delivery.attempts + 1,+ );+ const terminal =+ disposition.kind === "resource_unavailable" ||+ disposition.kind === "failed";+ const retryAfterMs =+ disposition.kind === "retry"+ ? disposition.retryAfterMs+ : DISCORD_ROOT_THREAD_CONFIRMATION_DELAY_MS;+ const now = new Date();+ await db.transaction(async (tx) => {+ if (disposition.kind === "resource_unavailable") {+ const fence = lifecycleRuntimeFence(delivery);+ const normalized = delivery.normalizedEvent as {+ resource?: { providerResourceId?: unknown };+ };+ const providerResourceId = normalized.resource?.providerResourceId;+ const current = fence+ ? await runtimeCallbackEndpoint(tx, endpoint.id, fence, [+ "verifying",+ "active",+ "attention",+ ])+ : null;+ const resource =+ current && typeof providerResourceId === "string"+ ? await tx+ .select({ id: chatEndpointResources.id })+ .from(chatEndpointResources)+ .where(+ and(+ eq(chatEndpointResources.companyId, current.companyId),+ eq(chatEndpointResources.endpointId, current.id),+ eq(+ chatEndpointResources.providerResourceId,+ providerResourceId,+ ),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null)+ : null;+ if (resource) {+ await tx+ .update(chatEndpointResources)+ .set({ availability: "unavailable", updatedAt: now })+ .where(eq(chatEndpointResources.id, resource.id));+ await tx+ .update(chatConversations)+ .set({ state: "unavailable", updatedAt: now })+ .where(+ and(+ eq(chatConversations.companyId, current!.companyId),+ eq(chatConversations.endpointId, current!.id),+ eq(chatConversations.resourceId, resource.id),+ inArray(chatConversations.state, ["active", "waiting"]),+ ),+ );+ }+ }+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ state: terminal ? "filtered" : "retry",+ attempts: delivery.attempts + 1,+ nextAttemptAt: terminal+ ? null+ : new Date(now.getTime() + retryAfterMs),+ processedAt: terminal ? now : null,+ redactedError: terminal+ ? "Discord thread creation was not confirmed"+ : redactError(error),+ updatedAt: now,+ })+ .where(+ and(+ eq(chatDeliveries.id, delivery.id),+ eq(chatDeliveries.state, "retry"),+ sql`${chatDeliveries.normalizedEvent}->>'providerThreadPending' = 'true'`,+ ),+ );+ });+ return false;+ }+ }+ return { admitDiscordRootMention, discordRootThreadPending, reconcileDiscordRootThread };+}diff --git a/server/src/services/chat-channels/inbound-attachments.ts b/server/src/services/chat-channels/inbound-attachments.tsnew file mode 100644index 0000000000..4be37251b6--- /dev/null+++ b/server/src/services/chat-channels/inbound-attachments.ts@@ -0,0 +1,674 @@+import type { EndpointRow, DbTransaction, DbOrTransaction, LifecycleRuntimeFence } from "./runtime-types.js";++import type { ChatEndpointRuntime } from "../voice/voice-runtime.js";++import { takePhotonCompanion } from "../photon/attachments.js";++import { HEIF_CONTENT_TYPES, photonHeifPreview, validatePhotonImage } from "../photon/media.js";++import { PhotonError } from "../photon/cloud.js";++import {+ createHash,+} from "node:crypto";+import {+ and,+ eq,+ inArray,+ isNull,+ ne,+ or,+ sql,+} from "drizzle-orm";++import type { Db } from "@paperclipai/db";++import {+ assets,+ chatActions,+ chatConversations,+ chatDeliveries,+ issueComments,+ issueAttachments,+} from "@paperclipai/db";++import {+ isAllowedContentType,+ MAX_ATTACHMENT_BYTES,+ normalizeContentType,+ normalizeUploadAttachmentContentType,+} from "../../attachment-types.js";++import {+ hasTelegramMediaProvenance,+ identifyTelegramMedia,+ telegramMediaNeedsIdentification,+} from "../chat-telegram-media-intake.js";++import {+ forbidden,+} from "../../errors.js";+import { logger } from "../../middleware/logger.js";++import type { StorageService } from "../../storage/types.js";++import { issueService } from "../issues.js";++import { isExternalChatWaitAuthorizationContention } from "../native-runtime/chat-attachment-reuse.js";++import {+ GITHUB_ATTACHMENT_BATCH_TIMEOUT_MS,+ GitHubAttachmentUnavailableError,+ prepareGitHubPublicAttachment,+} from "../chat-github-attachments.js";++import type {+ Attachment,+} from "chat";++type DeliveryRow = typeof chatDeliveries.$inferSelect;++type InboundAttachmentsOptions = {+ storage?: StorageService;+ authorizeInboundWakeup: (tx: DbOrTransaction, action: typeof chatActions.$inferSelect) => Promise<{ delivery: DeliveryRow; conversation: typeof chatConversations.$inferSelect }>;+ lifecycleRuntimeFence: (delivery: DeliveryRow) => LifecycleRuntimeFence | null;+ sanitizeFilename: (value: string | undefined) => string | null;+ issuesSvc: Pick<ReturnType<typeof issueService>, "createAttachment">;+ isExternalActionAuthorizationChange: (error: unknown) => boolean;+ redactError: (error: unknown) => string;+};++export function createInboundAttachments(db: Db, options: InboundAttachmentsOptions) {+ const { authorizeInboundWakeup, lifecycleRuntimeFence, sanitizeFilename, issuesSvc, isExternalActionAuthorizationChange, redactError } = options;+++ async function ingestAttachments(input: {+ endpoint: EndpointRow;+ endpointRuntime: ChatEndpointRuntime;+ deliveryId: string;+ issueId: string;+ issueCommentId: string;+ attachments: Attachment[];+ attachmentLimitOmissions?: number;+ unavailableReferenceCount?: number;+ actorUserId: string | null;+ }): Promise<{+ storedIds: string[];+ omissionReasons: Record<string, number>;+ }> {+ const omissionReasons: Record<string, number> = {};+ const omit = (reason: string, count = 1) => {+ omissionReasons[reason] = (omissionReasons[reason] ?? 0) + count;+ };+ const boundedAttachments = input.attachments.slice(0, 20);+ const photonDerivatives = new Map<Attachment, { source: Attachment; sourceHash: string; kind: "heif_jpeg_preview" | "live_photo_video" }>();+ const originalPhotonAttachments = new Map<Attachment, string>();+ if (+ input.endpoint.provider === "microsoft-teams" &&+ input.unavailableReferenceCount+ ) {+ // A channel/group reference is not a download capability. Still tell+ // the exact current-turn consumer that those bytes are unavailable,+ // including when there are no ingestible attachments at all.+ omit("download_unavailable", input.unavailableReferenceCount);+ }+ if (+ ["github", "imessage-photon"].includes(input.endpoint.provider) &&+ input.attachmentLimitOmissions+ ) {+ omit("attachment_limit", input.attachmentLimitOmissions);+ }+ if (input.attachments.length > boundedAttachments.length) {+ omit(+ "attachment_limit",+ input.attachments.length - boundedAttachments.length,+ );+ }+ if (!options.storage) {+ if (boundedAttachments.length)+ omit("storage_unavailable", boundedAttachments.length);+ return { storedIds: [], omissionReasons };+ }+ const existingByFingerprint = new Map<string, string[]>();+ const existingAttachments = await db+ .select({+ id: issueAttachments.id,+ byteSize: assets.byteSize,+ contentType: assets.contentType,+ originalFilename: assets.originalFilename,+ sha256: assets.sha256,+ })+ .from(issueAttachments)+ .innerJoin(+ assets,+ and(+ eq(assets.companyId, issueAttachments.companyId),+ eq(assets.id, issueAttachments.assetId),+ ),+ )+ .where(+ and(+ eq(issueAttachments.companyId, input.endpoint.companyId),+ eq(issueAttachments.issueId, input.issueId),+ eq(issueAttachments.issueCommentId, input.issueCommentId),+ ),+ );+ for (const existing of existingAttachments) {+ const fingerprint = JSON.stringify([+ existing.sha256,+ existing.byteSize,+ existing.contentType,+ existing.originalFilename,+ ]);+ const ids = existingByFingerprint.get(fingerprint) ?? [];+ ids.push(existing.id);+ existingByFingerprint.set(fingerprint, ids);+ }+ const storedIds: string[] = [];+ const withCurrentAttachmentAuthorization = async <T>(+ work: (tx: DbTransaction) => Promise<T>,+ enforceUnchangedSource = false,+ telegramMedia?: Attachment,+ ): Promise<T> => {+ for (let attempt = 0; ; attempt++) {+ try {+ return await db.transaction(async (tx) => {+ const action = await tx+ .select()+ .from(chatActions)+ .where(+ and(+ eq(chatActions.companyId, input.endpoint.companyId),+ eq(chatActions.endpointId, input.endpoint.id),+ eq(chatActions.deliveryId, input.deliveryId),+ eq(chatActions.kind, "inbound_wakeup"),+ ),+ )+ .limit(1)+ .then((rows) => rows[0]);+ if (+ !action ||+ !["preparing", "issued", "processing", "processed"].includes(+ action.status,+ ) ||+ action.payload.issueId !== input.issueId ||+ action.payload.commentId !== input.issueCommentId+ )+ throw forbidden(+ "The attachment's current chat admission is unavailable",+ { code: "chat_action_authorization_changed" },+ );+ const current = await authorizeInboundWakeup(tx, action);+ // Delivery settlement/replay can update these receipts without+ // taking the issue lock. Lock in delivery -> action order only+ // after policy authorization; NOWAIT breaks cross-worker lock+ // inversions and the outer loop retries the whole transaction.+ const lockedDelivery = await tx+ .select()+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.companyId, input.endpoint.companyId),+ eq(chatDeliveries.id, input.deliveryId),+ ),+ )+ .for("update", { noWait: true })+ .limit(1)+ .then((rows) => rows[0]);+ const lockedAction = await tx+ .select()+ .from(chatActions)+ .where(+ and(+ eq(chatActions.companyId, input.endpoint.companyId),+ eq(chatActions.id, action.id),+ ),+ )+ .for("update", { noWait: true })+ .limit(1)+ .then((rows) => rows[0]);+ const scopeKeys = [+ "version",+ "issueId",+ "commentId",+ "agentId",+ "sessionGeneration",+ "requestedByActorType",+ "requestedByActorId",+ ] as const;+ if (+ current.delivery.state !== "processing" ||+ !lockedDelivery ||+ !lockedAction ||+ lockedDelivery.state !== "processing" ||+ lockedDelivery.endpointId !== action.endpointId ||+ lockedDelivery.conversationId !== action.conversationId ||+ lockedDelivery.principalId !== action.principalId ||+ lockedDelivery.attempts !== current.delivery.attempts ||+ JSON.stringify(lifecycleRuntimeFence(lockedDelivery)) !==+ JSON.stringify(lifecycleRuntimeFence(current.delivery)) ||+ lockedAction.endpointId !== action.endpointId ||+ lockedAction.deliveryId !== action.deliveryId ||+ lockedAction.conversationId !== action.conversationId ||+ lockedAction.principalId !== action.principalId ||+ lockedAction.kind !== "inbound_wakeup" ||+ !["preparing", "issued", "processing", "processed"].includes(+ lockedAction.status,+ ) ||+ scopeKeys.some(+ (key) => lockedAction.payload[key] !== action.payload[key],+ )+ )+ throw forbidden(+ "The attachment's current chat admission is unavailable",+ { code: "chat_action_authorization_changed" },+ );+ if (enforceUnchangedSource) {+ if (telegramMedia) {+ const normalized = lockedDelivery.normalizedEvent as {+ principal?: { externalId?: string };+ message?: {+ providerMessageId?: string;+ attachments?: Array<{ recovery?: unknown }>;+ };+ };+ const fence = lifecycleRuntimeFence(lockedDelivery);+ const descriptor =+ input.endpointRuntime.attachmentRecoveryDescriptor(+ telegramMedia,+ {+ threadId: current.conversation.externalThreadId,+ messageId: normalized.message?.providerMessageId ?? "",+ principalExternalId: normalized.principal?.externalId,+ runtimeGeneration: fence?.generation,+ credentialFingerprint: fence?.credentialFingerprint,+ },+ );+ if (+ descriptor?.locator.kind !== "telegram_media" ||+ !normalized.message?.attachments?.some((item) => {+ const retained = item.recovery as {+ version?: unknown;+ provider?: unknown;+ locator?: Record<string, unknown>;+ attachment?: Record<string, unknown>;+ } | null;+ return (+ retained?.version === 1 &&+ retained.provider === "telegram" &&+ Object.entries(descriptor.locator).every(+ ([key, value]) => retained.locator?.[key] === value,+ ) &&+ Object.entries(descriptor.attachment).every(+ ([key, value]) => retained.attachment?.[key] === value,+ )+ );+ })+ )+ throw forbidden(+ "The media's admitted source is unavailable",+ { code: "chat_action_authorization_changed" },+ );+ }+ const [source] = await tx+ .select({ id: issueComments.id })+ .from(issueComments)+ .where(+ and(+ eq(issueComments.companyId, input.endpoint.companyId),+ eq(issueComments.issueId, input.issueId),+ eq(issueComments.id, input.issueCommentId),+ isNull(issueComments.deletedAt),+ sql`${issueComments.updatedAt} = ${issueComments.createdAt}`,+ ),+ )+ .for("share", { noWait: true });+ // Lifecycle admission precedes its conversation drain. Pending+ // source changes already invalidate this image download, even+ // when the append-only original comment is still untouched.+ const [lifecycle] = await tx+ .select({ id: chatDeliveries.id })+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.companyId, input.endpoint.companyId),+ eq(chatDeliveries.endpointId, input.endpoint.id),+ or(+ isNull(chatDeliveries.conversationId),+ eq(+ chatDeliveries.conversationId,+ current.conversation.id,+ ),+ ),+ ne(chatDeliveries.state, "filtered"),+ inArray(chatDeliveries.eventKind, [+ "message_updated",+ "message_deleted",+ "message_restored",+ ]),+ sql`${chatDeliveries.normalizedEvent}->'runtimeContext' = ${JSON.stringify(lifecycleRuntimeFence(lockedDelivery))}::jsonb`,+ sql`${chatDeliveries.normalizedEvent}->'message'->>'targetProviderEventId' = ${lockedDelivery.providerEventId}`,+ ),+ )+ .limit(1);+ if (!source || lifecycle)+ throw forbidden(+ "The image's admitted source changed before attachment registration",+ {+ code: "chat_action_authorization_changed",+ },+ );+ }+ return await work(tx);+ });+ } catch (error) {+ if (!isExternalChatWaitAuthorizationContention(error) || attempt >= 4)+ throw error;+ // Retry the complete short transaction; no network/storage work or+ // backoff occurs while governance rows are locked.+ await new Promise((resolve) =>+ setTimeout(resolve, 20 * (attempt + 1)),+ );+ }+ }+ };+ // One shared deadline bounds the sequential batch; an expired batch never+ // starts another GitHub request. Other providers retain their own policy.+ const githubBatchSignal =+ input.endpoint.provider === "github"+ ? AbortSignal.timeout(GITHUB_ATTACHMENT_BATCH_TIMEOUT_MS)+ : undefined;+ // This new image-only lane shares one budget across token acquisition and+ // downloads. DB/storage commit semantics remain explicit and unchanged.+ const teamsInlineBatchSignal =+ input.endpoint.provider === "microsoft-teams"+ ? AbortSignal.timeout(10_000)+ : undefined;+ for (let attachment of boundedAttachments) {+ const teamsInlineImage =+ input.endpoint.provider === "microsoft-teams" &&+ input.endpointRuntime.attachmentRecoveryDescriptor(attachment)?.locator+ .kind === "teams_inline_image";+ const telegramMedia =+ input.endpoint.provider === "telegram" &&+ hasTelegramMediaProvenance(attachment);+ const sourceBoundMedia =+ teamsInlineImage ||+ telegramMedia ||+ input.endpoint.provider === "imessage-photon";+ const requireCurrentAttachmentAuthorization =+ input.endpoint.provider === "github" || sourceBoundMedia;+ try {+ if (teamsInlineImage && teamsInlineBatchSignal?.aborted) {+ omit("download_unavailable");+ continue;+ }+ // GitHub's anonymized upload URLs carry no trustworthy MIME metadata.+ // Resolve public bytes only here, after durable comment admission, and+ // then apply the same storage/type policy as every native attachment.+ if (input.endpoint.provider === "github") {+ await withCurrentAttachmentAuthorization(async () => {});+ attachment = await prepareGitHubPublicAttachment(+ attachment,+ githubBatchSignal,+ async (request, signal) => {+ await withCurrentAttachmentAuthorization(async () => {});+ return (+ (await input.endpointRuntime.resolveGitHubAttachmentComment?.(+ request,+ signal,+ )) ?? null+ );+ },+ );+ }+ if (+ requireCurrentAttachmentAuthorization &&+ input.endpoint.provider !== "github"+ )+ await withCurrentAttachmentAuthorization(+ async () => {},+ sourceBoundMedia,+ telegramMedia ? attachment : undefined,+ );+ if (+ attachment.size !== undefined &&+ attachment.size > MAX_ATTACHMENT_BYTES+ ) {+ omit("declared_too_large");+ continue;+ }+ if (!attachment.fetchData) {+ omit("download_unavailable");+ continue;+ }+ const originalFilename = sanitizeFilename(attachment.name);+ let contentType = normalizeUploadAttachmentContentType({+ contentType: normalizeContentType(+ attachment.mimeType ?? "application/octet-stream",+ ),+ originalFilename,+ isAllowedContentType,+ });+ // Reject a provider-declared type before allocating the downloaded+ // payload. The actual byte length is checked again after the adapter's+ // bounded fetch contract resolves.+ // A filename may infer an Office MIME for ordinary documents, but it+ // must not bypass byte identification for native media without MIME.+ const identifyTelegram =+ telegramMedia &&+ telegramMediaNeedsIdentification(attachment) &&+ normalizeContentType(+ attachment.mimeType ?? "application/octet-stream",+ ) === "application/octet-stream";+ if (!isAllowedContentType(contentType) && !identifyTelegram) {+ omit("unsupported_type");+ continue;+ }+ const fetched = teamsInlineImage+ ? await input.endpointRuntime.fetchTeamsInlineImage(+ attachment,+ teamsInlineBatchSignal!,+ )+ : await attachment.fetchData();+ const body = Buffer.isBuffer(fetched) ? fetched : Buffer.from(fetched);+ if (body.length === 0) {+ omit("empty_download");+ continue;+ }+ if (body.length > MAX_ATTACHMENT_BYTES) {+ omit("downloaded_too_large");+ continue;+ }+ if (identifyTelegram) {+ contentType =+ identifyTelegramMedia(attachment, body) ??+ "application/octet-stream";+ if (!isAllowedContentType(contentType)) {+ omit("unsupported_type");+ continue;+ }+ }+ const photonSourceHash = createHash("sha256")+ .update(body)+ .digest("hex");+ if (input.endpoint.provider === "imessage-photon") {+ await validatePhotonImage(body, contentType);+ const companion = takePhotonCompanion(body);+ if (companion?.unavailable) omit("companion_unavailable");+ else if (companion) {+ const video: Attachment = { type: "video", name: companion.fileName, mimeType: companion.mimeType, size: companion.data.length, fetchData: async () => companion.data };+ photonDerivatives.set(video, { source: attachment, sourceHash: photonSourceHash, kind: "live_photo_video" });+ boundedAttachments.push(video);+ }+ if (+ HEIF_CONTENT_TYPES.has(contentType) &&+ isAllowedContentType("image/jpeg")+ ) {+ try {+ const preview = await photonHeifPreview(body);+ const derivative: Attachment = {+ type: "image",+ name: `${originalFilename} (JPEG preview).jpg`,+ mimeType: "image/jpeg",+ size: preview.length,+ fetchData: async () => preview,+ };+ photonDerivatives.set(derivative, { source: attachment, sourceHash: photonSourceHash, kind: "heif_jpeg_preview" });+ boundedAttachments.push(derivative);+ } catch {+ omit("preview_unavailable");+ }+ }+ }+ const fingerprint = JSON.stringify([+ photonSourceHash,+ body.length,+ contentType,+ originalFilename,+ ]);+ const existingIds = existingByFingerprint.get(fingerprint);+ const existingId = existingIds?.shift();+ if (requireCurrentAttachmentAuthorization) {+ // Revoke during either API resolution or the anonymous byte download+ // must prevent storage and attachment registration for that input.+ await withCurrentAttachmentAuthorization(+ async () => {},+ sourceBoundMedia,+ telegramMedia ? attachment : undefined,+ );+ }+ const registerPhotonProvenance = async (attachmentId: string) => {+ if (input.endpoint.provider !== "imessage-photon") return;+ const relation = photonDerivatives.get(attachment);+ if (!relation) {+ originalPhotonAttachments.set(attachment, attachmentId);+ return;+ }+ const originalAttachmentId =+ originalPhotonAttachments.get(relation.source);+ if (!originalAttachmentId)+ throw new Error("Photon related attachment source is missing");+ await db+ .insert(chatActions)+ .values({+ companyId: input.endpoint.companyId,+ endpointId: input.endpoint.id,+ deliveryId: input.deliveryId,+ kind: relation.kind === "heif_jpeg_preview" ? "attachment_derivative" : "attachment_companion",+ providerActionId: `photon-${relation.kind}:${input.deliveryId}:${originalAttachmentId}`,+ payload: {+ originalAttachmentId,+ derivativeAttachmentId: attachmentId,+ originalSha256: relation.sourceHash,+ derivativeSha256: photonSourceHash,+ kind: relation.kind,+ },+ status: "processed",+ })+ .onConflictDoNothing();+ };+ if (existingId) {+ storedIds.push(existingId);+ await registerPhotonProvenance(existingId);+ continue;+ }+ const stored = await options.storage.putFile({+ companyId: input.endpoint.companyId,+ namespace: `issues/${input.issueId}`,+ originalFilename,+ contentType,+ body,+ });+ const registration = {+ issueId: input.issueId,+ issueCommentId: input.issueCommentId,+ provider: stored.provider,+ objectKey: stored.objectKey,+ contentType: stored.contentType,+ byteSize: stored.byteSize,+ sha256: stored.sha256,+ originalFilename: stored.originalFilename,+ createdByUserId: input.actorUserId,+ };+ let row;+ try {+ row = requireCurrentAttachmentAuthorization+ ? await withCurrentAttachmentAuthorization(+ (tx) =>+ issueService(tx as unknown as Db).createAttachment(+ registration,+ ),+ sourceBoundMedia,+ telegramMedia ? attachment : undefined,+ )+ : await issuesSvc.createAttachment(registration);+ } catch (error) {+ // An explicit authorization denial happens before registration. Do+ // not delete on ambiguous database errors which may have committed.+ if (+ requireCurrentAttachmentAuthorization &&+ isExternalActionAuthorizationChange(error)+ )+ await options.storage+ .deleteObject(input.endpoint.companyId, stored.objectKey)+ .catch(() => undefined);+ throw error;+ }+ storedIds.push(row.id);+ await registerPhotonProvenance(row.id);+ } catch (error) {+ if (isExternalActionAuthorizationChange(error)) throw error;+ if (+ error instanceof PhotonError &&+ ["attachment_not_ready", "network", "quota", "credentials"].includes(+ error.code,+ )+ )+ throw error;+ // Use the closed current-input omission vocabulary consumed by native+ // prompts; provider-specific diagnostics remain redacted log codes.+ omit(+ error instanceof GitHubAttachmentUnavailableError+ ? "download_unavailable"+ : "processing_failed",+ );+ // A malformed or unavailable provider attachment must not strand the+ // durable text delivery. The rejected file is intentionally omitted;+ // the delivery remains auditable through its normalized attachment+ // metadata without persisting provider credentials or download URLs.+ logger.warn(+ {+ endpointId: input.endpoint.id,+ issueId: input.issueId,+ ...(error instanceof GitHubAttachmentUnavailableError+ ? {+ deliveryId: input.deliveryId,+ attachmentDiagnosticCode: error.code,+ }+ : {}),+ attachmentName: sanitizeFilename(attachment.name),+ error: redactError(error),+ },+ "external chat attachment was rejected",+ );+ }+ }+ return { storedIds, omissionReasons };+ }++ function attachmentOmissionDetail(result: {+ omissionReasons: Record<string, number>;+ }): string | null {+ const entries = Object.entries(result.omissionReasons).filter(+ ([, count]) => count > 0,+ );+ const omitted = entries.reduce((total, [, count]) => total + count, 0);+ if (!omitted) return null;+ const reasons = entries+ .map(([reason, count]) => `${reason.replaceAll("_", " ")}: ${count}`)+ .join(", ");+ return `${omitted} external attachment${omitted === 1 ? " was" : "s were"} omitted (${reasons})`;+ }+ return { ingestAttachments, attachmentOmissionDetail };+}diff --git a/server/src/services/chat-channels/microsoft-teams/file-transfer-projection.ts b/server/src/services/chat-channels/microsoft-teams/file-transfer-projection.tsnew file mode 100644index 0000000000..34365a4618--- /dev/null+++ b/server/src/services/chat-channels/microsoft-teams/file-transfer-projection.ts@@ -0,0 +1,18 @@+import { sql } from "drizzle-orm";+import { chatTeamsFileTransfers } from "@paperclipai/db";++export const fileTransferProjectionColumns = {+ publicationId: chatTeamsFileTransfers.publicationId,+ phase: chatTeamsFileTransfers.phase,+ version: chatTeamsFileTransfers.version,+ filename: chatTeamsFileTransfers.filename,+ expiresAt: chatTeamsFileTransfers.expiresAt,+ consentMessageId: chatTeamsFileTransfers.consentMessageId,+ responseActivityId: chatTeamsFileTransfers.responseActivityId,+ fileInfoMessageId: chatTeamsFileTransfers.fileInfoMessageId,+ operatorConfirmed: sql<boolean>`+ coalesce(${chatTeamsFileTransfers.privateState}#>>'{resolution,schema}', '') = 'paperclip.teams.file-resolution.v1'+ and coalesce(${chatTeamsFileTransfers.privateState}#>>'{resolution,action}', '') = 'mark_delivered'+ and coalesce(${chatTeamsFileTransfers.privateState}#>>'{resolution,fromPhase}', '') = 'file_info_unknown'+ `,+};diff --git a/server/src/services/chat-channels/outbound-attachments.ts b/server/src/services/chat-channels/outbound-attachments.tsnew file mode 100644index 0000000000..0f2e3a8b02--- /dev/null+++ b/server/src/services/chat-channels/outbound-attachments.ts@@ -0,0 +1,294 @@+import {+ createHash,+} from "node:crypto";+import {+ and,+ eq,+ inArray,+} from "drizzle-orm";++import type { Db } from "@paperclipai/db";++import {+ assets,+ chatPublications,+ issueAttachments,+} from "@paperclipai/db";+import type {+ SafeChatPublicationPayload,+} from "@paperclipai/shared";++import {+ isAllowedContentType,+ MAX_ATTACHMENT_BYTES,+} from "../../attachment-types.js";++import type { StorageService } from "../../storage/types.js";++import {+ isTeamsInlineImageContentType,+ TEAMS_INLINE_IMAGE_MAX_BYTES,+} from "../chat-teams-inline-images.js";++import type {+ FileUpload,+} from "chat";++const OUTBOUND_ATTACHMENT_STORAGE_TIMEOUT_MS = 10_000;++class OutboundAttachmentHydrationError extends Error {+ readonly code = "CHAT_ATTACHMENT_HYDRATION_FAILED";++ constructor(message: string, cause?: unknown) {+ super(message, cause === undefined ? undefined : { cause });+ this.name = "OutboundAttachmentHydrationError";+ }+}++class OutboundAttachmentValidationError extends Error {+ readonly code = "CHAT_ATTACHMENT_VALIDATION_FAILED";++ constructor(message: string) {+ super(message);+ this.name = "OutboundAttachmentValidationError";+ }+}++function isOutboundAttachmentHydrationError(+ error: unknown,+): error is OutboundAttachmentHydrationError {+ return error instanceof OutboundAttachmentHydrationError;+}++function isOutboundAttachmentValidationError(+ error: unknown,+): error is OutboundAttachmentValidationError {+ return error instanceof OutboundAttachmentValidationError;+}++/**+ * Read one already-authorized attachment before any provider transport starts.+ * The database digest, rather than mutable object-store metadata, is the+ * integrity boundary. Both acquisition and streaming are bounded so a stuck+ * storage backend cannot hold the publication lane indefinitely.+ */+export async function hydrateOutboundAttachment(input: {+ storage: StorageService;+ companyId: string;+ objectKey: string;+ byteSize: number;+ sha256: string;+ filename: string;+ mimeType: string;+ timeoutMs?: number;+}): Promise<FileUpload> {+ const timeoutMs =+ typeof input.timeoutMs === "number" &&+ Number.isFinite(input.timeoutMs) &&+ input.timeoutMs > 0+ ? input.timeoutMs+ : OUTBOUND_ATTACHMENT_STORAGE_TIMEOUT_MS;+ if (+ !Number.isSafeInteger(input.byteSize) ||+ input.byteSize <= 0 ||+ input.byteSize > MAX_ATTACHMENT_BYTES ||+ !/^[0-9a-f]{64}$/iu.test(input.sha256)+ ) {+ throw new OutboundAttachmentHydrationError(+ "Chat publication attachment metadata is invalid",+ );+ }+ const acquisitionTimeoutError = new OutboundAttachmentHydrationError(+ "Chat publication attachment storage read timed out",+ );+ let acquisitionTimedOut = false;+ let rejectAcquisition!: (error: Error) => void;+ const acquisitionTimeout = new Promise<never>((_resolve, reject) => {+ rejectAcquisition = reject;+ });+ const acquisitionTimer = setTimeout(() => {+ acquisitionTimedOut = true;+ rejectAcquisition(acquisitionTimeoutError);+ }, timeoutMs);+ acquisitionTimer.unref?.();+ const objectPromise = Promise.resolve()+ .then(() => input.storage.getObject(input.companyId, input.objectKey))+ .then((object) => {+ if (acquisitionTimedOut) object.stream.destroy();+ return object;+ })+ .catch((error) => {+ throw isOutboundAttachmentHydrationError(error)+ ? error+ : new OutboundAttachmentHydrationError(+ "Chat publication attachment storage read failed",+ error,+ );+ });+ let object: Awaited<ReturnType<StorageService["getObject"]>>;+ try {+ object = await Promise.race([objectPromise, acquisitionTimeout]);+ } finally {+ clearTimeout(acquisitionTimer);+ }++ if (+ object.contentLength !== undefined &&+ object.contentLength !== input.byteSize+ ) {+ object.stream.destroy();+ throw new OutboundAttachmentHydrationError(+ "Chat publication attachment size changed after registration",+ );+ }++ const streamTimeoutError = new OutboundAttachmentHydrationError(+ "Chat publication attachment storage read timed out",+ );+ const streamTimer = setTimeout(() => {+ object.stream.destroy(streamTimeoutError);+ }, timeoutMs);+ streamTimer.unref?.();+ const chunks: Buffer[] = [];+ const digest = createHash("sha256");+ let bytes = 0;+ try {+ for await (const chunk of object.stream) {+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);+ bytes += buffer.length;+ if (bytes > input.byteSize || bytes > MAX_ATTACHMENT_BYTES) {+ object.stream.destroy();+ throw new OutboundAttachmentHydrationError(+ "Chat publication attachment exceeded its streaming byte limit",+ );+ }+ digest.update(buffer);+ chunks.push(buffer);+ }+ } catch (error) {+ throw isOutboundAttachmentHydrationError(error)+ ? error+ : new OutboundAttachmentHydrationError(+ "Chat publication attachment storage read failed",+ error,+ );+ } finally {+ clearTimeout(streamTimer);+ }++ const actualDigest = digest.digest("hex");+ if (bytes !== input.byteSize || actualDigest !== input.sha256.toLowerCase()) {+ if (!object.stream.destroyed) object.stream.destroy();+ throw new OutboundAttachmentHydrationError(+ "Chat publication attachment integrity changed after registration",+ );+ }++ return {+ data: Buffer.concat(chunks, bytes),+ filename: input.filename,+ mimeType: input.mimeType,+ };+}+export { isOutboundAttachmentHydrationError, isOutboundAttachmentValidationError };++type OutboundAttachmentsOptions = { storage?: StorageService; };++export function createOutboundAttachments(db: Db, options: OutboundAttachmentsOptions) {++++ async function publicationFiles(+ publication: typeof chatPublications.$inferSelect,+ payload: SafeChatPublicationPayload,+ preparation: { teamsInlineImagesOnly?: boolean } = {},+ ): Promise<FileUpload[]> {+ if (!payload.attachmentIds?.length) return [];+ try {+ const rows = await db+ .select({+ id: issueAttachments.id,+ issueId: issueAttachments.issueId,+ issueCommentId: issueAttachments.issueCommentId,+ objectKey: assets.objectKey,+ contentType: assets.contentType,+ byteSize: assets.byteSize,+ sha256: assets.sha256,+ originalFilename: assets.originalFilename,+ })+ .from(issueAttachments)+ .innerJoin(assets, eq(issueAttachments.assetId, assets.id))+ .where(+ and(+ eq(issueAttachments.companyId, publication.companyId),+ eq(issueAttachments.issueId, publication.issueId),+ inArray(issueAttachments.id, payload.attachmentIds),+ ),+ );+ const byId = new Map(rows.map((row) => [row.id, row]));+ const orderedRows = payload.attachmentIds.map((attachmentId) => {+ const row = byId.get(attachmentId);+ if (+ !row ||+ (publication.commentId &&+ row.issueCommentId !== publication.commentId) ||+ row.byteSize <= 0 ||+ row.byteSize > MAX_ATTACHMENT_BYTES ||+ !row.objectKey.trim() ||+ !/^[0-9a-f]{64}$/iu.test(row.sha256) ||+ !isAllowedContentType(row.contentType)+ )+ throw new OutboundAttachmentValidationError(+ "Chat publication attachment is invalid or outside its authorized task comment",+ );+ return row;+ });+ // Picture messages have a different Teams contract from arbitrary files.+ // Preserve the normal scope/metadata checks above, but never hydrate a+ // document or oversized image just to discover it needs a task link.+ if (+ preparation.teamsInlineImagesOnly &&+ orderedRows.some(+ (row) =>+ row.byteSize > TEAMS_INLINE_IMAGE_MAX_BYTES ||+ !isTeamsInlineImageContentType(row.contentType),+ )+ ) {+ return [];+ }+ // Authorization and persisted metadata must fail definitively even when+ // storage is unavailable; do not mask an invalid file as a transient outage.+ if (!options.storage)+ throw new OutboundAttachmentHydrationError(+ "Attachment storage is unavailable for chat publication",+ );+ const files: FileUpload[] = [];+ for (const row of orderedRows) {+ files.push(+ await hydrateOutboundAttachment({+ storage: options.storage,+ companyId: publication.companyId,+ objectKey: row.objectKey,+ byteSize: row.byteSize,+ sha256: row.sha256,+ filename: row.originalFilename ?? `attachment-${row.id}`,+ mimeType: row.contentType,+ }),+ );+ }+ return files;+ } catch (error) {+ if (+ isOutboundAttachmentHydrationError(error) ||+ isOutboundAttachmentValidationError(error)+ ) {+ throw error;+ }+ throw new OutboundAttachmentHydrationError(+ "Chat publication attachment preparation failed",+ error,+ );+ }+ }+ return { publicationFiles };+}diff --git a/server/src/services/chat-channels/provider-effects.ts b/server/src/services/chat-channels/provider-effects.tsnew file mode 100644index 0000000000..5ca3b4b178--- /dev/null+++ b/server/src/services/chat-channels/provider-effects.ts@@ -0,0 +1,957 @@+import { createTelegramCallbackNoticeAuthority } from "./telegram/callback-notices.js";++import { slackThreadChannelId } from "./slack/messages.js";++import type { EndpointRow, DbTransaction, DbOrTransaction, LifecycleRuntimeFence } from "./runtime-types.js";++import { baseTeamsConversationId } from "./microsoft-teams/resources.js";++import { dueChatAction, PROVIDER_EFFECT_STALE_MS } from "../chat-action-work.js";++import { notifyChatDeliveryWork, notifyChatActionWork } from "../chat-work-notifications.js";++import type { ChatEndpointRuntime } from "../voice/voice-runtime.js";++import { chatCredentialMutationLease } from "../chat-credential-mutation-lease.js";++import { projectSafeChatPublicationText } from "../chat-publication-projection.js";++import { PhotonChatAdapter } from "../photon/adapter.js";++import {+ and,+ asc,+ eq,+ inArray,+ lte,+ sql,+} from "drizzle-orm";++import {+ teamsConversationId,+} from "../chat-control-chronology.js";++import type { Db } from "@paperclipai/db";++import {+ chatActions,+ chatConversations,+ chatDeliveries,+ chatEndpointResources,+ chatEndpoints,+ toolConnections,+} from "@paperclipai/db";+import type {+ ChatProvider,+} from "@paperclipai/shared";++import {+ parseTelegramCallbackReceipt,+ telegramCallbackThreadId,+ TELEGRAM_PRIVATE_ACTION_UNAVAILABLE,+ type TelegramCallbackReceipt,+} from "../chat-telegram-ephemeral.js";++import { logger } from "../../middleware/logger.js";+import { redactSensitiveText } from "../../redaction.js";++import { classifyChatPublicationError } from "../chat-publication-errors.js";++import type {+ Thread,+} from "chat";++import type { EndpointRecord } from "./runtime-types.js";++type ProviderEffectTarget = {+ post: Thread["post"];+ postEphemeral?: Thread["postEphemeral"];+};+type ProviderEffectPayload = {+ version: 1;+ effect: "thread_message" | "ephemeral_message" | "telegram_callback_notice";+ telegramCallback?: TelegramCallbackReceipt;+ telegramAuthorizationSha256?: string;+ authorizationMode?: "principal" | "safe_notice";+ threadId: string;+ userId?: string;+ text: string;+ fallbackText?: string;+ settleDelivery: boolean;+ completeConversationId?: string;+ resourceId?: string;+ runtimeGeneration: number;+ credentialFingerprint: string;+};++function providerEffectPayload(+ payload: Record<string, unknown>,+): ProviderEffectPayload | null {+ if (+ payload.version !== 1 ||+ (payload.effect !== "thread_message" &&+ payload.effect !== "ephemeral_message" &&+ payload.effect !== "telegram_callback_notice") ||+ typeof payload.threadId !== "string" ||+ !payload.threadId ||+ typeof payload.text !== "string" ||+ !payload.text ||+ typeof payload.settleDelivery !== "boolean" ||+ typeof payload.runtimeGeneration !== "number" ||+ !Number.isSafeInteger(payload.runtimeGeneration) ||+ typeof payload.credentialFingerprint !== "string"+ ) {+ return null;+ }+ if (+ payload.effect === "ephemeral_message" &&+ (typeof payload.userId !== "string" || !payload.userId)+ ) {+ return null;+ }+ for (const key of [+ "authorizationMode",+ "userId",+ "fallbackText",+ "completeConversationId",+ "resourceId",+ ] as const) {+ const value = payload[key];+ if (value !== undefined && (typeof value !== "string" || !value)) {+ return null;+ }+ }+ if (+ payload.authorizationMode !== undefined &&+ payload.authorizationMode !== "principal" &&+ payload.authorizationMode !== "safe_notice"+ ) {+ return null;+ }+ if (payload.effect === "telegram_callback_notice") {+ const receipt = parseTelegramCallbackReceipt(payload.telegramCallback);+ if (+ !receipt ||+ payload.authorizationMode !== "safe_notice" ||+ payload.text !== TELEGRAM_PRIVATE_ACTION_UNAVAILABLE ||+ payload.threadId !== telegramCallbackThreadId(receipt) ||+ payload.userId !== receipt.receiverUserId ||+ payload.settleDelivery !== false ||+ payload.fallbackText !== undefined ||+ payload.completeConversationId !== undefined ||+ typeof payload.telegramAuthorizationSha256 !== "string" ||+ !/^[a-f0-9]{64}$/.test(payload.telegramAuthorizationSha256)+ )+ return null;+ } else if (+ payload.telegramCallback !== undefined ||+ payload.telegramAuthorizationSha256 !== undefined+ )+ return null;+ return payload as ProviderEffectPayload;+}+export type { ProviderEffectTarget, ProviderEffectPayload };+export { providerEffectPayload };++type ProviderEffectsOptions = {+ endpointRecord: (endpointId: string) => Promise<EndpointRecord | null>;+ runtimeCallbackEndpoint: (tx: DbTransaction, endpointId: string, context: LifecycleRuntimeFence, statuses: EndpointRow["status"][]) => Promise<EndpointRow | null>;+ withCredentialMutationLease: ReturnType<typeof chatCredentialMutationLease>;+ runtimeFor: (endpoint: EndpointRow) => Promise<ChatEndpointRuntime>;+ invalidateRuntime: (endpointId: string) => Promise<boolean>;+ lockCurrentPrincipalAuthorization: (tx: DbOrTransaction, endpoint: EndpointRow, principalId: string) => Promise<{ allowed: boolean }>;+ redactError: (error: unknown) => string;+ MAX_ERROR_TEXT: number;+ nonDirectDestinationAllowed: (endpoint: EndpointRow, resource: typeof chatEndpointResources.$inferSelect | null | undefined) => boolean;+ lockTelegramCallbackNoticeAuthority: ReturnType<typeof createTelegramCallbackNoticeAuthority>["lockTelegramCallbackNoticeAuthority"];+};++export function createProviderEffects(db: Db, options: ProviderEffectsOptions) {+ const { endpointRecord, runtimeCallbackEndpoint, withCredentialMutationLease, runtimeFor, invalidateRuntime, lockCurrentPrincipalAuthorization, redactError, MAX_ERROR_TEXT, nonDirectDestinationAllowed, lockTelegramCallbackNoticeAuthority } = options;+++ async function stageProviderEffect(+ database: DbOrTransaction,+ input: {+ endpoint: EndpointRow;+ deliveryId?: string | null;+ conversationId?: string | null;+ principalId?: string | null;+ providerActionId: string;+ payload: Omit<+ ProviderEffectPayload,+ "runtimeGeneration" | "credentialFingerprint"+ >;+ runtimeContext: LifecycleRuntimeFence;+ },+ ) {+ await notifyChatActionWork(database, "provider_effect");+ const [inserted] = await database+ .insert(chatActions)+ .values({+ companyId: input.endpoint.companyId,+ endpointId: input.endpoint.id,+ deliveryId: input.deliveryId ?? null,+ conversationId: input.conversationId ?? null,+ principalId: input.principalId ?? null,+ kind: "provider_effect",+ providerActionId: input.providerActionId,+ payload: {+ ...input.payload,+ runtimeGeneration: input.runtimeContext.generation,+ credentialFingerprint: input.runtimeContext.credentialFingerprint,+ },+ status: "received",+ })+ .onConflictDoNothing()+ .returning();+ if (inserted) return inserted;+ return database+ .select()+ .from(chatActions)+ .where(+ and(+ eq(chatActions.endpointId, input.endpoint.id),+ eq(chatActions.providerActionId, input.providerActionId),+ eq(chatActions.kind, "provider_effect"),+ ),+ )+ .then((rows) => rows[0] ?? null);+ }++ function providerEffectDisposition(+ error: unknown,+ attempt: number,+ providerEffectCompleted: boolean,+ ) {+ if (!providerEffectCompleted)+ return classifyChatPublicationError(error, attempt);+ return {+ kind: "delivery_unknown" as const,+ reason:+ "Provider effect completed, but Paperclip could not confirm its durable result",+ };+ }++ async function finalizeProviderEffectFailure(input: {+ action: typeof chatActions.$inferSelect;+ endpoint: EndpointRow;+ payload: ProviderEffectPayload;+ disposition: ReturnType<typeof providerEffectDisposition>;+ attempt: number;+ }): Promise<boolean> {+ const failure = redactSensitiveText(input.disposition.reason).slice(+ 0,+ MAX_ERROR_TEXT,+ );+ const retryable = input.disposition.kind === "retry";+ const retryAt =+ input.disposition.kind === "retry"+ ? new Date(Date.now() + input.disposition.retryAfterMs)+ : null;+ let invalidateCurrentRuntime = false;+ const finalized = await db.transaction(async (tx) => {+ // Admission locks the endpoint before its delivery. Keep that order+ // when failure settlement also needs to change endpoint/resource health.+ const currentEndpoint =+ input.disposition.kind === "endpoint_attention" ||+ input.disposition.kind === "resource_unavailable"+ ? await runtimeCallbackEndpoint(+ tx,+ input.endpoint.id,+ {+ generation: input.payload.runtimeGeneration,+ credentialFingerprint: input.payload.credentialFingerprint,+ },+ ["verifying", "active"],+ )+ : null;+ await notifyChatActionWork(tx, "provider_effect");+ const [ownedAction] = await tx+ .update(chatActions)+ .set({+ status:+ input.disposition.kind === "delivery_unknown"+ ? "delivery_unknown"+ : "failed",+ result: {+ code: `provider_effect_${input.disposition.kind}`,+ attempts: input.attempt,+ redactedError: failure,+ retryable,+ retryAt: retryAt?.toISOString() ?? null,+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, input.action.id),+ eq(chatActions.status, "processing"),+ sql`(${chatActions.result}->>'attempts')::int = ${input.attempt}`,+ ),+ )+ .returning({ id: chatActions.id });+ if (!ownedAction) return false;+ if (input.payload.settleDelivery && input.action.deliveryId) {+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ state: retryable ? "retry" : "failed",+ nextAttemptAt: retryAt,+ redactedError:+ input.disposition.kind === "delivery_unknown"+ ? `Provider response is unconfirmed: ${failure}`.slice(+ 0,+ MAX_ERROR_TEXT,+ )+ : failure,+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatDeliveries.id, input.action.deliveryId),+ eq(chatDeliveries.state, "processing"),+ ),+ );+ }+ if (input.disposition.kind === "endpoint_attention" && currentEndpoint) {+ await tx+ .update(chatEndpoints)+ .set({+ status: "attention",+ healthMessage: "Provider credentials or permissions need attention",+ lastError: failure,+ updatedAt: new Date(),+ })+ .where(eq(chatEndpoints.id, currentEndpoint.id));+ await tx+ .update(toolConnections)+ .set({+ status: "disabled",+ enabled: false,+ healthStatus: "degraded",+ healthMessage: "Provider credentials or permissions need attention",+ lastError: failure,+ healthCheckedAt: new Date(),+ updatedAt: new Date(),+ })+ .where(eq(toolConnections.id, currentEndpoint.connectionId));+ invalidateCurrentRuntime = true;+ } else if (+ input.disposition.kind === "resource_unavailable" &&+ input.payload.resourceId &&+ currentEndpoint+ ) {+ await tx+ .update(chatEndpointResources)+ .set({ availability: "unavailable", updatedAt: new Date() })+ .where(+ and(+ eq(chatEndpointResources.id, input.payload.resourceId),+ eq(chatEndpointResources.endpointId, currentEndpoint.id),+ ),+ );+ }+ return true;+ });+ if (finalized && invalidateCurrentRuntime) {+ await invalidateRuntime(input.endpoint.id).catch(() => undefined);+ }+ return finalized;+ }++ async function quarantineStaleProviderEffect(+ action: typeof chatActions.$inferSelect,+ ) {+ const payload = providerEffectPayload(action.payload);+ const failure =+ "Provider delivery could not be confirmed after the worker stopped. The effect will not be replayed automatically.";+ await db.transaction(async (tx) => {+ await notifyChatActionWork(tx, "provider_effect");+ const [quarantined] = await tx+ .update(chatActions)+ .set({+ status: "delivery_unknown",+ result: {+ code: "provider_effect_delivery_unknown",+ redactedError: failure,+ retryable: false,+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, action.id),+ eq(chatActions.status, "processing"),+ eq(chatActions.updatedAt, action.updatedAt),+ sql`(${chatActions.result}->>'attempts')::int = ${+ typeof action.result?.attempts === "number"+ ? action.result.attempts+ : -1+ }`,+ lte(+ chatActions.updatedAt,+ new Date(Date.now() - PROVIDER_EFFECT_STALE_MS),+ ),+ ),+ )+ .returning({ id: chatActions.id });+ if (quarantined && payload?.settleDelivery && action.deliveryId) {+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ state: "failed",+ nextAttemptAt: null,+ redactedError: failure,+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatDeliveries.id, action.deliveryId),+ eq(chatDeliveries.state, "processing"),+ ),+ );+ }+ });+ }++ function providerEffectThreadResourceId(+ provider: ChatProvider,+ threadId: string,+ ): string | null {+ if (provider === "slack") {+ return (+ slackThreadChannelId(threadId) ??+ (!threadId.includes(":") ? threadId : null)+ );+ }+ if (provider === "telegram") {+ return /^telegram:([^:]+)/.exec(threadId)?.[1] ?? null;+ }+ if (provider === "github") {+ return /^github:([^:]+)/.exec(threadId)?.[1]?.toLowerCase() ?? null;+ }+ if (provider === "discord") {+ return /^discord:[^:]+:([^:]+)/.exec(threadId)?.[1] ?? null;+ }+ const conversationId = teamsConversationId(threadId);+ return conversationId ? baseTeamsConversationId(conversationId) : null;+ }++ async function lockCurrentProviderEffectAuthorization(+ tx: DbTransaction,+ action: typeof chatActions.$inferSelect,+ endpoint: EndpointRow,+ payload: ProviderEffectPayload,+ ): Promise<boolean> {+ if (payload.effect === "telegram_callback_notice") {+ const receipt = parseTelegramCallbackReceipt(payload.telegramCallback);+ if (!receipt || !action.deliveryId) return false;+ const delivery = await tx+ .select()+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.id, action.deliveryId),+ eq(chatDeliveries.companyId, action.companyId),+ eq(chatDeliveries.endpointId, action.endpointId),+ eq(chatDeliveries.state, "filtered"),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ const retained =+ delivery &&+ parseTelegramCallbackReceipt(delivery.normalizedEvent.telegramCallback);+ if (+ !delivery ||+ delivery.principalId !== action.principalId ||+ retained?.sourceSha256 !== receipt.sourceSha256 ||+ delivery.normalizedEvent.telegramAuthorizationSha256 !==+ payload.telegramAuthorizationSha256+ )+ return false;+ return (+ (await lockTelegramCallbackNoticeAuthority(+ tx,+ endpoint,+ receipt,+ action.principalId,+ )) === payload.telegramAuthorizationSha256+ );+ }+ const conversation = action.conversationId+ ? await tx+ .select()+ .from(chatConversations)+ .where(+ and(+ eq(chatConversations.companyId, endpoint.companyId),+ eq(chatConversations.endpointId, endpoint.id),+ eq(chatConversations.id, action.conversationId),+ inArray(chatConversations.state, ["active", "waiting"]),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null)+ : null;+ if (action.conversationId && !conversation) return false;+ const inferredResourceId = providerEffectThreadResourceId(+ endpoint.provider,+ payload.threadId,+ );+ const resource = await tx+ .select()+ .from(chatEndpointResources)+ .where(+ and(+ eq(chatEndpointResources.companyId, endpoint.companyId),+ eq(chatEndpointResources.endpointId, endpoint.id),+ payload.resourceId || conversation?.resourceId+ ? eq(+ chatEndpointResources.id,+ payload.resourceId ?? conversation!.resourceId!,+ )+ : inferredResourceId+ ? eq(chatEndpointResources.providerResourceId, inferredResourceId)+ : sql`false`,+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ const slackChannelId =+ endpoint.provider === "slack"+ ? slackThreadChannelId(payload.threadId)+ : null;+ const isDirectMessage =+ conversation?.isDirectMessage === true ||+ resource?.type === "direct_message" ||+ Boolean(slackChannelId && /^D[A-Z0-9]+$/i.test(slackChannelId));+ const destinationAllowed = isDirectMessage+ ? endpoint.allowDirectMessages+ : nonDirectDestinationAllowed(endpoint, resource);+ if (payload.authorizationMode === "safe_notice") return true;+ if (!destinationAllowed) return false;+ if (!action.principalId) return false;+ return (+ await lockCurrentPrincipalAuthorization(tx, endpoint, action.principalId)+ ).allowed;+ }++ async function cancelUnauthorizedProviderEffect(+ tx: DbTransaction,+ action: typeof chatActions.$inferSelect,+ attempt: number,+ ): Promise<boolean> {+ await notifyChatActionWork(tx, "provider_effect");+ const [cancelled] = await tx+ .update(chatActions)+ .set({+ status: "cancelled",+ result: {+ attempts: attempt,+ code: "provider_effect_no_longer_authorized",+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, action.id),+ eq(chatActions.status, "processing"),+ sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,+ ),+ )+ .returning({ id: chatActions.id });+ if (!cancelled) return false;+ if (action.deliveryId) {+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ state: "filtered",+ processedAt: new Date(),+ nextAttemptAt: null,+ redactedError:+ "Provider reply was suppressed because current chat authorization changed",+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatDeliveries.id, action.deliveryId),+ eq(chatDeliveries.state, "processing"),+ ),+ );+ }+ return true;+ }++ async function processProviderEffect(+ actionId: string,+ liveTarget?: ProviderEffectTarget,+ ): Promise<"processed" | "pending" | "failed" | "delivery_unknown"> {+ const initial = await db+ .select()+ .from(chatActions)+ .where(+ and(+ eq(chatActions.id, actionId),+ eq(chatActions.kind, "provider_effect"),+ ),+ )+ .then((rows) => rows[0] ?? null);+ if (!initial) return "failed";+ const initialEndpoint = await endpointRecord(initial.endpointId);+ if (!initialEndpoint) return "failed";++ const processClaimedEffect = async () => {+ let action = await db+ .select()+ .from(chatActions)+ .where(eq(chatActions.id, actionId))+ .then((rows) => rows[0] ?? null);+ if (!action) return "failed";+ const payload = providerEffectPayload(action.payload);+ if (!payload) {+ await db.transaction(async (tx) => {+ await notifyChatActionWork(tx, "provider_effect");+ return tx+ .update(chatActions)+ .set({+ status: "failed",+ result: { code: "provider_effect_payload_invalid" },+ updatedAt: new Date(),+ })+ .where(eq(chatActions.id, action.id));+ });+ return "failed";+ }+ if (action.status === "processed") return "processed";+ if (action.status === "delivery_unknown") return "delivery_unknown";+ if (action.status === "processing") {+ if (action.updatedAt > new Date(Date.now() - PROVIDER_EFFECT_STALE_MS))+ return "pending";+ await quarantineStaleProviderEffect(action);+ return "delivery_unknown";+ }+ if (action.status === "failed") {+ if (action.result?.retryable !== true) return "failed";+ const retryAt =+ typeof action.result.retryAt === "string"+ ? new Date(action.result.retryAt)+ : null;+ if (retryAt && retryAt > new Date()) return "pending";+ } else if (action.status !== "received") {+ return "failed";+ }++ const attempt =+ (typeof action.result?.attempts === "number"+ ? action.result.attempts+ : 0) + 1;+ const record = await endpointRecord(action.endpointId);+ let providerEffectCompleted = false;+ try {+ if (!record) {+ throw Object.assign(+ new Error("Chat endpoint is unavailable for this provider effect"),+ { code: "CHAT_PROVIDER_PRETRANSPORT_REJECTED" },+ );+ }+ return await withCredentialMutationLease(+ record.endpoint,+ async (credentialLease) => {+ const claim = await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ const currentAction = await tx+ .select()+ .from(chatActions)+ .where(+ and(+ eq(chatActions.id, action!.id),+ eq(chatActions.kind, "provider_effect"),+ eq(chatActions.status, action!.status),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ if (!currentAction) return null;+ const currentEndpoint = await runtimeCallbackEndpoint(+ tx,+ currentAction.endpointId,+ {+ generation: payload.runtimeGeneration,+ credentialFingerprint: payload.credentialFingerprint,+ },+ ["verifying", "active"],+ );+ const authorized = currentEndpoint+ ? await lockCurrentProviderEffectAuthorization(+ tx,+ currentAction,+ currentEndpoint,+ payload,+ )+ : false;+ await notifyChatActionWork(tx, "provider_effect");+ const [transportClaim] = await tx+ .update(chatActions)+ .set({+ status: "processing",+ result: { attempts: attempt },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, currentAction.id),+ eq(chatActions.status, currentAction.status),+ ),+ )+ .returning();+ if (!transportClaim) return null;+ if (!currentEndpoint || !authorized) {+ const cancelled = await cancelUnauthorizedProviderEffect(+ tx,+ transportClaim,+ attempt,+ );+ if (!cancelled) {+ throw new Error(+ "Provider effect ownership changed before authorization cancellation",+ );+ }+ return { outcome: "cancelled" as const };+ }+ await credentialLease.assertOwned(tx);+ return {+ action: transportClaim,+ endpoint: currentEndpoint,+ outcome: "claimed" as const,+ };+ });+ if (!claim) return "pending";+ if (claim.outcome === "cancelled") return "failed";+ action = claim.action;++ // `processing` is the durable, single-owner transport claim and+ // authorization linearization point. Its transaction has committed+ // before provider I/O begins. The renewable credential lease keeps+ // runtime identity stable without holding database row locks.+ let sent: { id: string; threadId: string } | null = null;+ if (payload.effect === "telegram_callback_notice") {+ sent = await (+ await runtimeFor(claim.endpoint)+ ).sendTelegramCallbackNotice(+ payload.telegramCallback!,+ payload.text,+ );+ } else {+ const target =+ liveTarget ??+ (await runtimeFor(claim.endpoint)).thread(payload.threadId);+ if (payload.effect === "ephemeral_message") {+ if (!target.postEphemeral) {+ if (!payload.fallbackText) {+ throw Object.assign(+ new Error("Provider does not support ephemeral messages"),+ { code: "CHAT_PROVIDER_PRETRANSPORT_REJECTED" },+ );+ }+ sent = await target.post(payload.fallbackText);+ } else {+ try {+ sent = await target.postEphemeral(+ payload.userId!,+ payload.text,+ { fallbackToDM: false },+ );+ } catch (error) {+ if (+ !payload.fallbackText ||+ classifyChatPublicationError(error, attempt).kind !==+ "failed"+ ) {+ throw error;+ }+ }+ if (!sent && payload.fallbackText) {+ sent = await target.post(payload.fallbackText);+ }+ }+ } else if (claim.endpoint.provider === "imessage-photon") {+ const adapter = (await runtimeFor(claim.endpoint)).getProviderAdapter();+ if (!(adapter instanceof PhotonChatAdapter)) throw new Error("Photon runtime unavailable");+ const receipt = await adapter.publish(payload.threadId, `effect:${action.id}`, projectSafeChatPublicationText(payload.text), {+ assertCurrent: async () => { await credentialLease.assertOwned(); },+ });+ sent = { id: receipt.id, threadId: payload.threadId };+ } else {+ sent = await target.post(payload.text);+ }+ }+ if (!sent) {+ throw Object.assign(+ new Error("Provider did not accept the message"),+ { code: "CHAT_PROVIDER_PRETRANSPORT_REJECTED" },+ );+ }+ providerEffectCompleted = true;+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ // A duplicate webhook holds the endpoint while waiting for the+ // delivery's unique-index entry. Lock this endpoint first too,+ // before settling the action/conversation/delivery, so neither+ // transaction can wait on a row already held by the other.+ const currentEndpoint = await runtimeCallbackEndpoint(+ tx,+ claim.endpoint.id,+ {+ generation: payload.runtimeGeneration,+ credentialFingerprint: payload.credentialFingerprint,+ },+ ["verifying", "active"],+ );+ await notifyChatActionWork(tx, "provider_effect");+ const [completed] = await tx+ .update(chatActions)+ .set({+ status: "processed",+ result: {+ attempts: attempt,+ providerMessageId: sent.id,+ threadId: sent.threadId,+ ...(payload.effect === "telegram_callback_notice"+ ? {+ code:+ payload.telegramCallback?.chatType === "private"+ ? "telegram_private_api_accepted"+ : "telegram_ephemeral_api_accepted",+ }+ : {}),+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, action!.id),+ eq(chatActions.status, "processing"),+ sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,+ ),+ )+ .returning({ id: chatActions.id });+ if (!completed) {+ throw new Error(+ "Provider effect ownership changed before commit",+ );+ }+ if (payload.completeConversationId) {+ await tx+ .update(chatConversations)+ .set({ state: "completed", updatedAt: new Date() })+ .where(+ and(+ eq(chatConversations.id, payload.completeConversationId),+ eq(chatConversations.endpointId, claim.endpoint.id),+ inArray(chatConversations.state, ["active", "waiting"]),+ ),+ );+ }+ if (payload.settleDelivery && action!.deliveryId) {+ await notifyChatDeliveryWork(tx);+ const [settled] = await tx+ .update(chatDeliveries)+ .set({+ state: "processed",+ processedAt: new Date(),+ nextAttemptAt: null,+ redactedError: null,+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatDeliveries.id, action!.deliveryId),+ eq(chatDeliveries.state, "processing"),+ ),+ )+ .returning({ id: chatDeliveries.id });+ if (!settled) {+ throw new Error(+ "Provider effect delivery ownership changed before commit",+ );+ }+ }+ if (currentEndpoint) {+ await tx+ .update(chatEndpoints)+ .set({ lastEventAt: new Date(), updatedAt: new Date() })+ .where(eq(chatEndpoints.id, currentEndpoint.id));+ }+ await credentialLease.assertOwned(tx);+ });+ return "processed";+ },+ );+ } catch (error) {+ const disposition = providerEffectDisposition(+ error,+ attempt,+ providerEffectCompleted,+ );+ try {+ await finalizeProviderEffectFailure({+ action,+ endpoint: record?.endpoint ?? initialEndpoint.endpoint,+ payload,+ disposition,+ attempt,+ });+ } catch (finalizationError) {+ if (disposition.kind === "delivery_unknown") {+ throw Object.assign(+ new Error(+ "Provider effect is ambiguous and its durable quarantine failed",+ { cause: finalizationError },+ ),+ { code: "CHAT_PROVIDER_EFFECT_AMBIGUOUS" },+ );+ }+ throw finalizationError;+ }+ throw error;+ }+ };+ return processClaimedEffect();+ }++ async function processPendingProviderEffects(limit = 25) {+ const now = new Date();+ const staleBefore = new Date(now.getTime() - PROVIDER_EFFECT_STALE_MS);+ const actions = await db+ .select()+ .from(chatActions)+ .where(dueChatAction("provider_effect", now.getTime()))+ .orderBy(asc(chatActions.createdAt))+ .limit(limit);+ for (const action of actions) {+ if (action.status === "processing" && action.updatedAt <= staleBefore) {+ await quarantineStaleProviderEffect(action);+ continue;+ }+ try {+ await processProviderEffect(action.id);+ } catch (error) {+ logger.warn(+ {+ endpointId: action.endpointId,+ actionId: action.id,+ error: redactError(error),+ },+ "chat provider effect reconciliation failed",+ );+ }+ }+ return actions.length;+ }+ return { stageProviderEffect, processProviderEffect, processPendingProviderEffects };+}diff --git a/server/src/services/chat-channels/reactions.ts b/server/src/services/chat-channels/reactions.tsnew file mode 100644index 0000000000..83df24432e--- /dev/null+++ b/server/src/services/chat-channels/reactions.ts@@ -0,0 +1,891 @@+import type { EndpointRow, DbTransaction, DbOrTransaction, RuntimeContext, LifecycleRuntimeFence, InboundRuntimeContext } from "./runtime-types.js";++import {+ stableExternalPrincipalId,+} from "./message-lifecycle.js";++import { notifyChatDeliveryWork } from "../chat-work-notifications.js";++import {+ createHash,+} from "node:crypto";+import {+ and,+ asc,+ desc,+ eq,+ gt,+ gte,+ inArray,+ isNull,+ lt,+ lte,+ or,+ sql,+ type SQL,+} from "drizzle-orm";++import {+ externalThreadIdentityCondition,+} from "../chat-control-chronology.js";++import type { Db } from "@paperclipai/db";++import {+ chatConversations,+ chatDeliveries,+ chatEndpointResources,+ chatMessageLinks,+ chatPublications,+} from "@paperclipai/db";+import type {+ ChatEventKind,+ ChatProvider,+} from "@paperclipai/shared";++import { logger } from "../../middleware/logger.js";++import {+ type ChatSdkCallbackEvent,+} from "../chat-sdk-runtime.js";++import type {+ Author,+ ReactionEvent,+} from "chat";++import type { EndpointRecord } from "./runtime-types.js";+import { slackThreadChannelId } from "./slack/messages.js";++// Reactions can beat the transaction that persists a just-sent provider+// message link. Keep that narrow gap durable, but never retain an unbound+// reaction indefinitely or let it enter the ordinary inbound-message FIFO.+const REACTION_LINK_RETRY_DELAY_MS = 250;+const REACTION_LINK_MAX_DELAY_MS = 5_000;+const REACTION_LINK_MAX_ATTEMPTS = 20;+const REACTION_LINK_MAX_AGE_MS = 2 * 60_000;+type DeliveryRow = typeof chatDeliveries.$inferSelect;+type ConversationRow = typeof chatConversations.$inferSelect;++type InboundReactionsOptions = {+ lockCurrentPrincipalAuthorization: (tx: DbOrTransaction, endpoint: EndpointRow, principalId: string) => Promise<{ allowed: boolean }>;+ runtimeCallbackRecord: (endpointId: string, context: RuntimeContext, statuses: EndpointRow["status"][]) => Promise<EndpointRecord | null>;+ runtimeCallbackEndpoint: (tx: DbTransaction, endpointId: string, context: LifecycleRuntimeFence, statuses: EndpointRow["status"][]) => Promise<EndpointRow | null>;+ ensurePrincipal: (endpoint: EndpointRow, author: Author, raw?: unknown) => Promise<{ principal: { id: string } }>;+ durableExternalThreadIdentity: (threadId: string) => string;+ recordCurrentMicrosoftTeamsRoute: (endpoint: EndpointRow, context: InboundRuntimeContext | undefined, threadId: string, raw: unknown) => Promise<void>;+ lifecycleRuntimeFence: (delivery: DeliveryRow) => LifecycleRuntimeFence | null;+ deliveryReady: (delivery: DeliveryRow, now: Date) => boolean;+ redactError: (error: unknown) => string;+ nonDirectDestinationAllowed: (endpoint: EndpointRow, resource: typeof chatEndpointResources.$inferSelect | null | undefined) => boolean;+ reactionLinkPreflightBarrier?: () => Promise<void>;+ reactionReplayEndpointLockBarrier?: () => Promise<void>;+ reactionReplayConversationLockBarrier?: () => Promise<void>;+};++export function createInboundReactions(db: Db, options: InboundReactionsOptions) {+ const { lockCurrentPrincipalAuthorization, runtimeCallbackRecord, runtimeCallbackEndpoint, ensurePrincipal, durableExternalThreadIdentity, recordCurrentMicrosoftTeamsRoute, lifecycleRuntimeFence, deliveryReady, redactError, nonDirectDestinationAllowed } = options;+++ function reactionConversationThreadCondition(+ provider: ChatProvider,+ threadId: string,+ ): SQL | undefined {+ const exact = externalThreadIdentityCondition(+ sql<string>`${chatConversations.externalThreadId}`,+ threadId,+ );+ const slackDmChannel =+ provider === "slack" ? slackThreadChannelId(threadId) : null;+ return slackDmChannel && /^D[A-Z0-9-]*$/i.test(slackDmChannel)+ ? or(+ exact,+ and(+ eq(chatConversations.isDirectMessage, true),+ eq(chatConversations.externalThreadId, `slack:${slackDmChannel}:`),+ ),+ )+ : exact;+ }++ async function reactionConversationForMessage(+ database: DbOrTransaction,+ endpoint: EndpointRow,+ threadId: string,+ providerMessageId: string,+ direction?: "outbound",+ ): Promise<ConversationRow | null> {+ return database+ .select({ conversation: chatConversations })+ .from(chatMessageLinks)+ .innerJoin(+ chatConversations,+ and(+ eq(chatConversations.companyId, chatMessageLinks.companyId),+ eq(chatConversations.endpointId, chatMessageLinks.endpointId),+ eq(chatConversations.id, chatMessageLinks.conversationId),+ ),+ )+ .where(+ and(+ eq(chatMessageLinks.companyId, endpoint.companyId),+ eq(chatMessageLinks.endpointId, endpoint.id),+ eq(chatMessageLinks.providerMessageId, providerMessageId),+ direction ? eq(chatMessageLinks.direction, direction) : undefined,+ reactionConversationThreadCondition(endpoint.provider, threadId),+ ),+ )+ .orderBy(desc(chatConversations.sessionGeneration))+ .limit(1)+ .then((rows) => rows[0]?.conversation ?? null);+ }++ async function lockReactionConversationForMessage(+ tx: DbTransaction,+ endpoint: EndpointRow,+ threadId: string,+ providerMessageId: string,+ direction?: "outbound",+ ): Promise<ConversationRow | null> {+ const candidate = await reactionConversationForMessage(+ tx,+ endpoint,+ threadId,+ providerMessageId,+ direction,+ );+ if (!candidate) return null;+ const current = await tx+ .select()+ .from(chatConversations)+ .where(+ and(+ eq(chatConversations.companyId, endpoint.companyId),+ eq(chatConversations.endpointId, endpoint.id),+ eq(chatConversations.id, candidate.id),+ ),+ )+ // Publication settlement inserts the outbound message link before it+ // updates the endpoint. NO KEY UPDATE serializes state changes while+ // remaining compatible with that link's conversation FK KEY SHARE.+ .for("no key update")+ .then((rows) => rows[0] ?? null);+ if (+ !current ||+ !(current.isDirectMessage+ ? ["active", "waiting", "completed"].includes(current.state)+ : ["active", "waiting"].includes(current.state))+ ) {+ return null;+ }+ const linkStillExists = await tx+ .select({ id: chatMessageLinks.id })+ .from(chatMessageLinks)+ .where(+ and(+ eq(chatMessageLinks.companyId, endpoint.companyId),+ eq(chatMessageLinks.endpointId, endpoint.id),+ eq(chatMessageLinks.conversationId, current.id),+ eq(chatMessageLinks.providerMessageId, providerMessageId),+ direction ? eq(chatMessageLinks.direction, direction) : undefined,+ ),+ )+ .limit(1)+ .then((rows) => rows.length > 0);+ return linkStillExists ? current : null;+ }++ async function streamingReactionConversation(+ database: DbOrTransaction,+ endpoint: EndpointRow,+ threadId: string,+ ): Promise<ConversationRow | null> {+ const candidates = await database+ .selectDistinct({+ conversation: chatConversations,+ sessionGeneration: chatConversations.sessionGeneration,+ })+ .from(chatConversations)+ .innerJoin(+ chatPublications,+ and(+ eq(chatPublications.companyId, chatConversations.companyId),+ eq(chatPublications.endpointId, chatConversations.endpointId),+ eq(chatPublications.conversationId, chatConversations.id),+ ),+ )+ .where(+ and(+ eq(chatConversations.companyId, endpoint.companyId),+ eq(chatConversations.endpointId, endpoint.id),+ or(+ inArray(chatConversations.state, ["active", "waiting"]),+ and(+ eq(chatConversations.isDirectMessage, true),+ eq(chatConversations.state, "completed"),+ ),+ ),+ reactionConversationThreadCondition(endpoint.provider, threadId),+ eq(chatPublications.state, "streaming"),+ ),+ )+ .orderBy(desc(chatConversations.sessionGeneration))+ .limit(2);+ if (candidates.length !== 1) return null;+ return candidates[0]!.conversation;+ }++ async function lockStreamingReactionConversation(+ tx: DbTransaction,+ endpoint: EndpointRow,+ threadId: string,+ ): Promise<ConversationRow | null> {+ const candidate = await streamingReactionConversation(+ tx,+ endpoint,+ threadId,+ );+ if (!candidate) return null;+ const current = await tx+ .select()+ .from(chatConversations)+ .where(+ and(+ eq(chatConversations.companyId, endpoint.companyId),+ eq(chatConversations.endpointId, endpoint.id),+ eq(chatConversations.id, candidate.id),+ or(+ inArray(chatConversations.state, ["active", "waiting"]),+ and(+ eq(chatConversations.isDirectMessage, true),+ eq(chatConversations.state, "completed"),+ ),+ ),+ ),+ )+ // Keep the same lock strength/order as the exact-link path above so an+ // in-flight message-link insert cannot deadlock reaction admission.+ .for("no key update")+ .then((rows) => rows[0] ?? null);+ if (!current) return null;+ const stillStreaming = await tx+ .select({ id: chatPublications.id })+ .from(chatPublications)+ .where(+ and(+ eq(chatPublications.companyId, endpoint.companyId),+ eq(chatPublications.endpointId, endpoint.id),+ eq(chatPublications.conversationId, current.id),+ eq(chatPublications.state, "streaming"),+ ),+ )+ .limit(1)+ .then((rows) => rows.length > 0);+ return stillStreaming ? current : null;+ }++ async function authorizeReactionConversation(+ tx: DbTransaction,+ endpoint: EndpointRow,+ conversation: ConversationRow,+ principalId: string,+ ): Promise<boolean> {+ const resource =+ conversation.resourceId && !conversation.isDirectMessage+ ? await tx+ .select()+ .from(chatEndpointResources)+ .where(+ and(+ eq(chatEndpointResources.companyId, endpoint.companyId),+ eq(chatEndpointResources.endpointId, endpoint.id),+ eq(chatEndpointResources.id, conversation.resourceId),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null)+ : null;+ const destinationAllowed = conversation.isDirectMessage+ ? endpoint.allowDirectMessages+ : nonDirectDestinationAllowed(endpoint, resource);+ if (!destinationAllowed) return false;+ return (await lockCurrentPrincipalAuthorization(tx, endpoint, principalId))+ .allowed;+ }++ async function handleReaction(+ event: ChatSdkCallbackEvent<ReactionEvent>,+ runtimeContext: RuntimeContext,+ ) {+ const record = await runtimeCallbackRecord(+ event.endpointId,+ runtimeContext,+ ["active"],+ );+ if (+ !record ||+ record.endpoint.status !== "active" ||+ record.endpoint.provider !== event.provider ||+ record.endpoint.capabilities.reactions !== true ||+ event.event.user.isMe ||+ event.event.user.isBot === true ||+ event.event.user.isSystem+ ) {+ return;+ }+ // A DM can have a newer task generation while this reaction still belongs+ // to an older linked message. Resolve its exact lineage before choosing a+ // generation; never attach it to the latest task merely sharing the chat.+ // A just-sent provider message can be visible before its publication/link+ // transaction commits. Only that exact thread's streaming publication is+ // enough evidence to stage an otherwise-unbound reaction for replay.+ let conversation = await reactionConversationForMessage(+ db,+ record.endpoint,+ event.event.threadId,+ event.event.messageId,+ );+ await options.reactionLinkPreflightBarrier?.();+ const plausibleStreamingConversation = conversation+ ? null+ : await streamingReactionConversation(+ db,+ record.endpoint,+ event.event.threadId,+ );+ if (!conversation && !plausibleStreamingConversation) {+ // Settlement can commit between the first exact-link lookup and the+ // streaming-publication lookup. Recheck the durable link before treating+ // the callback as an arbitrary unknown message.+ conversation = await reactionConversationForMessage(+ db,+ record.endpoint,+ event.event.threadId,+ event.event.messageId,+ );+ if (!conversation) return;+ }++ const principal = await ensurePrincipal(+ record.endpoint,+ event.event.user,+ event.event.raw,+ );+ let rawFingerprint: string;+ try {+ rawFingerprint = createHash("sha256")+ .update(JSON.stringify(event.event.raw ?? null))+ .digest("hex")+ .slice(0, 24);+ } catch {+ rawFingerprint = "unavailable";+ }+ const eventKind: ChatEventKind = event.event.added+ ? "reaction_added"+ : "reaction_removed";+ const providerEventId = [+ eventKind,+ durableExternalThreadIdentity(event.event.threadId),+ event.event.messageId,+ stableExternalPrincipalId(+ record.endpoint.provider,+ event.event.user,+ event.event.raw,+ ),+ event.event.rawEmoji,+ rawFingerprint,+ ].join(":");+ const normalizedEvent = {+ providerEventId,+ kind: eventKind,+ conversation: { externalThreadId: event.event.threadId },+ message: { providerMessageId: event.event.messageId },+ reaction: {+ emoji: event.event.emoji.name,+ rawEmoji: event.event.rawEmoji,+ added: event.event.added,+ },+ runtimeContext: {+ generation: runtimeContext.generation,+ credentialFingerprint: runtimeContext.credentialFingerprint,+ },+ };+ const admitted = await db.transaction(async (tx) => {+ const currentEndpoint = await runtimeCallbackEndpoint(+ tx,+ event.endpointId,+ runtimeContext,+ ["active"],+ );+ if (!currentEndpoint) return false;+ const linkedConversation = await lockReactionConversationForMessage(+ tx,+ currentEndpoint,+ event.event.threadId,+ event.event.messageId,+ );+ const currentConversation =+ linkedConversation ??+ (await lockStreamingReactionConversation(+ tx,+ currentEndpoint,+ event.event.threadId,+ ));+ if (+ !currentConversation ||+ !(await authorizeReactionConversation(+ tx,+ currentEndpoint,+ currentConversation,+ principal.principal.id,+ ))+ ) {+ return false;+ }+ const now = new Date();+ if (linkedConversation) {+ const expiryCutoff = new Date(now.getTime() - REACTION_LINK_MAX_AGE_MS);+ const hasOutboundLink = await tx+ .select({ id: chatMessageLinks.id })+ .from(chatMessageLinks)+ .where(+ and(+ eq(chatMessageLinks.companyId, currentEndpoint.companyId),+ eq(chatMessageLinks.endpointId, currentEndpoint.id),+ eq(chatMessageLinks.conversationId, linkedConversation.id),+ eq(chatMessageLinks.providerMessageId, event.event.messageId),+ eq(chatMessageLinks.direction, "outbound"),+ ),+ )+ .limit(1)+ .then((rows) => rows.length > 0);+ await notifyChatDeliveryWork(tx);+ const reconciled = hasOutboundLink+ ? await tx+ .update(chatDeliveries)+ .set({+ conversationId: linkedConversation.id,+ state: "processed",+ attempts: sql`${chatDeliveries.attempts} + 1`,+ nextAttemptAt: null,+ processedAt: now,+ redactedError: null,+ updatedAt: now,+ })+ .where(+ and(+ eq(chatDeliveries.endpointId, currentEndpoint.id),+ eq(chatDeliveries.providerEventId, providerEventId),+ inArray(chatDeliveries.state, ["received", "retry"]),+ gt(chatDeliveries.receivedAt, expiryCutoff),+ lt(chatDeliveries.attempts, REACTION_LINK_MAX_ATTEMPTS),+ sql`${chatDeliveries.normalizedEvent}->'runtimeContext'->>'generation' = ${String(runtimeContext.generation)}`,+ sql`${chatDeliveries.normalizedEvent}->'runtimeContext'->>'credentialFingerprint' = ${runtimeContext.credentialFingerprint}`,+ ),+ )+ .returning({ id: chatDeliveries.id })+ : [];+ if (reconciled.length > 0) return true;+ await notifyChatDeliveryWork(tx);+ const expired = await tx+ .update(chatDeliveries)+ .set({+ state: "filtered",+ nextAttemptAt: null,+ processedAt: now,+ redactedError:+ "Reaction target did not become linked before replay expiry",+ updatedAt: now,+ })+ .where(+ and(+ eq(chatDeliveries.endpointId, currentEndpoint.id),+ eq(chatDeliveries.providerEventId, providerEventId),+ inArray(chatDeliveries.state, ["received", "retry"]),+ or(+ lte(chatDeliveries.receivedAt, expiryCutoff),+ gte(chatDeliveries.attempts, REACTION_LINK_MAX_ATTEMPTS),+ ),+ sql`${chatDeliveries.normalizedEvent}->'runtimeContext'->>'generation' = ${String(runtimeContext.generation)}`,+ sql`${chatDeliveries.normalizedEvent}->'runtimeContext'->>'credentialFingerprint' = ${runtimeContext.credentialFingerprint}`,+ ),+ )+ .returning({ id: chatDeliveries.id });+ if (expired.length > 0) return false;+ }+ await notifyChatDeliveryWork(tx);+ const inserted = await tx+ .insert(chatDeliveries)+ .values({+ companyId: currentEndpoint.companyId,+ endpointId: currentEndpoint.id,+ conversationId: linkedConversation?.id ?? null,+ principalId: principal.principal.id,+ providerEventId,+ deduplicationKey: createHash("sha256")+ .update(providerEventId)+ .digest("hex"),+ eventKind,+ normalizedEvent,+ state: linkedConversation ? "processed" : "received",+ attempts: linkedConversation ? 1 : 0,+ nextAttemptAt: linkedConversation+ ? null+ : new Date(now.getTime() + REACTION_LINK_RETRY_DELAY_MS),+ processedAt: linkedConversation ? now : null,+ })+ .onConflictDoNothing()+ .returning({ id: chatDeliveries.id });+ if (inserted.length > 0) return true;+ return tx+ .select({ id: chatDeliveries.id })+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.endpointId, currentEndpoint.id),+ eq(chatDeliveries.providerEventId, providerEventId),+ inArray(chatDeliveries.state, ["received", "retry", "processed"]),+ ),+ )+ .limit(1)+ .then((rows) => rows.length > 0);+ });+ if (admitted) {+ await recordCurrentMicrosoftTeamsRoute(+ record.endpoint,+ runtimeContext,+ event.event.threadId,+ event.event.raw,+ );+ }+ }++ function normalizedPendingReaction(delivery: DeliveryRow): {+ added: boolean;+ emoji: string;+ messageId: string;+ rawEmoji: string;+ runtimeContext: LifecycleRuntimeFence;+ threadId: string;+ } | null {+ if (+ delivery.eventKind !== "reaction_added" &&+ delivery.eventKind !== "reaction_removed"+ ) {+ return null;+ }+ const normalized = delivery.normalizedEvent;+ if (+ !normalized ||+ typeof normalized !== "object" ||+ Array.isArray(normalized)+ ) {+ return null;+ }+ const value = normalized as Record<string, unknown>;+ const conversation = value.conversation;+ const message = value.message;+ const reaction = value.reaction;+ const runtimeContext = lifecycleRuntimeFence(delivery);+ if (+ !conversation ||+ typeof conversation !== "object" ||+ Array.isArray(conversation) ||+ !message ||+ typeof message !== "object" ||+ Array.isArray(message) ||+ !reaction ||+ typeof reaction !== "object" ||+ Array.isArray(reaction) ||+ !runtimeContext+ ) {+ return null;+ }+ const threadId = (conversation as Record<string, unknown>).externalThreadId;+ const messageId = (message as Record<string, unknown>).providerMessageId;+ const reactionRecord = reaction as Record<string, unknown>;+ const added = reactionRecord.added;+ const emoji = reactionRecord.emoji;+ const rawEmoji = reactionRecord.rawEmoji;+ return typeof threadId === "string" &&+ threadId.length > 0 &&+ typeof messageId === "string" &&+ messageId.length > 0 &&+ typeof added === "boolean" &&+ added === (delivery.eventKind === "reaction_added") &&+ typeof emoji === "string" &&+ emoji.length > 0 &&+ typeof rawEmoji === "string" &&+ rawEmoji.length > 0+ ? { added, emoji, messageId, rawEmoji, runtimeContext, threadId }+ : null;+ }++ async function processPendingReactionDelivery(+ candidate: DeliveryRow,+ ): Promise<void> {+ const reaction = normalizedPendingReaction(candidate);+ if (!reaction || !candidate.principalId) {+ const now = new Date();+ await db.transaction(async (tx) => {+ await notifyChatDeliveryWork(tx);+ return tx+ .update(chatDeliveries)+ .set({+ state: "failed",+ nextAttemptAt: null,+ processedAt: now,+ redactedError: "Normalized reaction delivery is incomplete",+ updatedAt: now,+ })+ .where(+ and(+ eq(chatDeliveries.id, candidate.id),+ inArray(chatDeliveries.state, ["received", "retry"]),+ ),+ );+ });+ return;+ }+ const principalId = candidate.principalId;++ await db.transaction(async (tx) => {+ const currentEndpoint = await runtimeCallbackEndpoint(+ tx,+ candidate.endpointId,+ reaction.runtimeContext,+ ["active"],+ );+ let conversation: ConversationRow | null = null;+ let disposition:+ | { kind: "processed"; conversationId: string }+ | { kind: "retry" }+ | { kind: "filtered"; reason: string };++ if (!currentEndpoint) {+ disposition = {+ kind: "filtered",+ reason: "Reaction callback belonged to an unavailable runtime",+ };+ } else {+ await options.reactionReplayEndpointLockBarrier?.();+ conversation = await lockReactionConversationForMessage(+ tx,+ currentEndpoint,+ reaction.threadId,+ reaction.messageId,+ "outbound",+ );+ if (conversation) {+ await options.reactionReplayConversationLockBarrier?.();+ }+ if (conversation) {+ disposition = (await authorizeReactionConversation(+ tx,+ currentEndpoint,+ conversation,+ principalId,+ ))+ ? { kind: "processed", conversationId: conversation.id }+ : {+ kind: "filtered",+ reason:+ "Reaction destination or principal is no longer authorized",+ };+ } else {+ conversation = await lockStreamingReactionConversation(+ tx,+ currentEndpoint,+ reaction.threadId,+ );+ if (conversation) {+ await options.reactionReplayConversationLockBarrier?.();+ }+ if (!conversation) {+ disposition = {+ kind: "filtered",+ reason: "Reaction target was not linked to a sent message",+ };+ } else {+ disposition = (await authorizeReactionConversation(+ tx,+ currentEndpoint,+ conversation,+ principalId,+ ))+ ? { kind: "retry" }+ : {+ kind: "filtered",+ reason:+ "Reaction destination or principal is no longer authorized",+ };+ }+ }+ }++ // Endpoint, conversation, destination and identity locks are acquired+ // before the delivery row so pause/revoke and replay use one lock order.+ const locked = await tx+ .select()+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.id, candidate.id),+ inArray(chatDeliveries.state, ["received", "retry"]),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ // Authorization locks may wait behind a concurrent lifecycle mutation.+ // Sample the expiry clock only after this delivery is exclusively held.+ const decisionAt = new Date();+ if (!locked || !deliveryReady(locked, decisionAt)) return;+ const lockedReaction = normalizedPendingReaction(locked);+ if (+ !lockedReaction ||+ lockedReaction.runtimeContext.generation !==+ reaction.runtimeContext.generation ||+ lockedReaction.runtimeContext.credentialFingerprint !==+ reaction.runtimeContext.credentialFingerprint+ ) {+ disposition = {+ kind: "filtered",+ reason: "Reaction delivery identity changed before replay",+ };+ }++ const nextAttempts = locked.attempts + 1;+ const expired =+ decisionAt.getTime() - locked.receivedAt.getTime() >=+ REACTION_LINK_MAX_AGE_MS;+ if (expired || locked.attempts >= REACTION_LINK_MAX_ATTEMPTS) {+ disposition = {+ kind: "filtered",+ reason: "Reaction target did not become linked before replay expiry",+ };+ }+ if (disposition.kind === "retry" && !expired) {+ if (nextAttempts < REACTION_LINK_MAX_ATTEMPTS) {+ const delay = Math.min(+ REACTION_LINK_RETRY_DELAY_MS *+ 2 ** Math.min(Math.max(locked.attempts, 0), 5),+ REACTION_LINK_MAX_DELAY_MS,+ );+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set({+ state: "retry",+ attempts: nextAttempts,+ nextAttemptAt: new Date(decisionAt.getTime() + delay),+ redactedError: "Waiting for the sent message link",+ updatedAt: decisionAt,+ })+ .where(+ and(+ eq(chatDeliveries.id, locked.id),+ eq(chatDeliveries.state, locked.state),+ eq(chatDeliveries.attempts, locked.attempts),+ ),+ );+ return;+ }+ disposition = {+ kind: "filtered",+ reason: "Reaction target did not become linked before retry expiry",+ };+ } else if (disposition.kind === "retry") {+ disposition = {+ kind: "filtered",+ reason: "Reaction target did not become linked before age expiry",+ };+ }++ const processedAt = new Date();+ await notifyChatDeliveryWork(tx);+ await tx+ .update(chatDeliveries)+ .set(+ disposition.kind === "processed"+ ? {+ conversationId: disposition.conversationId,+ state: "processed",+ attempts: nextAttempts,+ nextAttemptAt: null,+ processedAt,+ redactedError: null,+ updatedAt: processedAt,+ }+ : {+ state: "filtered",+ attempts: nextAttempts,+ nextAttemptAt: null,+ processedAt,+ redactedError: disposition.reason,+ updatedAt: processedAt,+ },+ )+ .where(+ and(+ eq(chatDeliveries.id, locked.id),+ eq(chatDeliveries.state, locked.state),+ eq(chatDeliveries.attempts, locked.attempts),+ ),+ );+ });+ }++ async function processPendingReactionDeliveries(+ limit: number,+ onlyDeliveryId?: string,+ ): Promise<number> {+ const now = new Date();+ const candidates = await db+ .select()+ .from(chatDeliveries)+ .where(+ and(+ sql`not exists (select 1 from chat_endpoints e where e.id = ${chatDeliveries.endpointId} and e.provider = 'agentmail')`,+ onlyDeliveryId ? eq(chatDeliveries.id, onlyDeliveryId) : undefined,+ inArray(chatDeliveries.eventKind, [+ "reaction_added",+ "reaction_removed",+ ]),+ or(+ and(+ eq(chatDeliveries.state, "received"),+ or(+ isNull(chatDeliveries.nextAttemptAt),+ lte(chatDeliveries.nextAttemptAt, now),+ ),+ ),+ and(+ eq(chatDeliveries.state, "retry"),+ or(+ isNull(chatDeliveries.nextAttemptAt),+ lte(chatDeliveries.nextAttemptAt, now),+ ),+ ),+ ),+ ),+ )+ .orderBy(asc(chatDeliveries.receivedAt), asc(chatDeliveries.id))+ .limit(limit);+ for (const candidate of candidates) {+ try {+ await processPendingReactionDelivery(candidate);+ } catch (error) {+ logger.warn(+ {+ endpointId: candidate.endpointId,+ deliveryId: candidate.id,+ error: redactError(error),+ },+ "chat reaction-link reconciliation failed",+ );+ }+ }+ return candidates.length;+ }+ return { handleReaction, processPendingReactionDeliveries };+}diff --git a/server/src/services/chat-channels/receipt-reactions.ts b/server/src/services/chat-channels/receipt-reactions.tsnew file mode 100644index 0000000000..a733091a12--- /dev/null+++ b/server/src/services/chat-channels/receipt-reactions.ts@@ -0,0 +1,586 @@+import type { ChatRuntime } from "../chat-runtime.js";+import type { EndpointRow, RuntimeContext, LifecycleRuntimeFence } from "./runtime-types.js";++import { dueChatAction, PROVIDER_EFFECT_STALE_MS } from "../chat-action-work.js";++import { notifyChatActionWork } from "../chat-work-notifications.js";++import type { ChatEndpointRuntime } from "../voice/voice-runtime.js";++import {+ receiptReactionPayload,+ type ReceiptReactionPayload,+} from "../chat-receipt-reactions.js";++import { chatCredentialMutationLease, type CredentialMutationLeaseGuard } from "../chat-credential-mutation-lease.js";++import {+ and,+ asc,+ eq,+ like,+ sql,+} from "drizzle-orm";++import type { Db } from "@paperclipai/db";++import {+ chatActions,+ chatDeliveries,+ chatEndpoints,+ toolConnections,+} from "@paperclipai/db";+import type {+ ChatEndpointSetupState,+ ChatProvider,+ ToolCredentialSecretRef,+} from "@paperclipai/shared";++import {+ parseGitHubReceiptIdentity,+ type GitHubReceiptIdentity,+} from "../chat-github-receipt-reactions.js";++import { logger } from "../../middleware/logger.js";++import { classifyChatPublicationError } from "../chat-publication-errors.js";++import type {+ Message,+ Thread,+} from "chat";++import type { EndpointRecord } from "./runtime-types.js";+import { isSlackReceiptReactionAlreadyApplied } from "./slack/messages.js";++type ReceiptReactionsOptions = {+ endpointRecord: (endpointId: string) => Promise<EndpointRecord | null>;+ runtimeContextForRecord: (record: EndpointRecord) => RuntimeContext;+ withCredentialMutationLease: ReturnType<typeof chatCredentialMutationLease>;+ runtimeFor: (endpoint: EndpointRow) => Promise<ChatEndpointRuntime>;+ fetchImpl: typeof fetch;+ runtime: Pick<ChatRuntime, "get">;+ runtimeGeneration: (setup: ChatEndpointSetupState) => number;+ credentialFingerprint: (refs: ToolCredentialSecretRef[]) => string;+ redactError: (error: unknown) => string;+ MAX_ERROR_TEXT: number;+ receiptReactionTransportBarrier?: () => Promise<void>;+};++export function createReceiptReactions(db: Db, options: ReceiptReactionsOptions) {+ const { endpointRecord, runtimeContextForRecord, withCredentialMutationLease, runtimeFor, fetchImpl, runtime, runtimeGeneration, credentialFingerprint, redactError, MAX_ERROR_TEXT } = options;+++ async function addReceiptReaction(input: {+ deliveryId: string;+ endpoint: EndpointRow;+ message: Message;+ runtimeContext?: LifecycleRuntimeFence;+ thread: Thread;+ }): Promise<void> {+ // GitHub acknowledges through one editable response comment. Continue to+ // drain legacy eyes removals, but never create new eyes for these requests.+ if (input.endpoint.provider === "github") return;+ const record = await endpointRecord(input.endpoint.id);+ if (!record) return;+ // A live SDK object remains bound to the credentials that authenticated+ // its callback. Preserve that original fence rather than sampling the+ // endpoint again after a rotation and accidentally blessing an obsolete+ // adapter with the new generation.+ const context = input.runtimeContext ?? runtimeContextForRecord(record);+ const [inserted] = await db.transaction(async (tx) => {+ await notifyChatActionWork(tx, "receipt_reaction");+ return tx+ .insert(chatActions)+ .values({+ companyId: input.endpoint.companyId,+ endpointId: input.endpoint.id,+ deliveryId: input.deliveryId,+ kind: "receipt_reaction",+ providerActionId: `receipt_reaction:${input.deliveryId}`,+ payload: {+ version: 1,+ operation: "add",+ threadId: input.thread.id,+ messageId: input.message.id,+ reaction: "eyes",+ runtimeGeneration: context.generation,+ credentialFingerprint: context.credentialFingerprint,+ } satisfies ReceiptReactionPayload,+ status: "received",+ })+ .onConflictDoNothing()+ .returning({ id: chatActions.id });+ });+ const actionId =+ inserted?.id ??+ (await db+ .select({ id: chatActions.id })+ .from(chatActions)+ .where(+ and(+ eq(chatActions.endpointId, input.endpoint.id),+ eq(+ chatActions.providerActionId,+ `receipt_reaction:${input.deliveryId}`,+ ),+ ),+ )+ .then((rows) => rows[0]?.id ?? null));+ if (!actionId) return;+ await options.receiptReactionTransportBarrier?.();+ await processReceiptReaction(actionId);+ }++ async function processReceiptReaction(actionId: string): Promise<void> {+ const initialAction = await db+ .select({ endpointId: chatActions.endpointId })+ .from(chatActions)+ .where(+ and(+ eq(chatActions.id, actionId),+ eq(chatActions.kind, "receipt_reaction"),+ ),+ )+ .then((rows) => rows[0] ?? null);+ if (!initialAction) return;+ const initialEndpoint = await endpointRecord(initialAction.endpointId);+ if (!initialEndpoint) return;+ // Receipt reactions are GitHub repository mutations too. Serialize their+ // final runtime-fence check and provider call with reconnect, secret+ // rotation, pause, and removal so credentials cannot become obsolete+ // between authorization and transport.+ await withCredentialMutationLease(initialEndpoint.endpoint, (lease) =>+ processReceiptReactionWithCredentialLease(actionId, lease),+ );+ }++ async function processReceiptReactionWithCredentialLease(+ actionId: string,+ credentialLease: CredentialMutationLeaseGuard,+ ): Promise<void> {+ let action = await db+ .select()+ .from(chatActions)+ .where(+ and(+ eq(chatActions.id, actionId),+ eq(chatActions.kind, "receipt_reaction"),+ ),+ )+ .then((rows) => rows[0] ?? null);+ if (!action || ["processed", "cancelled"].includes(action.status)) return;+ const payload = receiptReactionPayload(action.payload);+ if (!payload) {+ await db.transaction(async (tx) => {+ await notifyChatActionWork(tx, "receipt_reaction");+ return tx+ .update(chatActions)+ .set({+ status: "failed",+ result: {+ code: "receipt_reaction_payload_invalid",+ retryable: false,+ },+ updatedAt: new Date(),+ })+ .where(eq(chatActions.id, action.id));+ });+ return;+ }+ if (payload.operation === "add" && action.deliveryId) {+ const terminalRemoval = await db+ .select({ id: chatActions.id })+ .from(chatActions)+ .where(+ and(+ eq(chatActions.endpointId, action.endpointId),+ eq(+ chatActions.providerActionId,+ `receipt_reaction_remove:${action.deliveryId}`,+ ),+ ),+ )+ .then((rows) => rows[0] ?? null);+ if (terminalRemoval) {+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ await notifyChatActionWork(tx, "receipt_reaction");+ await tx+ .update(chatActions)+ .set({+ status: "cancelled",+ result: {+ ...(typeof action!.result?.attempts === "number"+ ? { attempts: action!.result.attempts }+ : {}),+ code: "receipt_reaction_superseded_by_terminal_publication",+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, action!.id),+ eq(chatActions.status, action!.status),+ ),+ );+ await credentialLease.assertOwned(tx);+ });+ return;+ }+ }+ if (action.status === "processing") {+ if (action.updatedAt > new Date(Date.now() - PROVIDER_EFFECT_STALE_MS))+ return;+ // Adding or removing the same reaction is idempotent. A worker+ // interruption can be retried safely without an ambiguous+ // duplicate-message boundary.+ await db.transaction(async (tx) => {+ await notifyChatActionWork(tx, "receipt_reaction");+ return tx+ .update(chatActions)+ .set({+ status: "failed",+ result: {+ ...(action.result ?? {}),+ retryable: true,+ retryAt: new Date().toISOString(),+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, action.id),+ eq(chatActions.status, "processing"),+ eq(chatActions.updatedAt, action.updatedAt),+ ),+ );+ });+ action = await db+ .select()+ .from(chatActions)+ .where(eq(chatActions.id, action.id))+ .then((rows) => rows[0] ?? null);+ if (!action) return;+ }+ if (action.status === "failed") {+ if (action.result?.retryable !== true) return;+ const retryAt =+ typeof action.result.retryAt === "string"+ ? new Date(action.result.retryAt)+ : null;+ if (retryAt && retryAt > new Date()) return;+ } else if (action.status !== "received") {+ return;+ }+ const attempt =+ (typeof action.result?.attempts === "number" ? action.result.attempts : 0) ++ 1;+ const retainedGitHubReceipt = parseGitHubReceiptIdentity(+ action.result?.githubReceipt,+ );+ const [claimed] = await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ await notifyChatActionWork(tx, "receipt_reaction");+ const rows = await tx+ .update(chatActions)+ .set({+ status: "processing",+ result: {+ attempts: attempt,+ ...(retainedGitHubReceipt+ ? { githubReceipt: retainedGitHubReceipt }+ : {}),+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, action!.id),+ eq(chatActions.status, action!.status),+ ),+ )+ .returning();+ await credentialLease.assertOwned(tx);+ return rows;+ });+ if (!claimed) return;++ let reactionProvider: ChatProvider | null = null;+ let githubReceipt: GitHubReceiptIdentity | null = retainedGitHubReceipt;+ try {+ const record = await endpointRecord(action.endpointId);+ if (+ !record ||+ !["verifying", "active"].includes(record.endpoint.status) ||+ runtimeGeneration(record.endpoint.setup) !== payload.runtimeGeneration ||+ credentialFingerprint(record.credentialSecretRefs) !==+ payload.credentialFingerprint+ ) {+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ await notifyChatActionWork(tx, "receipt_reaction");+ await tx+ .update(chatActions)+ .set({+ status: "cancelled",+ result: {+ attempts: attempt,+ code: "receipt_reaction_runtime_superseded",+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, action!.id),+ eq(chatActions.status, "processing"),+ sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,+ ),+ );+ await credentialLease.assertOwned(tx);+ });+ return;+ }+ reactionProvider = record.endpoint.provider;+ // Resolve the adapter only after acquiring the credential lease and+ // proving the action's durable generation/fingerprint is still current.+ // Never reuse the live callback's adapter: it may hold an installation+ // token minted by a superseded private key.+ const endpointRuntime = await runtimeFor(record.endpoint);+ const adapter = endpointRuntime.thread(payload.threadId).adapter;+ await credentialLease.assertOwned();+ if (record.endpoint.provider === "slack") {+ await endpointRuntime.applySlackReceiptReaction(payload, fetchImpl);+ } else if (record.endpoint.provider === "github") {+ const assertCurrent = async () => {+ await credentialLease.assertOwned();+ const [current] = await db+ .select({ endpoint: chatEndpoints, connection: toolConnections })+ .from(chatEndpoints)+ .innerJoin(+ toolConnections,+ and(+ eq(toolConnections.id, chatEndpoints.connectionId),+ eq(toolConnections.companyId, chatEndpoints.companyId),+ ),+ )+ .where(+ and(+ eq(chatEndpoints.id, action!.endpointId),+ eq(chatEndpoints.companyId, action!.companyId),+ ),+ )+ .limit(1);+ if (+ !current ||+ !["active", "verifying"].includes(current.endpoint.status) ||+ !current.connection.enabled ||+ current.connection.status !== "active" ||+ runtimeGeneration(current.endpoint.setup) !==+ payload.runtimeGeneration ||+ credentialFingerprint(current.connection.credentialSecretRefs) !==+ payload.credentialFingerprint ||+ runtime.get(action!.endpointId) !== endpointRuntime+ )+ throw new Error("GitHub receipt authority is no longer current");+ };+ const applied = await endpointRuntime.applyGitHubReceiptReaction(+ { ...payload, ...(githubReceipt ? { githubReceipt } : {}) },+ assertCurrent,+ fetchImpl,+ );+ githubReceipt = parseGitHubReceiptIdentity(applied);+ if (+ !githubReceipt ||+ (payload.operation === "add" && !githubReceipt.reactionId)+ )+ throw new Error("GitHub receipt identity was not confirmed");+ } else if (payload.operation === "remove") {+ await adapter.removeReaction(+ payload.threadId,+ payload.messageId,+ payload.reaction,+ );+ } else {+ await adapter.addReaction(+ payload.threadId,+ payload.messageId,+ payload.reaction,+ );+ }+ // The provider may already have accepted the idempotent reaction. Fence+ // the local success receipt so a reclaimed lease cannot report success+ // for an obsolete runtime.+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ await notifyChatActionWork(tx, "receipt_reaction");+ const processed = await tx+ .update(chatActions)+ .set({+ status: "processed",+ result: {+ attempts: attempt,+ ...(githubReceipt ? { githubReceipt } : {}),+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, action.id),+ eq(chatActions.status, "processing"),+ sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,+ ),+ )+ .returning({ id: chatActions.id });+ if (!processed.length) {+ throw new Error(+ "Receipt-reaction ownership changed before success settlement",+ );+ }+ if (action.deliveryId) {+ await tx+ .update(chatDeliveries)+ .set({ redactedError: null, updatedAt: new Date() })+ .where(+ and(+ eq(chatDeliveries.id, action.deliveryId),+ eq(chatDeliveries.state, "processed"),+ like(chatDeliveries.redactedError, "Receipt reaction %"),+ ),+ );+ }+ await credentialLease.assertOwned(tx);+ });+ } catch (error) {+ if (+ payload.operation === "add" &&+ reactionProvider === "slack" &&+ isSlackReceiptReactionAlreadyApplied(error)+ ) {+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ await notifyChatActionWork(tx, "receipt_reaction");+ const processed = await tx+ .update(chatActions)+ .set({+ status: "processed",+ result: {+ attempts: attempt,+ code: "receipt_reaction_already_applied",+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, action!.id),+ eq(chatActions.status, "processing"),+ sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,+ ),+ )+ .returning({ id: chatActions.id });+ if (!processed.length) {+ throw new Error(+ "Receipt-reaction ownership changed before idempotent settlement",+ );+ }+ if (action.deliveryId) {+ await tx+ .update(chatDeliveries)+ .set({ redactedError: null, updatedAt: new Date() })+ .where(+ and(+ eq(chatDeliveries.id, action.deliveryId),+ eq(chatDeliveries.state, "processed"),+ like(chatDeliveries.redactedError, "Receipt reaction %"),+ ),+ );+ }+ await credentialLease.assertOwned(tx);+ });+ return;+ }+ const disposition = classifyChatPublicationError(error, attempt);+ const retryable =+ disposition.kind === "retry" ||+ (disposition.kind === "delivery_unknown" && attempt < 3);+ const retryAfterMs =+ disposition.kind === "retry"+ ? disposition.retryAfterMs+ : 100 * 2 ** Math.max(0, attempt - 1);+ const operationLabel =+ payload.operation === "remove" ? " reaction removal" : " reaction";+ const diagnostic =+ `Receipt${operationLabel} ${retryable ? "deferred" : "failed"} after ${attempt} attempt${attempt === 1 ? "" : "s"} (${disposition.kind}): ${redactError(error)}`.slice(+ 0,+ MAX_ERROR_TEXT,+ );+ const retryAt = retryable+ ? new Date(Date.now() + retryAfterMs).toISOString()+ : null;+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ await notifyChatActionWork(tx, "receipt_reaction");+ const [failed] = await tx+ .update(chatActions)+ .set({+ status: "failed",+ result: {+ attempts: attempt,+ ...(githubReceipt ? { githubReceipt } : {}),+ code:+ payload.operation === "remove"+ ? `receipt_reaction_removal_${disposition.kind}`+ : `receipt_reaction_${disposition.kind}`,+ redactedError: diagnostic,+ retryable,+ retryAt,+ },+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatActions.id, action.id),+ eq(chatActions.status, "processing"),+ sql`(${chatActions.result}->>'attempts')::int = ${attempt}`,+ ),+ )+ .returning({ id: chatActions.id });+ if (failed && action.deliveryId) {+ await tx+ .update(chatDeliveries)+ .set({ redactedError: diagnostic, updatedAt: new Date() })+ .where(+ and(+ eq(chatDeliveries.id, action.deliveryId),+ eq(chatDeliveries.state, "processed"),+ ),+ );+ }+ await credentialLease.assertOwned(tx);+ });+ logger.warn(+ {+ endpointId: action.endpointId,+ deliveryId: action.deliveryId,+ attempts: attempt,+ disposition: disposition.kind,+ operation: payload.operation,+ retryAt,+ },+ "external chat receipt reaction deferred",+ );+ }+ }++ async function processPendingReceiptReactions(+ limit = 25,+ onlyActionId?: string,+ ) {+ const actions = await db.select({ id: chatActions.id }).from(chatActions)+ .where(and(dueChatAction("receipt_reaction"), onlyActionId ? eq(chatActions.id, onlyActionId) : undefined))+ .orderBy(asc(chatActions.createdAt)).limit(limit);+ for (const action of actions) await processReceiptReaction(action.id);+ return actions.length;+ }+ return { addReceiptReaction, processReceiptReaction, processPendingReceiptReactions };+}diff --git a/server/src/services/chat-channels/runtime-types.ts b/server/src/services/chat-channels/runtime-types.tsindex a764a0297e..cd2f6881e9 100644--- a/server/src/services/chat-channels/runtime-types.ts+++ b/server/src/services/chat-channels/runtime-types.ts@@ -1,5 +1,5 @@import type { Db, chatEndpoints } from "@paperclipai/db";-import type { ToolCredentialSecretRef } from "@paperclipai/shared";+import type { ToolCredentialSecretRef, ChatEndpointSetupState, ChatEndpointCallbackSurfaces } from "@paperclipai/shared";import type { ChatEndpointRuntime } from "../voice/voice-runtime.js";export type EndpointRow = typeof chatEndpoints.$inferSelect;@@ -36,3 +36,17 @@ export type EndpointRecord = {applicationId: string;credentialSecretRefs: ToolCredentialSecretRef[];};++export type SlackCallbackSurface = keyof ChatEndpointCallbackSurfaces;++export type SlackCallbackObservation = { url: string; observedAt: string };++export type InternalSetupState = ChatEndpointSetupState & {+ photonIntakeAfter?: string;+ runtimeGeneration?: number;+ /** Binds pre-install URL verification to the signing secret later configured. */+ slackVerificationSigningFingerprint?: string;+ slackCallbackSurfaces?: Partial<+ Record<SlackCallbackSurface, SlackCallbackObservation>+ >;+};diff --git a/server/src/services/chat-channels/setup-probes.ts b/server/src/services/chat-channels/setup-probes.tsnew file mode 100644index 0000000000..36d0f8f9f6--- /dev/null+++ b/server/src/services/chat-channels/setup-probes.ts@@ -0,0 +1,353 @@+import type { EndpointRow, DbOrTransaction } from "./runtime-types.js";++import { notifyChatEndpointWork } from "../chat-work-notifications.js";++import { chatCredentialMutationLease } from "../chat-credential-mutation-lease.js";++import { githubChatManagementService } from "../chat-github-management.js";++import {+ and,+ asc,+ desc,+ eq,+ gte,+ inArray,+ isNotNull,+ or,+ sql,+} from "drizzle-orm";++import type { Db } from "@paperclipai/db";++import {+ chatActions,+ chatConversations,+ chatDeliveries,+ chatEndpoints,+ chatIdentityLinks,+ chatMessageLinks,+ chatPublications,+ heartbeatRuns,+ issueComments,+ toolConnections,+} from "@paperclipai/db";+import type {+ ChatEndpoint,+ ChatEndpointSetupState,+} from "@paperclipai/shared";++import {+ conflict,+ forbidden,+ notFound,+} from "../../errors.js";++import {+ logActivity,+} from "../activity-log.js";++import {+ githubRunReplyState,+} from "../chat-run-publications.js";++import type { EndpointRecord } from "./runtime-types.js";++type SetupProbesOptions = {+ endpointRecord: (endpointId: string) => Promise<EndpointRecord | null>;+ withCredentialMutationLease: ReturnType<typeof chatCredentialMutationLease>;+ fetchImpl: typeof fetch;+ findAuthorizedIdentityLink: (endpoint: EndpointRow, userId: string) => Promise<{ id: string } | null>;+ runtimeGeneration: (setup: ChatEndpointSetupState) => number;+ lockCurrentPrincipalAuthorization: (tx: DbOrTransaction, endpoint: EndpointRow, principalId: string) => Promise<{ allowed: boolean }>;+ get: (endpointId: string) => Promise<ChatEndpoint>;+ setupTestActivationBarrier?: () => Promise<void>;+};++export function createSetupProbes(db: Db, options: SetupProbesOptions) {+ const { endpointRecord, withCredentialMutationLease, fetchImpl, findAuthorizedIdentityLink, runtimeGeneration, lockCurrentPrincipalAuthorization, get } = options;+++ async function setupTestStatus(endpointId: string, userId: string) {+ const record = await endpointRecord(endpointId);+ if (!record) throw notFound("Chat endpoint not found");+ const startedAt = record.endpoint.setup.testStartedAt;+ if (!startedAt) return { messageReceivedAt: null };+ const links = await db.select({ principalId: chatIdentityLinks.principalId }).from(chatIdentityLinks).where(and(+ eq(chatIdentityLinks.companyId, record.endpoint.companyId), eq(chatIdentityLinks.endpointId, endpointId),+ eq(chatIdentityLinks.paperclipUserId, userId), eq(chatIdentityLinks.status, "linked"),+ ));+ if (!links.length) return { messageReceivedAt: null };+ const principalIds = links.map((link) => link.principalId);+ const [delivery, command] = await Promise.all([+ db.select({ at: chatDeliveries.createdAt }).from(chatDeliveries).where(and(+ eq(chatDeliveries.companyId, record.endpoint.companyId), eq(chatDeliveries.endpointId, endpointId),+ inArray(chatDeliveries.principalId, principalIds), gte(chatDeliveries.createdAt, new Date(startedAt)),+ inArray(chatDeliveries.eventKind, ["message", "mention"]),+ )).orderBy(asc(chatDeliveries.createdAt)).limit(1).then((rows) => rows[0]),+ db.select({ at: chatActions.createdAt }).from(chatActions).where(and(+ eq(chatActions.companyId, record.endpoint.companyId), eq(chatActions.endpointId, endpointId),+ inArray(chatActions.principalId, principalIds), eq(chatActions.kind, "slash_task_start"), gte(chatActions.createdAt, new Date(startedAt)),+ )).orderBy(asc(chatActions.createdAt)).limit(1).then((rows) => rows[0]),+ ]);+ const at = [delivery?.at, command?.at].filter((value): value is Date => Boolean(value)).sort((a, b) => a.getTime() - b.getTime())[0];+ return { messageReceivedAt: at?.toISOString() ?? null };+ }++ async function test(endpointId: string, finishOptions?: { optionalSlackTestForUser: string }) {+ const initial = await endpointRecord(endpointId);+ if (!initial) throw notFound("Chat endpoint not found");+ return withCredentialMutationLease(+ initial.endpoint,+ async (credentialLease) => {+ // Reload only after owning the same lane as reconnect, pause, removal,+ // and credential rotation. Qualification and activation must describe+ // one exact provider runtime, never a setup snapshot that a concurrent+ // reconnect has already superseded.+ const record = await endpointRecord(endpointId);+ if (!record) throw notFound("Chat endpoint not found");+ const endpoint = record.endpoint;+ if (endpoint.status !== "verifying" || endpoint.setup.step !== "test") {+ throw conflict("This connection is not waiting for a setup test", {+ code: "chat_endpoint_not_testing",+ });+ }+ if (endpoint.provider === "github" && endpoint.setup.github) {+ const verified = await githubChatManagementService(db, fetchImpl).verification(endpoint.id);+ if (!verified.ready && !(finishOptions?.optionalSlackTestForUser && verified.connectionReady)) throw conflict("Finish verifying the App, repositories, and assigned agent's tools before activating this bot", { checks: verified.checks });+ }+ const testStartedAtValue = endpoint.setup.testStartedAt;+ const testStartedAt = testStartedAtValue+ ? new Date(testStartedAtValue)+ : null;+ const optionalSlackTest = Boolean(finishOptions?.optionalSlackTestForUser);+ if (optionalSlackTest) {+ if (!["slack", "github"].includes(endpoint.provider) || !endpoint.setup.webhookVerifiedAt || !endpoint.providerAccountId) {+ throw conflict("Verify the connection before finishing setup");+ }+ const linked = await findAuthorizedIdentityLink(endpoint, finishOptions!.optionalSlackTestForUser);+ if (!linked) throw forbidden("Connect your account before finishing setup");+ }+ if (!optionalSlackTest) {+ if (+ !endpoint.lastEventAt ||+ !testStartedAtValue ||+ !testStartedAt ||+ Number.isNaN(testStartedAt.getTime()) ||+ endpoint.lastEventAt < testStartedAt+ ) {+ throw conflict(+ "Send the test message in the provider before completing setup",+ {+ code: "chat_test_message_missing",+ },+ );+ }+ const requiredTrigger =+ ["telegram", "imessage-photon"].includes(endpoint.provider)+ ? "direct_message"+ : "subscribed_message";+ const qualifyingDelivery = await db+ .select({+ id: chatDeliveries.id,+ conversationId: chatDeliveries.conversationId,+ processedAt: chatDeliveries.processedAt,+ })+ .from(chatDeliveries)+ .where(+ and(+ eq(chatDeliveries.companyId, endpoint.companyId),+ eq(chatDeliveries.endpointId, endpoint.id),+ eq(chatDeliveries.state, "processed"),+ gte(chatDeliveries.processedAt, testStartedAt),+ sql`${chatDeliveries.normalizedEvent}->>'trigger' = ${requiredTrigger}`,+ ),+ )+ .orderBy(desc(chatDeliveries.processedAt))+ .limit(1)+ .then((rows) => rows[0] ?? null);+ if (+ !qualifyingDelivery?.conversationId ||+ !qualifyingDelivery.processedAt+ ) {+ throw conflict(+ ["telegram", "imessage-photon"].includes(endpoint.provider)+ ? "Send the test direct message before completing setup"+ : "Reply once without mentioning the agent before completing setup",+ { code: "chat_test_follow_up_missing" },+ );+ }+ const finalPublication = await db+ .select({+ commentId: chatPublications.commentId,+ payload: chatPublications.payload,+ })+ .from(chatPublications)+ .innerJoin(+ issueComments,+ and(+ eq(issueComments.id, chatPublications.commentId),+ eq(issueComments.companyId, chatPublications.companyId),+ eq(issueComments.issueId, chatPublications.issueId),+ eq(issueComments.authorType, "agent"),+ eq(issueComments.authorAgentId, endpoint.assignedAgentId),+ ),+ )+ .innerJoin(+ chatMessageLinks,+ and(+ eq(chatMessageLinks.companyId, chatPublications.companyId),+ eq(chatMessageLinks.endpointId, chatPublications.endpointId),+ eq(+ chatMessageLinks.conversationId,+ chatPublications.conversationId,+ ),+ eq(chatMessageLinks.deliveryId, qualifyingDelivery.id),+ eq(chatMessageLinks.direction, "inbound"),+ isNotNull(chatMessageLinks.commentId),+ ),+ )+ .innerJoin(+ heartbeatRuns,+ and(+ eq(heartbeatRuns.id, issueComments.createdByRunId),+ eq(heartbeatRuns.companyId, chatPublications.companyId),+ eq(heartbeatRuns.agentId, endpoint.assignedAgentId),+ eq(heartbeatRuns.status, "succeeded"),+ eq(+ sql<string>`${heartbeatRuns.contextSnapshot} ->> 'issueId'`,+ sql<string>`${chatPublications.issueId}::text`,+ ),+ or(+ sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`,+ sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'commentId'`,+ sql`coalesce(${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`,+ ),+ ),+ )+ .where(+ and(+ eq(chatPublications.companyId, endpoint.companyId),+ eq(chatPublications.endpointId, endpoint.id),+ eq(+ chatPublications.conversationId,+ qualifyingDelivery.conversationId,+ ),+ eq(chatPublications.state, "published"),+ gte(chatPublications.publishedAt, qualifyingDelivery.processedAt),+ ),+ )+ .orderBy(desc(chatPublications.publishedAt))+ .then((rows) =>+ rows.find(+ (row) =>+ row.payload.interactionId === undefined &&+ row.payload.progressState === undefined &&+ row.commentId !== null,+ ),+ );+ let githubToolReply = false;+ if (!finalPublication && endpoint.provider === "github") {+ const setupRuns = await db.select({ id: heartbeatRuns.id, issueId: chatConversations.issueId })+ .from(heartbeatRuns)+ .innerJoin(chatMessageLinks, and(+ eq(chatMessageLinks.companyId, endpoint.companyId),+ eq(chatMessageLinks.endpointId, endpoint.id),+ eq(chatMessageLinks.deliveryId, qualifyingDelivery.id),+ eq(chatMessageLinks.direction, "inbound"),+ or(+ sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'`,+ sql`coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`,+ ),+ ))+ .innerJoin(chatConversations, and(+ eq(chatConversations.id, qualifyingDelivery.conversationId),+ eq(chatConversations.id, chatMessageLinks.conversationId),+ eq(chatConversations.companyId, endpoint.companyId),+ sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${chatConversations.issueId}::text`,+ ))+ .where(and(eq(heartbeatRuns.companyId, endpoint.companyId),+ eq(heartbeatRuns.agentId, endpoint.assignedAgentId), eq(heartbeatRuns.status, "succeeded")))+ .orderBy(desc(heartbeatRuns.createdAt)).limit(20);+ for (const run of setupRuns) {+ if (await githubRunReplyState(db, { companyId: endpoint.companyId, endpointId: endpoint.id,+ issueId: run.issueId, runId: run.id }) === "confirmed") {+ githubToolReply = true;+ break;+ }+ }+ }+ if (!finalPublication && !githubToolReply) {+ throw conflict(+ "Wait for the Paperclip agent to reply to the setup turn before completing setup",+ {+ code: "chat_test_round_trip_incomplete",+ },+ );+ }+ }+ await options.setupTestActivationBarrier?.();+ const expectedGeneration = runtimeGeneration(endpoint.setup);+ await db.transaction(async (tx) => {+ await credentialLease.assertOwned(tx);+ if (optionalSlackTest) {+ const linked = await tx.select({ principalId: chatIdentityLinks.principalId }).from(chatIdentityLinks).where(and(+ eq(chatIdentityLinks.endpointId, endpoint.id), eq(chatIdentityLinks.paperclipUserId, finishOptions!.optionalSlackTestForUser), eq(chatIdentityLinks.status, "linked"),+ )).limit(1).then((rows) => rows[0]);+ if (!linked || !(await lockCurrentPrincipalAuthorization(tx, endpoint, linked.principalId)).allowed) throw forbidden("Your connected account is no longer authorized");+ }+ await notifyChatEndpointWork(tx);+ const [activated] = await tx+ .update(chatEndpoints)+ .set({+ status: "active",+ setup: {+ ...endpoint.setup,+ step: "complete",+ testStartedAt: null,+ testSkipped: optionalSlackTest,+ },+ healthMessage: optionalSlackTest ? "Connected; conversation test optional" : "Connected",+ activatedAt: endpoint.activatedAt ?? new Date(),+ updatedAt: new Date(),+ })+ .where(+ and(+ eq(chatEndpoints.id, endpointId),+ eq(chatEndpoints.status, "verifying"),+ sql`${chatEndpoints.setup}->>'step' = 'test'`,+ sql`coalesce((${chatEndpoints.setup}->>'runtimeGeneration')::integer, 0) = ${expectedGeneration}`,+ sql`${chatEndpoints.setup}->>'testStartedAt' = ${testStartedAtValue}`,+ ),+ )+ .returning({ id: chatEndpoints.id });+ if (!activated) {+ throw conflict("This setup test was superseded by a reconnect", {+ code: "chat_endpoint_test_superseded",+ });+ }+ await tx+ .update(toolConnections)+ .set({+ status: "active",+ enabled: true,+ healthStatus: "healthy",+ healthMessage: optionalSlackTest ? "Connected; conversation test optional" : "Connected",+ lastError: null,+ healthCheckedAt: new Date(),+ updatedAt: new Date(),+ })+ .where(eq(toolConnections.id, endpoint.connectionId));+ if (optionalSlackTest) await logActivity(tx as unknown as Db, {+ companyId: endpoint.companyId, actorType: "user", actorId: finishOptions!.optionalSlackTestForUser,+ action: "chat.setup_completed", entityType: "chat_endpoint", entityId: endpointId,+ details: { conversationTestOptional: true },+ });+ await credentialLease.assertOwned(tx);+ });+ return get(endpointId);+ },+ );+ }+ return { setupTestStatus, test };+}diff --git a/server/src/services/chat-channels/slack/callback-verification.ts b/server/src/services/chat-channels/slack/callback-verification.tsnew file mode 100644index 0000000000..ecddb2f665--- /dev/null+++ b/server/src/services/chat-channels/slack/callback-verification.ts@@ -0,0 +1,300 @@+import { isProvisionedSlackSetup } from "@paperclipai/shared";+import type { EndpointRow, DbOrTransaction, SlackCallbackSurface, InternalSetupState } from "../runtime-types.js";++import { notifyChatVerificationWork } from "../../chat-work-notifications.js";++import { slackChatRegistrationService } from "../../chat-slack-registration.js";+import { chatSlackRegistrations } from "@paperclipai/db";++import { runtimeCanonicalOrigin } from "../../cloud-runtime-identity.js";++import {+ createHash,+ createHmac,+ timingSafeEqual,+} from "node:crypto";+import {+ and,+ eq,+} from "drizzle-orm";++import type { Db } from "@paperclipai/db";++import {+ chatEndpoints,+ toolConnections,+} from "@paperclipai/db";+import type {+ ToolCredentialSecretRef,+} from "@paperclipai/shared";++import {+ logActivity,+} from "../../activity-log.js";++import { secretService } from "../../secrets.js";++function slackRequestSignatureIsValid(+ request: Request,+ body: string,+ signingSecret: string,+): boolean {+ const timestamp = request.headers.get("x-slack-request-timestamp");+ const signature = request.headers.get("x-slack-signature");+ if (!timestamp || !signature) return false;+ const timestampSeconds = Number(timestamp);+ if (+ !Number.isFinite(timestampSeconds) ||+ Math.abs(Math.floor(Date.now() / 1000) - timestampSeconds) > 300+ )+ return false;+ const expected = `v0=${createHmac("sha256", signingSecret).update(`v0:${timestamp}:${body}`).digest("hex")}`;+ try {+ return timingSafeEqual(Buffer.from(signature), Buffer.from(expected));+ } catch {+ return false;+ }+}++function slackRequestWorkspaceId(+ body: string,+ contentType: string,+): string | null {+ let payload: unknown;+ try {+ if (contentType.includes("application/json")) {+ payload = JSON.parse(body);+ } else {+ const form = new URLSearchParams(body);+ const interactivePayload = form.get("payload");+ payload = interactivePayload+ ? JSON.parse(interactivePayload)+ : Object.fromEntries(form.entries());+ }+ } catch {+ return null;+ }+ if (!payload || typeof payload !== "object") return null;+ const record = payload as Record<string, unknown>;+ const nestedId = (value: unknown): string | null => {+ if (!value || typeof value !== "object") return null;+ const id = (value as Record<string, unknown>).id;+ return typeof id === "string" && id.length > 0 ? id : null;+ };+ const stringField = (key: string): string | null => {+ const value = record[key];+ return typeof value === "string" && value.length > 0 ? value : null;+ };+ const authorization = Array.isArray(record.authorizations)+ ? record.authorizations.find(+ (value): value is Record<string, unknown> =>+ Boolean(value) && typeof value === "object",+ )+ : null;+ const authorizationField = (key: string): string | null => {+ const value = authorization?.[key];+ return typeof value === "string" && value.length > 0 ? value : null;+ };++ // A Grid event may carry both an enterprise id and the concrete workspace+ // id. The bot identity is verified against auth.test's team_id, so prefer a+ // team id and use the enterprise id only when Slack omitted team context.+ return (+ stringField("team_id") ??+ nestedId(record.team) ??+ authorizationField("team_id") ??+ stringField("enterprise_id") ??+ nestedId(record.enterprise) ??+ authorizationField("enterprise_id")+ );+}++function canonicalCallbackUrl(value: string): string | null {+ try {+ const url = new URL(value);+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;+ url.hostname = url.hostname.replace(/\.$/, "");+ url.username = "";+ url.password = "";+ url.search = "";+ url.hash = "";+ return url.toString();+ } catch {+ return null;+ }+}++// TLS terminates at a reverse proxy in many self-hosted deployments. The+// transport scheme is not evidence of URL drift; authority and path still are.+// This is diagnostic only: it does not trust forwarded headers or change auth.+function slackCallbackMatchesPublicUrl(observed: string, current: string): boolean {+ const canonical = canonicalCallbackUrl(observed);+ if (canonical === current) return true;+ if (!canonical) return false;+ const observedUrl = new URL(canonical);+ const currentUrl = new URL(current);+ return observedUrl.protocol === "http:"+ && currentUrl.protocol === "https:"+ && observedUrl.host === currentUrl.host+ && observedUrl.pathname === currentUrl.pathname;+}++async function inspectSlackCallback(+ request: Request,+): Promise<SlackCallbackInspection | null> {+ const url = slackCallbackObservationUrl(request);+ if (!url) return null;+ const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";+ let body: string;+ try {+ body = await request.text();+ } catch {+ return null;+ }+ if (contentType.includes("application/json")) {+ try {+ const payload = JSON.parse(body) as {+ type?: unknown;+ challenge?: unknown;+ };+ const isUrlVerification =+ payload.type === "url_verification" &&+ typeof payload.challenge === "string" &&+ payload.challenge.length > 0;+ if (isUrlVerification || payload.type === "event_callback") {+ return {+ surface: "events",+ url,+ isUrlVerification,+ };+ }+ } catch {+ return null;+ }+ return null;+ }++ const form = new URLSearchParams(body);+ if (form.get("command")) {+ return { surface: "slashCommands", url, isUrlVerification: false };+ }+ const interactivePayload = form.get("payload");+ if (!interactivePayload) return null;+ try {+ const payload = JSON.parse(interactivePayload) as { type?: unknown };+ if (+ typeof payload.type === "string" &&+ [+ "block_actions",+ "block_suggestion",+ "dialog_submission",+ "message_action",+ "shortcut",+ "view_closed",+ "view_submission",+ "workflow_step_edit",+ ].includes(payload.type)+ ) {+ return { surface: "interactivity", url, isUrlVerification: false };+ }+ } catch {+ return null;+ }+ return null;+}++type SlackCallbackInspection = {+ surface: SlackCallbackSurface;+ url: string;+ isUrlVerification: boolean;+};++// Cloud records the public request host in dedicated headers so provider edges+// cannot replace it with their upstream host. Only use callback-health evidence on a+// claimed Cloud instance, after provider authentication succeeded. It must not+// change the Request passed to the adapter, signature verification, routing,+// board identity, or the configured URL used to generate callbacks.+function slackCallbackObservationUrl(request: Request): string | null {+ const directUrl = canonicalCallbackUrl(request.url);+ if (!directUrl || !runtimeCanonicalOrigin()) return directUrl;+ const hasCloudEvidence = request.headers.has("x-paperclip-cloud-forwarded-host");+ const host = request.headers.get(hasCloudEvidence ? "x-paperclip-cloud-forwarded-host" : "x-forwarded-host")?.trim();+ const protocol = request.headers.get(hasCloudEvidence ? "x-paperclip-cloud-forwarded-proto" : "x-forwarded-proto")?.trim();+ if (!host || /[\s/@\\?#,]/.test(host) || (protocol !== "https" && protocol !== "http")) return directUrl;+ try {+ const origin = new URL(`${protocol}://${host}`);+ // Accept one authority only, never credentials, paths, queries, or lists.+ if (!origin.host || origin.username || origin.password || origin.pathname !== "/" || origin.search || origin.hash) return directUrl;+ const observed = new URL(directUrl);+ observed.protocol = origin.protocol;+ observed.host = origin.host;+ observed.port = origin.port;+ return canonicalCallbackUrl(observed.toString());+ } catch {+ return directUrl;+ }+}+export { slackRequestSignatureIsValid, slackRequestWorkspaceId, canonicalCallbackUrl, slackCallbackMatchesPublicUrl, inspectSlackCallback };++type SlackCallbackVerificationOptions = {+ resolveCredentialRefs: (endpoint: EndpointRow, refs: ToolCredentialSecretRef[], database?: DbOrTransaction) => Promise<Record<string, string>>;+ getWebhookPublicBaseUrl: () => string | null;+ scheduleMessageProcessing: (task: () => Promise<void>) => void;+ slackRegistration: Pick<ReturnType<typeof slackChatRegistrationService>, "notifyVerified">;+};++export function createSlackCallbackVerification(db: Db, options: SlackCallbackVerificationOptions) {+ const { resolveCredentialRefs, getWebhookPublicBaseUrl, scheduleMessageProcessing, slackRegistration } = options;+++ async function verifySlackRequestUrl(endpoint: EndpointRow, request: Request): Promise<Response | null> {+ const callback = await inspectSlackCallback(request.clone());+ if (!callback?.isUrlVerification) return null;+ const body = await request.clone().text();+ let notifyAccount = false;+ // URL verification needs only the signing secret. Do not initialize the+ // SDK (which calls Slack auth.test), wait for OAuth, or acquire the creation+ // lease: Slack can deliver this check while app setup still owns that lease.+ const response = await db.transaction(async tx => {+ const [current] = await tx.select().from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)).for("no key update");+ if (!current || ["archived", "paused", "revoked"].includes(current.status)) return new Response("ignored", { status: 200 });+ const [connection] = await tx.select({ status: toolConnections.status, refs: toolConnections.credentialSecretRefs }).from(toolConnections)+ .where(and(eq(toolConnections.id, current.connectionId), eq(toolConnections.companyId, current.companyId)));+ if (!connection || connection.status === "archived") return new Response("ignored", { status: 200 });+ let secret = (await resolveCredentialRefs(current, connection.refs.filter(ref => ref.configPath.replace(/^credentials\./, "") === "signingSecret"), tx)).signingSecret;+ if (!secret && isProvisionedSlackSetup(current.setup.slackSetupMethod)) {+ const [registration] = await tx.select().from(chatSlackRegistrations)+ .where(and(eq(chatSlackRegistrations.endpointId, current.id), eq(chatSlackRegistrations.companyId, current.companyId)));+ if (registration?.status !== "removed" && registration?.secretIds.signingSecret) {+ secret = await secretService(tx as unknown as Db).resolveSecretValue(current.companyId, registration.secretIds.signingSecret, "latest", {+ accessContext: { consumerType: "system", consumerId: `slack-registration:${current.id}`, configPath: "slack_registration.signingSecret", actorType: "system" },+ });+ }+ }+ if (!secret) return new Response("Slack signing secret is not ready yet", { status: 503 });+ if (!slackRequestSignatureIsValid(request, body, secret)) return new Response("Invalid signature", { status: 401 });+ const workspaceId = slackRequestWorkspaceId(body, request.headers.get("content-type") ?? "");+ if (workspaceId && current.providerAccountId && workspaceId !== current.providerAccountId) return new Response("ignored", { status: 200 });+ const observedAt = new Date();+ const setup = current.setup as InternalSetupState;+ const matchesCurrentUrl = slackCallbackMatchesPublicUrl(callback.url, `${getWebhookPublicBaseUrl()}/api/chat-webhooks/${current.publicId}/slack`);+ await notifyChatVerificationWork(tx);+ await tx.update(chatEndpoints).set({ setup: {+ ...setup,+ ...(matchesCurrentUrl ? { webhookVerifiedAt: setup.webhookVerifiedAt ?? observedAt.toISOString(),+ slackVerificationSigningFingerprint: createHash("sha256").update(secret).digest("hex") } : {}),+ slackCallbackSurfaces: { ...setup.slackCallbackSurfaces, events: { url: callback.url, observedAt: observedAt.toISOString() } },+ ...(matchesCurrentUrl && setup.slackAccount?.status === "linked" && !setup.slackAccount.verificationStatus+ ? { slackAccount: { ...setup.slackAccount, verificationStatus: "pending" as const } } : {}),+ } as InternalSetupState, ...(matchesCurrentUrl ? { healthMessage: "Slack Events Request URL verified" } : {}), updatedAt: observedAt }).where(eq(chatEndpoints.id, current.id));+ if (matchesCurrentUrl && !setup.webhookVerifiedAt) await logActivity(tx as unknown as Db, { companyId: current.companyId, actorType: "system", actorId: "slack-webhook",+ action: "chat_endpoint.webhook_verified", entityType: "tool_connection", entityId: current.connectionId,+ details: { endpointId: current.id, provider: "slack" } });+ notifyAccount = matchesCurrentUrl && setup.slackAccount?.status === "linked" && !setup.slackAccount.verificationStatus;+ return Response.json({ challenge: (JSON.parse(body) as { challenge: string }).challenge });+ });+ if (notifyAccount) scheduleMessageProcessing(() => slackRegistration.notifyVerified(endpoint.id));+ return response;+ }+ return { verifySlackRequestUrl };+}diff --git a/server/src/services/chat-channels/slack/messages.ts b/server/src/services/chat-channels/slack/messages.tsindex eba1e833f2..dece436082 100644--- a/server/src/services/chat-channels/slack/messages.ts+++ b/server/src/services/chat-channels/slack/messages.ts@@ -41,3 +41,49 @@ export function slackMessageSentAt(raw: unknown, messageId: string): Date | nullconst date = new Date(Number(ts) * 1_000);return Number.isFinite(date.getTime()) ? date : null;}++export function isSlackReceiptReactionAlreadyApplied(error: unknown): boolean {+ const pending: Array<{ depth: number; value: unknown }> = [+ { depth: 0, value: error },+ ];+ const seen = new Set<object>();+ while (pending.length > 0) {+ const current = pending.shift();+ if (+ !current ||+ current.depth > 4 ||+ !current.value ||+ typeof current.value !== "object" ||+ seen.has(current.value)+ ) {+ continue;+ }+ seen.add(current.value);+ const record = current.value as {+ cause?: unknown;+ code?: unknown;+ data?: { error?: unknown };+ original?: unknown;+ originalError?: unknown;+ };+ if (+ record.code === "already_reacted" ||+ record.data?.error === "already_reacted"+ ) {+ return true;+ }+ for (const value of [record.cause, record.original, record.originalError]) {+ pending.push({ depth: current.depth + 1, value });+ }+ }+ return false;+}++export function slackThreadChannelId(threadId: string): string | null {+ if (!threadId.startsWith("slack:")) return null;+ const channelAndThread = threadId.slice("slack:".length);+ const separator = channelAndThread.indexOf(":");+ const channelId =+ separator === -1 ? channelAndThread : channelAndThread.slice(0, separator);+ return channelId || null;+}diff --git a/server/src/services/chat-channels/slack/task-start.ts b/server/src/services/chat-channels/slack/task-start.tsindex 0ccb379361..309953a69f 100644--- a/server/src/services/chat-channels/slack/task-start.ts+++ b/server/src/services/chat-channels/slack/task-start.ts@@ -1073,3 +1073,21 @@ export function createSlackTaskStart(db: Db, options: SlackTaskStartOptions) {}return { latestSlackDmControlThreadId, finalizeSlackTaskStartFailure, admitConfirmedSlackTaskStart, processSlackTaskStart, processPendingSlackTaskStarts };}++export function slackTaskStartActivityStatus(action: {+ status: string;+ updatedAt: Date;+}): string {+ const age = Date.now() - action.updatedAt.getTime();+ if (action.status === "validating" && age >= SLACK_COMMAND_POST_STALE_MS) {+ return "queued";+ }+ if (+ (action.status === "received" && age >= SLACK_COMMAND_POST_STALE_MS) ||+ (action.status === "resolving" &&+ age >= SLACK_COMMAND_EXPLICIT_RETRY_STALE_MS)+ ) {+ return "delivery_unknown";+ }+ return action.status;+}diff --git a/server/src/services/chat-channels/telegram/callback-notices.ts b/server/src/services/chat-channels/telegram/callback-notices.tsnew file mode 100644index 0000000000..fe926e033b--- /dev/null+++ b/server/src/services/chat-channels/telegram/callback-notices.ts@@ -0,0 +1,128 @@+import type { EndpointRow, DbTransaction, DbOrTransaction } from "../runtime-types.js";++import {+ createHash,+} from "node:crypto";+import {+ and,+ eq,+} from "drizzle-orm";++import {+ chatEndpointResources,+ chatExternalPrincipals,+ chatIdentityLinks,+} from "@paperclipai/db";++import {+ type TelegramCallbackReceipt,+} from "../../chat-telegram-ephemeral.js";++type TelegramCallbackNoticeAuthorityOptions = {+ nonDirectDestinationAllowed: (endpoint: EndpointRow, resource: typeof chatEndpointResources.$inferSelect | null | undefined) => boolean;+ lockCurrentPrincipalAuthorization: (tx: DbOrTransaction, endpoint: EndpointRow, principalId: string) => Promise<{ allowed: boolean; linkedDenied: boolean; userId: string | null; sponsorUserId?: string | null }>;+};++export function createTelegramCallbackNoticeAuthority(options: TelegramCallbackNoticeAuthorityOptions) {+ const { nonDirectDestinationAllowed, lockCurrentPrincipalAuthorization } = options;+++ // This is permission to return one fixed, neutral callback denial, not+ // permission to execute the denied action or publish to the conversation.+ // Retain the initial identity-policy snapshot so queued notices cannot cross+ // a subsequent actor/link/reach change. No provider I/O occurs under locks.+ async function lockTelegramCallbackNoticeAuthority(+ tx: DbTransaction,+ endpoint: EndpointRow,+ receipt: TelegramCallbackReceipt,+ principalId: string | null,+ ): Promise<string | null> {+ if (+ endpoint.provider !== "telegram" ||+ endpoint.status !== "active" ||+ endpoint.companyId !== receipt.companyId ||+ endpoint.id !== receipt.endpointId ||+ endpoint.botExternalId !== receipt.botUserId ||+ !endpoint.providerAccountId ||+ !principalId ||+ Date.now() < receipt.receivedAtMs ||+ Date.now() >= receipt.deadlineAtMs+ )+ return null;+ const resource =+ receipt.chatType === "private"+ ? null+ : await tx+ .select()+ .from(chatEndpointResources)+ .where(+ and(+ eq(chatEndpointResources.companyId, endpoint.companyId),+ eq(chatEndpointResources.endpointId, endpoint.id),+ eq(chatEndpointResources.providerResourceId, receipt.chatId),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ if (+ receipt.chatType === "private"+ ? !endpoint.allowDirectMessages+ : !resource || !nonDirectDestinationAllowed(endpoint, resource)+ )+ return null;+ const principal = await tx+ .select()+ .from(chatExternalPrincipals)+ .where(+ and(+ eq(chatExternalPrincipals.companyId, endpoint.companyId),+ eq(chatExternalPrincipals.provider, endpoint.provider),+ eq(+ chatExternalPrincipals.providerAccountId,+ endpoint.providerAccountId,+ ),+ eq(chatExternalPrincipals.id, principalId),+ eq(chatExternalPrincipals.externalId, receipt.receiverUserId),+ ),+ )+ .for("update")+ .then((rows) => rows[0] ?? null);+ if (!principal || principal.kind !== "user" || principal.isBot) return null;+ const authorization = await lockCurrentPrincipalAuthorization(+ tx,+ endpoint,+ principal.id,+ );+ const link = await tx+ .select({+ status: chatIdentityLinks.status,+ userId: chatIdentityLinks.paperclipUserId,+ })+ .from(chatIdentityLinks)+ .where(+ and(+ eq(chatIdentityLinks.companyId, endpoint.companyId),+ eq(chatIdentityLinks.endpointId, endpoint.id),+ eq(chatIdentityLinks.principalId, principal.id),+ ),+ )+ .then((rows) => rows[0] ?? null);+ return createHash("sha256")+ .update(+ JSON.stringify([+ endpoint.companyId,+ endpoint.id,+ receipt.botUserId,+ resource?.id ?? null,+ principal.id,+ principal.externalId,+ link,+ authorization,+ endpoint.allowUnlinkedPeople,+ endpoint.sponsorUserId,+ ]),+ )+ .digest("hex");+ }+ return { lockTelegramCallbackNoticeAuthority };+}diff --git a/server/src/services/chat-channels/telegram/messages.ts b/server/src/services/chat-channels/telegram/messages.tsindex 152b647853..ac75997b14 100644--- a/server/src/services/chat-channels/telegram/messages.ts+++ b/server/src/services/chat-channels/telegram/messages.ts@@ -1,3 +1,4 @@+import type { Attachment } from "chat";import { createHash } from "node:crypto";import type { chatDeliveries } from "@paperclipai/db";import type { ChatProvider } from "@paperclipai/shared";@@ -221,3 +222,14 @@ export function telegramMessageSentAt(raw: unknown): Date | null {const sentAt = new Date(value * 1_000);return Number.isFinite(sentAt.getTime()) ? sentAt : null;}++export function telegramMarkdownAttachment(text: string): Attachment {+ const data = Buffer.from(text, "utf8");+ return {+ data,+ mimeType: "text/markdown; charset=utf-8",+ name: "paperclip-response.md",+ size: data.byteLength,+ type: "file",+ };+ }