feat: add opt-in chat provider and data foundation (#13100)

Add dormant provider contracts, qualified patched adapters, tenant-scoped persistence and lifecycle ownership without activating chat routes. Preserve the experimental integration as dependent PR #13038.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-09 13:49:12 -05:00
1 parent 7d84b183fb
commit 6abeb67334
143 files changed
+789391 -162

No files matched your search

+3
View File
@@ -341,6 +341,8 @@ export {
SELF_SERVE_MCP_RESEARCH,
} from "./self-serve-mcp-research.js";
export * from "./validators/status-card.js";
export * from "./types/chat-channels.js";
export * from "./validators/chat-channels.js";
export { appDefinitionSchema, appDefinitionsSchema, connectionMethodDefSchema } from "./validators/app-definition.js";
export {
humanizeConnectionDisplayName,
@@ -1441,6 +1443,7 @@ export type {
ToolConnectionCredentialSource,
ToolConnectionCredentialPolicy,
ToolConnectionOwnership,
ToolConnectionPurpose,
ToolConnectionTransport,
ToolConnectionStatus,
ToolConnectionKind,
+498
View File
@@ -0,0 +1,498 @@
/** Provider-neutral contracts for Paperclip's native external chat subsystem. */
export const CHAT_PROVIDERS = [
"slack",
"github",
"discord",
"microsoft-teams",
"telegram",
] as const;
export type ChatProvider = (typeof CHAT_PROVIDERS)[number];
export const CHAT_ENDPOINT_STATUSES = [
"draft",
"verifying",
"active",
"paused",
"attention",
"revoked",
"archived",
] as const;
export type ChatEndpointStatus = (typeof CHAT_ENDPOINT_STATUSES)[number];
export const CHAT_DEPLOYMENT_MODES = ["direct", "relay"] as const;
export type ChatDeploymentMode = (typeof CHAT_DEPLOYMENT_MODES)[number];
export const CHAT_CONCURRENCY_POLICIES = [
"burst",
"queue",
"debounce",
"drop",
"concurrent",
] as const;
export type ChatConcurrencyPolicy = (typeof CHAT_CONCURRENCY_POLICIES)[number];
export const CHAT_EVENT_KINDS = [
"mention",
"message",
"direct_message",
"message_updated",
"message_deleted",
"message_restored",
"reaction_added",
"reaction_removed",
"action",
"modal_submitted",
"modal_closed",
"slash_command",
"file_shared",
"installation",
"uninstallation",
"unknown",
] as const;
export type ChatEventKind = (typeof CHAT_EVENT_KINDS)[number];
export const CHAT_DELIVERY_STATES = [
"received",
"filtered",
"processing",
"processed",
"retry",
"failed",
] as const;
export type ChatDeliveryState = (typeof CHAT_DELIVERY_STATES)[number];
export const CHAT_PUBLICATION_STATES = [
"pending",
"awaiting_consent",
"streaming",
"published",
"retry",
"delivery_unknown",
"failed",
"cancelled",
] as const;
export type ChatPublicationState = (typeof CHAT_PUBLICATION_STATES)[number];
export const CHAT_FILE_TRANSFER_PHASES = [
"consent_pending",
"consent_sending",
"consent_unknown",
"awaiting_consent",
"upload_pending",
"uploading",
"upload_unknown",
"file_info_pending",
"file_info_sending",
"file_info_unknown",
"delivered",
"declined",
"expired",
"cancelled",
"conflict",
] as const;
export type ChatFileTransferPhase = (typeof CHAT_FILE_TRANSFER_PHASES)[number];
/** Closed presentation only: never provider URLs, credentials or private state. */
export interface ChatFileTransferSummary {
provider: "microsoft-teams";
phase: ChatFileTransferPhase;
filename: string;
expiresAt?: string | null;
/** Monotonic durable row revision, not a schema version. */
version: number;
}
export type ChatFileTransferResolutionPrecondition = Pick<
ChatFileTransferSummary,
"phase" | "version"
>;
export const CHAT_CONVERSATION_STATES = [
"active",
"waiting",
"completed",
"unavailable",
"endpoint_removed",
] as const;
export type ChatConversationState = (typeof CHAT_CONVERSATION_STATES)[number];
export const CHAT_PRINCIPAL_KINDS = ["user", "bot", "app", "system"] as const;
export type ChatPrincipalKind = (typeof CHAT_PRINCIPAL_KINDS)[number];
export const CHAT_IDENTITY_LINK_STATUSES = [
"pending",
"linked",
"revoked",
"expired",
] as const;
export type ChatIdentityLinkStatus =
(typeof CHAT_IDENTITY_LINK_STATUSES)[number];
export const CHAT_RESOURCE_AVAILABILITIES = [
"available",
"unavailable",
"removed",
] as const;
export type ChatResourceAvailability =
(typeof CHAT_RESOURCE_AVAILABILITIES)[number];
export interface ChatAdapterCapabilities {
threads: boolean;
directMessages: boolean;
nativeStreaming: boolean;
messageEdits: boolean;
messageDeletes: boolean;
reactions: boolean;
files: boolean;
cards: boolean;
actions: boolean;
modals: boolean;
slashCommands: boolean;
ephemeralMessages: boolean;
proactiveDirectMessages: boolean;
}
export interface ChatEndpointBehaviorPolicy {
/** Defaults to queue and is not exposed in the initial settings UI. */
concurrency: ChatConcurrencyPolicy;
allowDirectMessages: boolean;
allowGroupChats: boolean;
allowUnlinkedPeople: boolean;
}
export const CHAT_CALLBACK_SURFACE_STATUSES = [
"current",
"stale",
"unverified",
] as const;
export type ChatCallbackSurfaceStatus =
(typeof CHAT_CALLBACK_SURFACE_STATUSES)[number];
export interface ChatEndpointCallbackSurfaceState {
status: ChatCallbackSurfaceStatus;
observedAt?: string | null;
}
export interface ChatEndpointCallbackSurfaces {
events: ChatEndpointCallbackSurfaceState;
interactivity: ChatEndpointCallbackSurfaceState;
slashCommands: ChatEndpointCallbackSurfaceState;
}
export interface ChatEndpointSetupState {
step: "choose_agent" | "provider_setup" | "test" | "complete";
/** Server-generated boundary; only provider events at or after this time can complete setup. */
testStartedAt?: string | null;
/** Set only after the provider has delivered a signed callback challenge. */
webhookVerifiedAt?: string | null;
authorizationUrl?: string | null;
providerUrl?: string | null;
command?: string | null;
webhookUrl?: string | null;
messagingEndpoint?: string | null;
/** Safe presence signal only; the secret value is returned once by its generation endpoint. */
webhookSecretConfigured?: boolean;
/** Provider callback surfaces observed at the endpoint's current public URL. */
callbackSurfaces?: ChatEndpointCallbackSurfaces;
/** True when at least one previously observed callback still targets an old public URL. */
callbacksNeedUpdate?: boolean;
}
export interface ChatEndpointSetupSecret {
webhookSecret: string;
}
export interface ChatEndpoint {
id: string;
companyId: string;
connectionId: string;
provider: ChatProvider;
publicId: string;
status: ChatEndpointStatus;
deploymentMode: ChatDeploymentMode;
assignedAgentId: string;
assignedAgentName?: string | null;
sponsorUserId?: string | null;
providerAccountId?: string | null;
providerAccountLabel?: string | null;
botExternalId?: string | null;
botUsername?: string | null;
botLabel?: string | null;
botAvatarUrl?: string | null;
allowDirectMessages: boolean;
allowGroupChats: boolean;
allowUnlinkedPeople: boolean;
replyMode: "subscribed";
capabilities: ChatAdapterCapabilities;
setup: ChatEndpointSetupState;
healthMessage?: string | null;
lastError?: string | null;
lastActivityAt?: string | null;
lastPublicationAt?: string | null;
activatedAt?: string | null;
createdAt: string;
updatedAt: string;
}
export interface ChatEndpointResource {
id: string;
companyId: string;
endpointId: string;
type: string;
providerResourceId: string;
parentProviderResourceId?: string | null;
label: string;
detail?: string | null;
providerUrl?: string | null;
availability: ChatResourceAvailability;
enabled: boolean;
createdAt: string;
updatedAt: string;
}
export interface ChatExternalPrincipal {
id: string;
companyId: string;
provider: ChatProvider;
providerAccountId: string;
externalId: string;
kind: ChatPrincipalKind;
displayName?: string | null;
handle?: string | null;
avatarUrl?: string | null;
isBot: boolean;
lastSeenAt?: string | null;
}
export interface ChatIdentityLink {
id: string;
companyId: string;
endpointId: string;
principalId: string;
externalLabel: string;
externalDetail?: string | null;
paperclipUserId?: string | null;
paperclipUserLabel?: string | null;
status: ChatIdentityLinkStatus;
expiresAt?: string | null;
confirmedAt?: string | null;
revokedAt?: string | null;
}
export interface ChatConversation {
id: string;
companyId: string;
endpointId: string;
resourceId?: string | null;
issueId: string;
issueIdentifier?: string | null;
issueTitle?: string | null;
externalConversationId: string;
externalThreadId: string;
sessionGeneration: number;
externalLabel: string;
externalUrl?: string | null;
isDirectMessage: boolean;
state: ChatConversationState;
lastPublicationStatus?: ChatPublicationState | null;
lastActivityAt?: string | null;
createdAt: string;
updatedAt: string;
}
export interface ChatDelivery {
id: string;
companyId: string;
endpointId: string;
conversationId?: string | null;
principalId?: string | null;
providerEventId: string;
deduplicationKey: string;
eventKind: ChatEventKind;
state: ChatDeliveryState;
attempts: number;
summary?: string | null;
redactedError?: string | null;
receivedAt: string;
processedAt?: string | null;
createdAt: string;
updatedAt: string;
}
export type SafeExternalChatCardKind = "status" | "question" | "confirmation";
export type SafeExternalChatCardAction =
| {
type: "callback";
actionId: string;
label: string;
style?: "default" | "primary" | "danger";
}
| {
type: "link";
label: string;
url: string;
};
export interface SafeExternalChatCard {
schema: "paperclip.chat.card.v1";
kind: SafeExternalChatCardKind;
title: string;
body?: string;
actions?: SafeExternalChatCardAction[];
}
export interface SafeChatPublicationPayload {
text: string;
attachmentIds?: string[];
interactionId?: string;
card?: SafeExternalChatCard;
/** Server-managed metadata for a logical publication split into durable messages. */
transportPart?: {
batchId: string;
count: number;
index: number;
/** Server-managed provider rendering for this transport part. */
mode?:
"inline" | "discord_markdown_attachment" | "telegram_markdown_attachment";
orderKey: string;
/** Closed, server-generated Markdown fence wrappers; text remains an exact source slice. */
prefix?: string;
suffix?: string;
};
progressState?:
| "queued"
| "working"
| "waiting_for_input"
| "approval_needed"
| "completed"
| "failed";
}
export interface ChatPublication {
id: string;
companyId: string;
endpointId: string;
conversationId: string;
issueId: string;
commentId?: string | null;
idempotencyKey: string;
state: ChatPublicationState;
providerMessageId?: string | null;
providerUrl?: string | null;
attempts: number;
redactedError?: string | null;
createdAt: string;
updatedAt: string;
publishedAt?: string | null;
}
export interface ChatPublicationSummary {
id: string;
state: ChatPublicationState;
providerUrl?: string | null;
attempts: number;
redactedError?: string | null;
nextAttemptAt?: string | null;
publishedAt?: string | null;
fileTransfer?: ChatFileTransferSummary;
}
export interface ChatPublicationBatchStatus {
/** First unresolved part; a terminal nonpublished part for mixed outcomes. */
publication: ChatPublicationSummary;
total: number;
published: number;
/** Additive during rolling upgrades; missing settlement proof is not permission to dismiss. */
parts?: ChatPublicationSummary[];
awaitingConsent?: number;
declined?: number;
expired?: number;
/** Excludes declined and expired. */
cancelled?: number;
/** published + declined + expired + cancelled, never failed or uncertain. */
settled?: number;
canDismiss?: boolean;
}
export interface ChatActivityItem {
id: string;
kind: "delivery" | "publication" | "action" | "health" | "repair";
actionType?:
| "slash_task_start"
| "provider_effect"
| "github_webhook_ingress"
| "slack_session_sync"
| "slack_session_stop";
status: string;
summary: string;
detail?: string | null;
createdAt: string;
replayable?: boolean;
resolutionActions?: Array<"mark_delivered" | "retry_anyway" | "cancel">;
fileTransfer?: ChatFileTransferSummary;
}
export interface ExternalChannelBindingSummary {
endpointId: string;
provider: ChatProvider;
botLabel?: string | null;
externalLabel: string;
externalUrl?: string | null;
conversationId: string;
publicationState?: ChatPublicationState | null;
assignedAgentLocked: true;
}
export interface CreateChatEndpointInput {
provider: ChatProvider;
assignedAgentId: string;
applicationId?: string;
name?: string;
}
export interface UpdateChatEndpointInput {
allowDirectMessages?: boolean;
allowGroupChats?: boolean;
allowUnlinkedPeople?: boolean;
}
export interface ConfigureChatEndpointInput {
action: "configure" | "verify" | "pause" | "resume" | "reconnect" | "remove";
credentials?: Record<string, string>;
}
export interface NormalizedChatEvent {
providerEventId: string;
kind: ChatEventKind;
providerAccountId: string;
principal: {
externalId: string;
kind: ChatPrincipalKind;
displayName?: string;
handle?: string;
isBot?: boolean;
};
resource: {
type: string;
providerResourceId: string;
parentProviderResourceId?: string;
label: string;
providerUrl?: string;
};
conversation: {
externalConversationId: string;
externalThreadId?: string;
label: string;
providerUrl?: string;
isDirectMessage?: boolean;
};
message?: {
providerMessageId: string;
text: string;
mentionedBot?: boolean;
replyToProviderMessageId?: string;
attachmentUrls?: string[];
};
raw: Record<string, unknown>;
}
+1
View File
@@ -507,6 +507,7 @@ export type {
ToolConnectionCredentialSource,
ToolConnectionCredentialPolicy,
ToolConnectionOwnership,
ToolConnectionPurpose,
ToolConnectionTransport,
ToolConnectionStatus,
ToolConnectionKind,
+1
View File
@@ -68,6 +68,7 @@ export type {
export type ToolActorType = "agent" | "user" | "system" | "plugin";
export type ToolConnectionTransport = "mcp_remote" | "rest_api" | "local_stdio";
export type ToolConnectionPurpose = "tool" | "channel";
export type ToolConnectionAuthKind = "oauth" | "api_key" | "none";
export type ToolConnectionOwnership = "platform_shared" | "platform_provisioned" | "customer" | "dcr";
export type ToolConnectionCredentialSource = "paperclip_vault" | "vercel_connect";
@@ -0,0 +1,113 @@
import { describe, expect, it } from "vitest";
import {
configureChatEndpointSchema,
microsoftTeamsCredentialIdSchema,
resolveChatActionSchema,
resolveChatPublicationSchema,
chatPublicationStateSchema,
} from "./chat-channels.js";
describe("Microsoft Teams chat credential validation", () => {
it("normalizes canonical Entra application and tenant UUIDs", () => {
const parsed = configureChatEndpointSchema.parse({
action: "configure",
credentials: {
clientId: " 76D0CB17-5EC4-4B3D-983B-DA8A01DC02C4 ",
tenantId: "F8CDEF31-A31E-4B4A-93E4-5F571E91255A",
clientSecret: "keep-case-sensitive-secret",
},
});
expect(parsed.credentials).toEqual({
clientId: "76d0cb17-5ec4-4b3d-983b-da8a01dc02c4",
tenantId: "f8cdef31-a31e-4b4a-93e4-5f571e91255a",
clientSecret: "keep-case-sensitive-secret",
});
});
it.each([
"common",
"organizations",
"contoso.onmicrosoft.com",
"76d0cb175ec44b3d983bda8a01dc02c4",
"00000000-0000-0000-0000-000000000000",
])("rejects non-canonical Teams credential id %s", (value) => {
expect(microsoftTeamsCredentialIdSchema.safeParse(value).success).toBe(
false,
);
expect(
configureChatEndpointSchema.safeParse({
action: "configure",
credentials: {
clientId: "76d0cb17-5ec4-4b3d-983b-da8a01dc02c4",
tenantId: value,
clientSecret: "secret",
},
}).success,
).toBe(false);
});
it("does not impose Teams UUID rules on unrelated provider credentials", () => {
expect(
configureChatEndpointSchema.parse({
action: "configure",
credentials: {
botToken: "xoxb-test",
signingSecret: "secret",
},
}),
).toEqual({
action: "configure",
credentials: {
botToken: "xoxb-test",
signingSecret: "secret",
},
});
});
});
describe("chat provider-action resolution validation", () => {
it("accepts consent waiting and a closed versioned file-stage precondition", () => {
expect(chatPublicationStateSchema.parse("awaiting_consent")).toBe(
"awaiting_consent",
);
const request = {
action: "cancel",
fileTransfer: { phase: "upload_unknown", version: 3 },
};
expect(resolveChatPublicationSchema.parse(request)).toEqual(request);
expect(resolveChatPublicationSchema.parse({ action: "cancel" })).toEqual({
action: "cancel",
});
});
it.each([
{ phase: "upload_unknown", version: 0 },
{ phase: "upload_unknown", version: 1.5 },
{ phase: "upload_unknown", version: Number.MAX_SAFE_INTEGER + 1 },
{ phase: "new_unreviewed_phase", version: 1 },
{ phase: "upload_unknown" },
{ phase: "upload_unknown", version: 1, uploadUrl: "private" },
])(
"rejects malformed file-stage resolution preconditions %#",
(fileTransfer) => {
expect(
resolveChatPublicationSchema.safeParse({
action: "cancel",
fileTransfer,
}).success,
).toBe(false);
},
);
it.each(["mark_delivered", "retry_anyway", "cancel"] as const)(
"accepts the explicit %s resolution",
(action) => {
expect(resolveChatActionSchema.parse({ action })).toEqual({ action });
},
);
it("rejects automatic or unknown provider-effect replay modes", () => {
expect(resolveChatActionSchema.safeParse({ action: "retry" }).success).toBe(
false,
);
});
});
@@ -0,0 +1,193 @@
import { z } from "zod";
import { multilineTextSchema } from "./text.js";
import {
CHAT_CONCURRENCY_POLICIES,
CHAT_DELIVERY_STATES,
CHAT_ENDPOINT_STATUSES,
CHAT_EVENT_KINDS,
CHAT_FILE_TRANSFER_PHASES,
CHAT_IDENTITY_LINK_STATUSES,
CHAT_PRINCIPAL_KINDS,
CHAT_PROVIDERS,
CHAT_PUBLICATION_STATES,
CHAT_RESOURCE_AVAILABILITIES,
} from "../types/chat-channels.js";
export const chatProviderSchema = z.enum(CHAT_PROVIDERS);
export const chatEndpointStatusSchema = z.enum(CHAT_ENDPOINT_STATUSES);
export const chatConcurrencyPolicySchema = z.enum(CHAT_CONCURRENCY_POLICIES);
export const chatEventKindSchema = z.enum(CHAT_EVENT_KINDS);
export const chatDeliveryStateSchema = z.enum(CHAT_DELIVERY_STATES);
export const chatPublicationStateSchema = z.enum(CHAT_PUBLICATION_STATES);
export const chatPrincipalKindSchema = z.enum(CHAT_PRINCIPAL_KINDS);
export const chatIdentityLinkStatusSchema = z.enum(CHAT_IDENTITY_LINK_STATUSES);
export const chatResourceAvailabilitySchema = z.enum(
CHAT_RESOURCE_AVAILABILITIES,
);
/**
* Microsoft emits Entra application and tenant identifiers in canonical UUID
* form in Bot Framework activities. Tenant aliases such as `common` or an
* `onmicrosoft.com` domain can be accepted by the token endpoint, but cannot
* be compared safely with the activity tenant id used by Paperclip's runtime
* fence. Normalize the UUIDs at the API boundary instead.
*/
export const microsoftTeamsCredentialIdSchema = z
.string()
.trim()
.uuid()
.refine((value) => value !== "00000000-0000-0000-0000-000000000000", {
message: "Microsoft Teams credential IDs cannot be the nil UUID",
})
.transform((value) => value.toLowerCase());
const chatEndpointCredentialsSchema = z
.record(z.string(), z.string().min(1))
.superRefine((credentials, ctx) => {
for (const key of ["clientId", "tenantId"] as const) {
const value = credentials[key];
if (value === undefined) continue;
const parsed = microsoftTeamsCredentialIdSchema.safeParse(value);
if (parsed.success) continue;
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: [key],
message: `${key} must be a canonical Microsoft Entra UUID`,
});
}
})
.transform((credentials) => {
const normalized = { ...credentials };
for (const key of ["clientId", "tenantId"] as const) {
const value = normalized[key];
if (value !== undefined) {
normalized[key] = microsoftTeamsCredentialIdSchema.parse(value);
}
}
return normalized;
});
export const createChatEndpointSchema = z
.object({
provider: chatProviderSchema,
assignedAgentId: z.string().uuid(),
applicationId: z.string().uuid().optional(),
name: z.string().trim().min(1).max(160).optional(),
})
.strict();
export const updateChatEndpointSchema = z
.object({
allowDirectMessages: z.boolean().optional(),
allowGroupChats: z.boolean().optional(),
allowUnlinkedPeople: z.boolean().optional(),
})
.strict()
.refine((value) => Object.keys(value).length > 0, {
message: "At least one chat endpoint field is required",
});
export const configureChatEndpointSchema = z
.object({
action: z.enum([
"configure",
"verify",
"pause",
"resume",
"reconnect",
"remove",
]),
credentials: chatEndpointCredentialsSchema.optional(),
})
.strict()
.superRefine((value, ctx) => {
if (
value.credentials &&
value.action !== "configure" &&
value.action !== "reconnect"
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["credentials"],
message: `Credentials are not accepted for the ${value.action} action`,
});
}
});
export const replaceChatEndpointResourcesSchema = z
.object({
resources: z
.array(
z
.object({
id: z.string().uuid(),
enabled: z.boolean(),
})
.strict(),
)
.max(500),
})
.strict();
export const publishChatCommentSchema = z
.object({
commentId: z.string().uuid(),
})
.strict();
export const publishChatBoardMessageSchema = z
.object({
body: multilineTextSchema.pipe(z.string().trim().min(1).max(100_000)),
idempotencyKey: z.string().trim().min(16).max(200),
attachmentIds: z
.array(z.string().uuid())
.max(20)
.refine((ids) => new Set(ids).size === ids.length, {
message: "Attachment ids must be unique",
})
.optional(),
})
.strict();
export const publishChatPublicationSchema = z.union([
publishChatCommentSchema,
publishChatBoardMessageSchema,
]);
export const resolveChatPublicationSchema = z
.object({
action: z.enum(["mark_delivered", "retry_anyway", "cancel"]),
fileTransfer: z
.object({
phase: z.enum(CHAT_FILE_TRANSFER_PHASES),
version: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
})
.strict()
.optional(),
})
.strict();
export const resolveChatActionSchema = z
.object({
action: z.enum(["mark_delivered", "retry_anyway", "cancel"]),
})
.strict();
export const createChatIdentityLinkIntentSchema = z
.object({
expiresInSeconds: z.number().int().min(300).max(86_400).default(1_800),
})
.strict()
.default({ expiresInSeconds: 1_800 });
export const confirmChatIdentityLinkSchema = z
.object({
token: z.string().min(32).max(4096),
})
.strict();
export const replayChatDeliverySchema = z.object({}).strict();
export const chatPublicEndpointIdSchema = z
.string()
.regex(/^[a-zA-Z0-9_-]{32,128}$/);