/** * The single output contract shared by every AI Compose generation. * * The plugin sends a `system` prompt that carries the real task: the field's own * system prompt for Compose, or the named action's instruction (Expand, * Simplify, Rephrase, Proofread, Summarize, Tone, Translate) for an action. * For richText Compose it wraps that task in `buildRichTextSystem`, which adds * rules demanding lexical JSON and a blog layout of `[paragraph]` / `[heading]` * markers, contradicting the prose instruction and making the model argue about * the conflict instead of writing. * * So the caller's system prompt is kept and only the contradicting part is * removed: every field follows one rule (plain prose out; the application * assembles the JSON the Compose client parses), while the action instructions * reach the model unchanged. `AI_OUTPUT_RULES` is appended to every generation. */ export const AI_OUTPUT_RULES = `OUTPUT RULES: Respond with plain prose only. Do not output JSON, code fences, schema definitions, or layout markers. Ordinary sentences and paragraphs are the entire expected output; the application converts them into the editor's format. CRITICAL: Never use em-dashes (\u2014) in your writing. Avoid obvious AI tells.`; /** * The plugin's block-placeholder paragraph. Preserved embed blocks are replaced * with `[[[BLOCK_]]]` tokens before generation and swapped back afterwards, so * the model has to echo the tokens verbatim for the blocks to survive. It is the * only part of the plugin's richText RULES block worth keeping. */ const BLOCK_PLACEHOLDER_INSTRUCTION = /- The text may contain one or more standalone placeholder tokens[\s\S]*?surrounding text\./; export const extractBlockPlaceholderInstruction = (pluginSystem?: string): string => { if (!pluginSystem) return ""; const match = pluginSystem.match(BLOCK_PLACEHOLDER_INSTRUCTION); return match ? match[0].trim() : ""; }; /** * `buildRichTextSystem` appends its RULES / LAYOUT INSTRUCTIONS / ADDITIONAL * GUIDELINES block after the caller's own prompt, so cutting at this marker * leaves the field's system prompt (or an action instruction) intact. */ const PLUGIN_RULES_MARKER = "\n\nRULES:"; /** * Backstop for the same text if that marker wording ever changes: the lines that * demand JSON or a layout are dropped wherever they appear. Each pattern matches * a whole line, so an action instruction that merely mentions JSON-ish words in * passing is never touched. */ const CONTRADICTORY_LINE_PATTERNS = [ /^-\s*Ensure the output follows the provided rich text JSON schema exactly\.?$/, /^-\s*Produce valid JSON with no undefined or null values\.?$/, /^LAYOUT INSTRUCTIONS:?$/, /^ADDITIONAL GUIDELINES:?$/, /^\[[a-z][a-z]*\]\s*(-|:)/, ]; const stripContradictoryLines = (text: string): string => text .split("\n") .filter((line) => !CONTRADICTORY_LINE_PATTERNS.some((pattern) => pattern.test(line.trim()))) .join("\n") .replace(/\n{3,}/g, "\n\n") .trim(); const stripPluginOutputDemands = (pluginSystem: string): string => { const markerIndex = pluginSystem.indexOf(PLUGIN_RULES_MARKER); if (markerIndex === -1) return stripContradictoryLines(pluginSystem); const base = pluginSystem.slice(0, markerIndex); const blockInstruction = extractBlockPlaceholderInstruction(pluginSystem); return stripContradictoryLines([base, blockInstruction].filter(Boolean).join("\n\n")); }; /** * The system prompt for one generation: whatever task the plugin sent (the * field's system prompt, or a named action's instruction such as Expand or * Simplify) plus the shared output rules, minus the plugin's JSON/layout demands. */ export const buildComposeSystem = ({ pluginSystem }: { pluginSystem?: string } = {}): string => { const base = stripPluginOutputDemands(pluginSystem ?? ""); return base ? `${base}\n\n${AI_OUTPUT_RULES}` : AI_OUTPUT_RULES; }; type JsonSchemaLike = { definitions?: unknown; properties?: Record; }; export type ProseShape = { kind: "lexical" } | { kind: "field"; key: string }; /** * Whether a generation schema is one this module knows how to fill with prose: * the lexical editor schema for richText (identified by its `definitions`), or * a single string property for text/textarea. Anything else (e.g. a hasMany * array) is left to the handler's structured fallback. */ export const resolveProseShape = (schema: unknown): ProseShape | null => { if (!schema || typeof schema !== "object") return null; const candidate = schema as JsonSchemaLike; if (candidate.definitions) return { kind: "lexical" }; const keys = Object.keys(candidate.properties ?? {}); if (keys.length !== 1) return null; const property = candidate.properties?.[keys[0]]; if (property?.type !== "string") return null; return { kind: "field", key: keys[0] }; }; export const wrapProse = (shape: ProseShape, text: string): Record => shape.kind === "lexical" ? plainTextToLexicalJson(text) : { [shape.key]: text }; export function plainTextToLexicalJson(text: string): Record { const paragraphs = text.split(/\n\n+/).filter((p) => p.trim()); const children = paragraphs.map((para) => ({ type: "paragraph", children: [ { type: "text", text: para.trim(), format: 0, style: "", mode: "normal", detail: 0, direction: "ltr", indent: 0, version: 1, }, ], direction: "ltr", format: "start", indent: 0, textFormat: 0, textStyle: "", version: 1, })); return { root: { type: "root", children, direction: "ltr", format: "", indent: 0, version: 1, }, }; }