mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-29 21:07:40 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Questions and review decisions must work in the conversation where a task started. > - Slack omitted question context and did not publish several review kinds. > - Some answers saved in Paperclip also lost their authorized continuation or their final Slack reply. > - A settled card and a successful run did not prove that the user received the result. > - This pull request preserves complete questions and follows the existing answer and delivery receipts through continuation. > - Users can read the request, submit an authorized decision, and receive the resumed task's result in the same conversation. ## Linked Issues or Issue Description Refs #17045 and #17218. **What happened?** Slack question cards could omit instructions and editable starting text. Checkbox reviews, item verdicts, task suggestions, and connection requests had no publication path. Complex question answers submitted in Paperclip could fail continuation authorization. Several review continuations completed without delivering their result to Slack. **Expected behavior** Show the actual question and context. Use native Slack controls when they preserve the form contract. Otherwise provide an explicit Paperclip review link. Persist one authorized response, resume through the existing delivery path, settle the card, and deliver the useful result to its originating conversation. **Steps to reproduce** 1. Start a task in Slack and ask a text or choice question with instructions and help text. 2. Submit native text and choice responses, then submit a complex form through Paperclip. 3. Accept a checklist, submit item decisions, select suggested tasks, or decline a connection request. 4. Inspect the saved answer, continuation run, original Slack card, and final Slack reply independently. ## What Changed - Preserve full prompts, context, descriptions, recommendations, help, and editable starting text. Use direct buttons for short choices, inline searchable selects for longer lists, and native checkboxes with explicit submission for multiple choices. - Add native custom-answer and validated-text modals, ordinary confirmation buttons, checklist decisions, per-item verdicts with reasons, suggested-task creation/dismissal, and connection decline. Keep governed approvals, permission grants, and forms that cannot be represented faithfully in the full Paperclip review surface. - Keep Slack-specific canonical-validation feedback in its owning platform module. Shared callbacks delegate without interpreting provider presentation. - Reuse the existing canonical interaction transactions, callback receipts, publication queue, and continuation delivery. Share ordinary confirmation handling across Telegram and Slack. Recheck current authorization and commit response receipts atomically. - Settle cards with the saved answer and remove stale controls. Ignore passive Slack link callbacks so opening a task does not display a false answer error. - Validate exact multi-select receipt mappings during native continuation. Recover automation-origin connection replies from their published prompt after validating the durable connection receipt. - Keep oversized multi-select handoffs free of unused native tokens, and retain the complete Paperclip form for 101–128 choices plus Other. Make the original-conversation audience explicit before submitting a Slack modal. - Add rollback, provider serialization, callback, continuation, and negative authorization regressions. Update the connector playbook and feature/access maps. No React or application UI changes are included. - Add a durable Q01–Q11 qualification index and provider coverage matrix. Require distinct functional, good-experience, and best-available-control assessments; real unanswered/answering/settled evidence; saved results, continuation and navigation proof; and retained failures. Mark other providers unaudited rather than assuming Slack parity. ## Verification Candidate: `e0017d446b1016a38d65382366cd1408cce33039`. The eleven-core-format live Slack gallery is pinned to `c3d458b2a06b660448940fd8cf33c5906f0058d5`; subsequent boundary fixes and the sharing notice have automated verification, not new live screenshots. - Real Slack UI testing covered all 11 formats: text, closed choice, long single select, multiple choices, choices with a custom answer, pattern-validated text, confirmation, checklist, item verdicts, suggested tasks, and connection requests. Each has unanswered/answering/answered screenshots as applicable, an inspected saved result, one continuation, and an individual experience review in the local HTML gallery. - The dedicated private QA app/channel used signed callbacks to the local candidate. A separately approved password-protected, read-only preview proved connection-review, suggested-task review, and created-task navigation. Anonymous access, writes, and credential routes were denied. No OAuth grant was attempted. - Real testing exposed and repaired a multi-select continuation failure and a misleading error on link-button clicks. Failed attempts remain in the evidence. The final navigation replay opened the exact pending connection request and declined it in Slack without granting access. Suggested-task creation produced the selected child with the correct parent and description. - Final review-fix verification: **32 form tests**, **28 provider/form-rendering tests**, **30 publication tests**, and **171 native continuation/authorization tests** passed. Earlier **3 atomic-resolution rollback**, **9 targeted callback/publication/Telegram**, and **28 review-continuation** cases passed. The final Slack/Teams modal subset also passed. The automation-origin connection cases, 101/128 custom-choice cases, and oversized multi-select continuation reproduced before their fixes and passed afterward; failing logs remain retained. These counts describe relevant runs, not a reliability percentage. - CI on `b5885b85fd` exposed a test fixture that assumed every Slack modal block was an input; the new sharing notice correctly renders a non-input block. The fixture now selects input blocks safely. The exact signed-modal correction/one-continuation test passed locally, together with 14 Slack form/modal tests. The failing CI log and its specific cause remain recorded. - `pnpm -r typecheck` and `pnpm build` passed. Server typechecking was repeated after the final source changes. Map and module-boundary checks and `git diff --check` passed. - The full `pnpm test:run` was attempted and stopped after repeated embedded PostgreSQL semaphore exhaustion on this host. Its 1,395-test chat suite found two stale native-control assertions; both were corrected and re-tested in a focused run. Focused database suites used separate disposable databases on existing local PostgreSQL. The full suite is not claimed green; new-head CI must complete before merge. - Final-head CI passed on `e0017d446b1016a38d65382366cd1408cce33039`: all test/build jobs and required `ci / verify` and `ci / e2e` gates are green ([run](https://github.com/paperclipai/paperclip/actions/runs/40115430194)). Greptile and Ponytail both reviewed this exact head at 5/5, the security scan passed, and all review threads are resolved. - All three QA app callbacks were restored to staging. Both temporary tunnels and local proxies were closed. The local endpoint was archived and its local credential copies removed. The candidate app was stopped. Limits: provider execution used a deterministic Claude protocol fixture, not an LLM. This is local real-provider UX proof, not deployed staging or broader Codie/Claude qualification. The public preview intentionally blocked ancillary artifact routes, so its destination pages could show a partial-history warning. The complete permission-grant flow and every oversized/mixed-form branch were not driven manually. Earlier fixture, test, and provider failures remain recorded. ## Risks - New reply routes require durable origin proof. Incorrect receipt matching could lose a reply or route it incorrectly. Tests cover missing, forged, mismatched, and revoked authority. - Governed forms keep their Paperclip resolution checks. This change does not grant new approval authority to Slack. - Existing completed review results can become deliverable through the repaired publication path without another provider run. - No schema, lockfile, workflow, public task-status model, or runtime-instruction change is included. This branch is not deployed. ## Model Used OpenAI Codex, GPT-6 family, with code execution and tool use. The exact backend model ID and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either linked existing issues or described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal Paperclip ticket id - [x] I have run focused tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green on the new head - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups on the new head - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
425 lines
15 KiB
TypeScript
425 lines
15 KiB
TypeScript
import type {
|
|
SafeChatPublicationPayload,
|
|
SafeExternalChatCard,
|
|
SafeExternalChatCardAction,
|
|
SafeExternalChatCardKind,
|
|
} from "@paperclipai/shared";
|
|
import { redactSensitiveText } from "../redaction.js";
|
|
|
|
// Bound sanitization work, not the amount silently delivered. The Board accepts
|
|
// 100k UTF-16 units; expansion from redaction/mention neutralization is allowed.
|
|
const MAX_TEXT_INPUT_LENGTH = 1_000_000;
|
|
const MAX_TEXT_OUTPUT_LENGTH = 4_000_000;
|
|
const MAX_ATTACHMENTS = 20;
|
|
const MAX_CARD_ACTIONS = 12;
|
|
const MAX_TITLE_LENGTH = 160;
|
|
const MAX_ACTION_LABEL_LENGTH = 80;
|
|
|
|
const UUID_RE =
|
|
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
const SAFE_IDENTIFIER_RE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,159}$/;
|
|
|
|
const HIDDEN_BLOCKS = [
|
|
/<analysis(?:\s[^>]*)?>[\s\S]*?<\/analysis>/gi,
|
|
/<thinking(?:\s[^>]*)?>[\s\S]*?<\/thinking>/gi,
|
|
/<reasoning(?:\s[^>]*)?>[\s\S]*?<\/reasoning>/gi,
|
|
/<chain_of_thought(?:\s[^>]*)?>[\s\S]*?<\/chain_of_thought>/gi,
|
|
/<tool(?:_trace|_call|_result)?(?:\s[^>]*)?>[\s\S]*?<\/tool(?:_trace|_call|_result)?>/gi,
|
|
/<(?:internal|debug|logs?)(?:\s[^>]*)?>[\s\S]*?<\/(?:internal|debug|logs?)>/gi,
|
|
/```(?:analysis|thinking|reasoning|chain[-_ ]?of[-_ ]?thought|tool(?:[-_ ]?(?:trace|call|result))?|trace|internal|debug|logs?|console|stdout|stderr)\b[^\r\n]*[\r\n][\s\S]*?```/gi,
|
|
/<(?:analysis|thinking|reasoning|chain_of_thought|tool(?:_trace|_call|_result)?|internal|debug|logs?)(?:\s[^>]*)?>[\s\S]*$/gi,
|
|
/```(?:analysis|thinking|reasoning|chain[-_ ]?of[-_ ]?thought|tool(?:[-_ ]?(?:trace|call|result))?|trace|internal|debug|logs?|console|stdout|stderr)\b[^\r\n]*[\r\n][\s\S]*$/gi,
|
|
/<!--[\s\S]*?-->/g,
|
|
];
|
|
|
|
const HIDDEN_SECTION_HEADING_RE =
|
|
/^(#{1,6})\s*(?:analysis|thinking|reasoning|chain[- ]of[- ]thought|internal(?: notes?)?|tool (?:trace|calls?|results?)|debug(?: logs?)?|raw logs?)\s*:?[ \t]*$/i;
|
|
const ANY_MARKDOWN_HEADING_RE = /^(#{1,6})\s+/;
|
|
const HIDDEN_LINE_RE =
|
|
/^\s*(?:(?:thought|thinking|reasoning|chain[- ]of[- ]thought|internal(?: note)?|tool(?: call| result| trace)?|stdout|stderr)\s*:|\[(?:trace|debug|internal|tool)\]|(?:trace|debug|internal)\s+\|)/i;
|
|
const STRUCTURED_LOG_LINE_RE =
|
|
/^\s*(?:\d{4}-\d{2}-\d{2}[T ][0-9:.+-]+\s+)?(?:\[(?:trace|debug)\]|(?:trace|debug)\b[: ]|(?:stdout|stderr)\s*:)/i;
|
|
|
|
const PRIVATE_KEY_RE =
|
|
/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gi;
|
|
const KNOWN_CREDENTIAL_RE =
|
|
/\b(?:sk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{16,}|xox[baprs]-[A-Za-z0-9-]{10,}|gh(?:p|o|u|s|r)_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|npm_[A-Za-z0-9]{20,}|AIza[0-9A-Za-z_-]{20,}|AKIA[0-9A-Z]{16})\b/g;
|
|
const LABELED_CREDENTIAL_RE =
|
|
/\b(api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|auth[-_ ]?token|client[-_ ]?secret|webhook[-_ ]?secret|token|secret|password|passwd|credential)\b(\s*(?:=|:)\s*)(?!\[REDACTED\])(?:"[^"]*"|'[^']*'|`[^`]*`|[^\s,;}\]]+)/gi;
|
|
const CONNECTION_STRING_RE =
|
|
/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?|ftp|sftp):\/\/[^\s<>()]+/gi;
|
|
|
|
const MARKDOWN_LINK_RE = /\[([^\]\r\n]{1,500})\]\(([^)\r\n]+)\)/g;
|
|
const AUTOLINK_RE = /<(https?:\/\/[^\s<>]+)>/gi;
|
|
const PLAIN_HTTP_URL_RE = /https?:\/\/[^\s<>"'`]+/gi;
|
|
const UNSAFE_SCHEME_RE =
|
|
/\b(?:javascript|data|file|vbscript|ssh):[^\s<>"'`)\]]+/gi;
|
|
const PROVIDER_BROADCAST_RE = /@(channel|here|everyone|all)\b/gi;
|
|
const SLACK_BROADCAST_RE = /<!(channel|here|everyone|group)>/gi;
|
|
|
|
const PUBLICATION_SOURCES = new Set<ExternalChatPublicationSource>([
|
|
"agent_comment",
|
|
"explicit_board_send",
|
|
"safe_milestone",
|
|
"issue_interaction",
|
|
"task_control",
|
|
]);
|
|
const CARD_KINDS = new Set<SafeExternalChatCardKind>([
|
|
"status",
|
|
"question",
|
|
"confirmation",
|
|
]);
|
|
const CARD_ACTION_STYLES = new Set<
|
|
NonNullable<
|
|
Extract<SafeExternalChatCardAction, { type: "callback" }>["style"]
|
|
>
|
|
>(["default", "primary", "danger"]);
|
|
const PROGRESS_STATES = new Set<
|
|
NonNullable<SafeChatPublicationPayload["progressState"]>
|
|
>([
|
|
"queued",
|
|
"working",
|
|
"waiting_for_input",
|
|
"approval_needed",
|
|
"completed",
|
|
"failed",
|
|
]);
|
|
|
|
export type ExternalChatPublicationSource =
|
|
| "agent_comment"
|
|
| "explicit_board_send"
|
|
| "safe_milestone"
|
|
| "issue_interaction"
|
|
| "task_control";
|
|
|
|
export interface ChatPublicationProjectionInput {
|
|
/** A caller must deliberately classify the source as externally visible. */
|
|
classification: "external";
|
|
source: ExternalChatPublicationSource;
|
|
text: string;
|
|
attachmentIds?: readonly string[] | null;
|
|
progressState?: SafeChatPublicationPayload["progressState"];
|
|
interaction?: {
|
|
id: string;
|
|
card: {
|
|
kind: SafeExternalChatCardKind;
|
|
title: string;
|
|
body?: string | null;
|
|
actions?: readonly SafeExternalChatCardAction[] | null;
|
|
selection?: SafeExternalChatCard["selection"];
|
|
};
|
|
} | null;
|
|
}
|
|
|
|
/**
|
|
* The persisted outbox payload produced by this boundary. `card` is a closed,
|
|
* provider-agnostic rendering description; adapters may render it natively or
|
|
* fall back to the already-sanitized text.
|
|
*/
|
|
export type ProjectedSafeChatPublicationPayload = SafeChatPublicationPayload;
|
|
|
|
export class UnsafeChatPublicationError extends Error {
|
|
constructor(message: string) {
|
|
super(message);
|
|
this.name = "UnsafeChatPublicationError";
|
|
}
|
|
}
|
|
|
|
function stripHiddenSections(input: string): string {
|
|
const output: string[] = [];
|
|
let hiddenHeadingLevel: number | null = null;
|
|
|
|
for (const line of input.split(/\r?\n/)) {
|
|
const hiddenHeading = line.match(HIDDEN_SECTION_HEADING_RE);
|
|
if (hiddenHeading) {
|
|
hiddenHeadingLevel = hiddenHeading[1].length;
|
|
continue;
|
|
}
|
|
|
|
if (hiddenHeadingLevel !== null) {
|
|
const nextHeading = line.match(ANY_MARKDOWN_HEADING_RE);
|
|
if (!nextHeading || nextHeading[1].length > hiddenHeadingLevel) continue;
|
|
hiddenHeadingLevel = null;
|
|
}
|
|
|
|
if (HIDDEN_LINE_RE.test(line) || STRUCTURED_LOG_LINE_RE.test(line))
|
|
continue;
|
|
output.push(line);
|
|
}
|
|
|
|
return output.join("\n");
|
|
}
|
|
|
|
/**
|
|
* Allows only public HTTPS URLs. User info, query strings, and fragments are
|
|
* intentionally discarded because signed URLs and OAuth/login tokens commonly
|
|
* place credentials there. Callers must never use this function as a fetch
|
|
* allowlist; it only projects display links.
|
|
*/
|
|
export function sanitizeExternalChatUrl(input: string): string | null {
|
|
const candidate = input.trim();
|
|
if (
|
|
!candidate ||
|
|
candidate.length > 2_048 ||
|
|
/[\u0000-\u001f\u007f]/.test(candidate)
|
|
) {
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
const parsed = new URL(candidate);
|
|
if (
|
|
parsed.protocol !== "https:" ||
|
|
parsed.username ||
|
|
parsed.password ||
|
|
!parsed.hostname
|
|
) {
|
|
return null;
|
|
}
|
|
const hostname = parsed.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
if (
|
|
hostname === "localhost" ||
|
|
hostname.endsWith(".localhost") ||
|
|
hostname.endsWith(".local") ||
|
|
hostname.endsWith(".internal") ||
|
|
hostname === "::1" ||
|
|
/^(?:fc|fd|fe8|fe9|fea|feb)[0-9a-f:]*$/i.test(hostname) ||
|
|
/^(?:127|10|0)\./.test(hostname) ||
|
|
/^169\.254\./.test(hostname) ||
|
|
/^192\.168\./.test(hostname) ||
|
|
/^172\.(?:1[6-9]|2\d|3[01])\./.test(hostname)
|
|
) {
|
|
return null;
|
|
}
|
|
parsed.search = "";
|
|
parsed.hash = "";
|
|
return parsed.toString();
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function sanitizeUrls(input: string): string {
|
|
let output = input.replace(
|
|
MARKDOWN_LINK_RE,
|
|
(_match, label: string, href: string) => {
|
|
const safeUrl = sanitizeExternalChatUrl(href);
|
|
return safeUrl ? `[${label}](${safeUrl})` : label;
|
|
},
|
|
);
|
|
output = output.replace(AUTOLINK_RE, (_match, href: string) => {
|
|
const safeUrl = sanitizeExternalChatUrl(href);
|
|
return safeUrl ? `<${safeUrl}>` : "[link removed]";
|
|
});
|
|
output = output.replace(PLAIN_HTTP_URL_RE, (href) => {
|
|
const trailing = href.match(/[.,;:!?]+$/)?.[0] ?? "";
|
|
const candidate = trailing ? href.slice(0, -trailing.length) : href;
|
|
return `${sanitizeExternalChatUrl(candidate) ?? "[link removed]"}${trailing}`;
|
|
});
|
|
return output.replace(UNSAFE_SCHEME_RE, "[link removed]");
|
|
}
|
|
|
|
function sanitizeCredentialText(input: string): string {
|
|
return redactSensitiveText(input)
|
|
.replace(PRIVATE_KEY_RE, "[REDACTED]")
|
|
.replace(KNOWN_CREDENTIAL_RE, "[REDACTED]")
|
|
.replace(
|
|
LABELED_CREDENTIAL_RE,
|
|
(_match, label: string, separator: string) =>
|
|
`${label}${separator}[REDACTED]`,
|
|
)
|
|
.replace(CONNECTION_STRING_RE, "[REDACTED]");
|
|
}
|
|
|
|
function truncateByCodePoint(input: string, limit: number): string {
|
|
if (input.length <= limit) return input;
|
|
return Array.from(input).slice(0, limit).join("");
|
|
}
|
|
|
|
/**
|
|
* The only text projection allowed to cross from Paperclip into a provider.
|
|
* It strips internal reasoning/tool/log content, redacts credentials, removes
|
|
* dangerous or token-bearing links, and neutralizes provider-wide mentions.
|
|
*/
|
|
export function projectSafeChatPublicationText(input: string): string {
|
|
if (input.length > MAX_TEXT_INPUT_LENGTH) {
|
|
throw new UnsafeChatPublicationError(
|
|
"External chat text exceeds its processing limit",
|
|
);
|
|
}
|
|
let output = input.replace(/<\|[^|\r\n]{1,80}\|>/g, "");
|
|
for (const pattern of HIDDEN_BLOCKS) output = output.replace(pattern, "");
|
|
output = stripHiddenSections(output);
|
|
// Strip token-bearing query strings before the general credential scanner.
|
|
// That scanner deliberately consumes uncertain unquoted values aggressively;
|
|
// running it first could eat the visible prose following a Markdown URL.
|
|
output = sanitizeUrls(output);
|
|
output = sanitizeCredentialText(output);
|
|
output = output
|
|
.replace(SLACK_BROADCAST_RE, (_match, name: string) => `@\u200b${name}`)
|
|
.replace(PROVIDER_BROADCAST_RE, (_match, name: string) => `@\u200b${name}`)
|
|
.replace(/[ \t]+\n/g, "\n")
|
|
.replace(/\n{3,}/g, "\n\n")
|
|
.trim();
|
|
|
|
if (!output) return "Update available in Paperclip.";
|
|
if (output.length > MAX_TEXT_OUTPUT_LENGTH) {
|
|
throw new UnsafeChatPublicationError(
|
|
"External chat text exceeds its projected processing limit",
|
|
);
|
|
}
|
|
return output;
|
|
}
|
|
|
|
function projectAttachmentIds(
|
|
input: readonly string[] | null | undefined,
|
|
): string[] | undefined {
|
|
if (!input?.length) return undefined;
|
|
if (input.length > MAX_ATTACHMENTS) {
|
|
throw new UnsafeChatPublicationError(
|
|
`External chat publications support at most ${MAX_ATTACHMENTS} attachments`,
|
|
);
|
|
}
|
|
|
|
const output: string[] = [];
|
|
const seen = new Set<string>();
|
|
for (const id of input) {
|
|
const normalized = id.trim().toLowerCase();
|
|
if (!UUID_RE.test(normalized)) {
|
|
throw new UnsafeChatPublicationError(
|
|
"External chat attachment ids must be UUIDs",
|
|
);
|
|
}
|
|
if (!seen.has(normalized)) {
|
|
seen.add(normalized);
|
|
output.push(normalized);
|
|
}
|
|
}
|
|
return output.length ? output : undefined;
|
|
}
|
|
|
|
function projectCard(
|
|
input: NonNullable<ChatPublicationProjectionInput["interaction"]>,
|
|
): { interactionId: string; card: SafeExternalChatCard } {
|
|
if (!SAFE_IDENTIFIER_RE.test(input.id)) {
|
|
throw new UnsafeChatPublicationError(
|
|
"External chat interaction id is invalid",
|
|
);
|
|
}
|
|
if (!CARD_KINDS.has(input.card.kind)) {
|
|
throw new UnsafeChatPublicationError("External chat card kind is invalid");
|
|
}
|
|
|
|
const title = truncateByCodePoint(
|
|
projectSafeChatPublicationText(input.card.title),
|
|
MAX_TITLE_LENGTH,
|
|
);
|
|
const body = input.card.body
|
|
? projectSafeChatPublicationText(input.card.body)
|
|
: undefined;
|
|
const rawActions = input.card.actions ?? [];
|
|
if (rawActions.length > MAX_CARD_ACTIONS) {
|
|
throw new UnsafeChatPublicationError(
|
|
`External chat cards support at most ${MAX_CARD_ACTIONS} actions`,
|
|
);
|
|
}
|
|
|
|
const selection = input.card.selection;
|
|
if (selection && (typeof selection.actionId !== "string" || !SAFE_IDENTIFIER_RE.test(selection.actionId) ||
|
|
!Array.isArray(selection.options) || selection.options.length < 1 || selection.options.length > 100 ||
|
|
selection.options.some(option => !option || typeof option.actionId !== "string" || !SAFE_IDENTIFIER_RE.test(option.actionId)) ||
|
|
new Set(selection.options.map(option => option.actionId)).size !== selection.options.length)) {
|
|
throw new UnsafeChatPublicationError("External chat selection is invalid");
|
|
}
|
|
const safeSelection = selection ? {
|
|
actionId: selection.actionId,
|
|
...(selection.multiple ? { multiple: true, submitLabel: truncateByCodePoint(projectSafeChatPublicationText(selection.submitLabel ?? "Submit"), 75) } : {}),
|
|
label: truncateByCodePoint(projectSafeChatPublicationText(selection.label), 150),
|
|
options: selection.options.map(option => ({
|
|
...(option.selected === true ? { selected: true } : {}),
|
|
actionId: option.actionId,
|
|
label: truncateByCodePoint(projectSafeChatPublicationText(option.label), 75),
|
|
...(option.description ? { description: truncateByCodePoint(projectSafeChatPublicationText(option.description), 75) } : {}),
|
|
})),
|
|
} : undefined;
|
|
const actions: SafeExternalChatCardAction[] = [];
|
|
for (const action of rawActions) {
|
|
const label = truncateByCodePoint(
|
|
projectSafeChatPublicationText(action.label),
|
|
MAX_ACTION_LABEL_LENGTH,
|
|
);
|
|
if (action.type === "callback") {
|
|
if (!SAFE_IDENTIFIER_RE.test(action.actionId)) {
|
|
throw new UnsafeChatPublicationError(
|
|
"External chat action id is invalid",
|
|
);
|
|
}
|
|
if (action.style && !CARD_ACTION_STYLES.has(action.style)) {
|
|
throw new UnsafeChatPublicationError(
|
|
"External chat action style is invalid",
|
|
);
|
|
}
|
|
actions.push({
|
|
type: "callback",
|
|
actionId: action.actionId,
|
|
label,
|
|
...(action.style ? { style: action.style } : {}),
|
|
});
|
|
continue;
|
|
}
|
|
|
|
if (action.type !== "link") {
|
|
throw new UnsafeChatPublicationError(
|
|
"External chat card action type is invalid",
|
|
);
|
|
}
|
|
|
|
const url = sanitizeExternalChatUrl(action.url);
|
|
if (!url) continue;
|
|
actions.push({ type: "link", label, url });
|
|
}
|
|
|
|
return {
|
|
interactionId: input.id,
|
|
card: {
|
|
schema: "paperclip.chat.card.v1",
|
|
kind: input.card.kind,
|
|
title,
|
|
...(body ? { body } : {}),
|
|
...(actions.length ? { actions } : {}),
|
|
...(safeSelection ? { selection: safeSelection } : {}),
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Builds the complete provider-bound payload. This is intentionally the only
|
|
* API that accepts attachments or rich interaction metadata.
|
|
*/
|
|
export function projectSafeChatPublication(
|
|
input: ChatPublicationProjectionInput,
|
|
): ProjectedSafeChatPublicationPayload {
|
|
if (
|
|
input.classification !== "external" ||
|
|
!PUBLICATION_SOURCES.has(input.source)
|
|
) {
|
|
throw new UnsafeChatPublicationError(
|
|
"Chat publication source must be explicitly classified for external delivery",
|
|
);
|
|
}
|
|
if (input.progressState && !PROGRESS_STATES.has(input.progressState)) {
|
|
throw new UnsafeChatPublicationError(
|
|
"External chat progress state is invalid",
|
|
);
|
|
}
|
|
const attachmentIds = projectAttachmentIds(input.attachmentIds);
|
|
const interaction = input.interaction ? projectCard(input.interaction) : null;
|
|
|
|
return {
|
|
text: projectSafeChatPublicationText(input.text),
|
|
...(attachmentIds ? { attachmentIds } : {}),
|
|
...(input.progressState ? { progressState: input.progressState } : {}),
|
|
...(interaction ?? {}),
|
|
};
|
|
}
|