/**
 * Prompt composer. The base is the OD-adapted "expert designer" system
 * prompt (see ./official-system.ts) — a full identity, workflow, and
 * content-philosophy charter. Stacked on top:
 *
 *   1. The discovery + planning + huashu-philosophy layer (./discovery.ts)
 *      — interactive question-form syntax, direction-picker fork,
 *      brand-spec extraction, TodoWrite reinforcement, 5-dim critique,
 *      and the embedded `directions.ts` library.
 *   2. The active design system's DESIGN.md (if any) — palette, typography,
 *      spacing rules treated as authoritative tokens.
 *   3. The active skill's SKILL.md (if any) — workflow specific to the
 *      kind of artifact being built. When the skill ships a seed
 *      (`assets/template.html`) and references (`references/layouts.md`,
 *      `references/checklist.md`), we inject a hard pre-flight rule above
 *      the skill body so the agent reads them BEFORE writing any code.
 *   4. For decks (skillMode === 'deck' OR metadata.kind === 'deck'), the
 *      deck framework directive (./deck-framework.ts) is pinned LAST so it
 *      overrides any softer slide-handling wording earlier in the stack —
 *      this is the load-bearing nav / counter / scroll JS / print
 *      stylesheet contract that PDF stitching depends on. We also fire on
 *      the metadata path so deck-kind projects without a bound skill
 *      (skill_id null) still get a framework, instead of having the agent
 *      re-author scaling / nav / print logic from scratch each turn. When
 *      the active skill ships its own seed (skill body references
 *      `assets/template.html`), we defer to that seed and skip the generic
 *      skeleton — the skill's framework wins to avoid double-injection.
 *
 * The composed string is what the daemon sees as `systemPrompt` and what
 * the Anthropic path sends as `system`.
 */
import { OFFICIAL_DESIGNER_PROMPT } from './official-system.js';
import { DISCOVERY_AND_PHILOSOPHY } from './discovery.js';
import { DECK_FRAMEWORK_DIRECTIVE } from './deck-framework.js';
import { MEDIA_GENERATION_CONTRACT } from './media-contract.js';
import { IMAGE_MODELS } from '../media-models.js';
import { renderPanelPrompt } from './panel.js';
import { defaultCritiqueConfig } from '@open-design/contracts/critique';
const ELEVENLABS_VOICE_PROMPT_OPTION_LIMIT = 100;
const ELEVENLABS_VOICE_OPTIONS_PROMPT_PREFIX = 'ElevenLabs voice list could not be loaded';
const PROMPT_SAFE_HTTP_STATUS_LABELS = {
    '400': 'Bad Request',
    '401': 'Unauthorized',
    '403': 'Forbidden',
    '404': 'Not Found',
    '429': 'Too Many Requests',
    '500': 'Internal Server Error',
    '502': 'Bad Gateway',
    '503': 'Service Unavailable',
    '504': 'Gateway Timeout',
};
function normalizePromptText(value) {
    return value
        .replace(/[\r\n]+/g, ' ')
        .replace(/\s+/g, ' ')
        .trim();
}
function formatElevenLabsVoiceOptionsErrorForPrompt(error) {
    const trimmed = normalizePromptText(error ?? '');
    if (!trimmed)
        return undefined;
    if (/no ElevenLabs API key/i.test(trimmed)) {
        return `${ELEVENLABS_VOICE_OPTIONS_PROMPT_PREFIX} because the ElevenLabs API key is missing. Tell the user to configure it in Settings or paste a voice id manually.`;
    }
    const statusMatch = trimmed.match(/(?:\((\d{3})(?:\s+([^)]+))?\)|\b(\d{3})(?:\s+([A-Za-z][A-Za-z -]{0,40}))?\b)/);
    if (statusMatch) {
        const statusCode = statusMatch[1] ?? statusMatch[3];
        const statusText = statusCode ? PROMPT_SAFE_HTTP_STATUS_LABELS[statusCode] ?? '' : '';
        const suffix = statusText ? ` ${statusText}` : '';
        return `${ELEVENLABS_VOICE_OPTIONS_PROMPT_PREFIX} (${statusCode}${suffix}). Tell the user to retry the lookup or paste a voice id manually.`;
    }
    return `${ELEVENLABS_VOICE_OPTIONS_PROMPT_PREFIX}. Tell the user to retry the lookup or paste a voice id manually.`;
}
export const BASE_SYSTEM_PROMPT = OFFICIAL_DESIGNER_PROMPT;
export const SKIP_DISCOVERY_BRIEF_OVERRIDE = `# Automated project mode — skip discovery form

This project was created through the daemon API with \`skipDiscoveryBrief: true\`. Override the discovery rules below: do NOT emit \`<question-form id="discovery">\`, do NOT show "Quick brief — 30 seconds", and do NOT ask a first-turn clarification form. Treat the user's first message and project metadata as the brief, then proceed directly to planning/building under the normal artifact workflow. Ask at most one concise follow-up only if a required detail is impossible to infer safely.`;
export function composeSystemPrompt({ agentId, includeCodexImagegenOverride = true, skillBody, skillName, skillMode, designSystemBody, designSystemTitle, designSystemTokensCss, designSystemFixtureHtml, craftBody, craftSections, memoryBody, metadata, template, audioVoiceOptions, audioVoiceOptionsError, critique, critiqueBrand, critiqueSkill, connectedExternalMcp, streamFormat, userInstructions, projectInstructions, }) {
    // Discovery + philosophy goes FIRST so its hard rules ("emit a form on
    // turn 1", "branch on brand on turn 2", "TodoWrite on turn 3", run
    // checklist + critique before <artifact>) win precedence over softer
    // wording later in the official base prompt.
    const parts = [];
    // API/BYOK mode (streamFormat === 'plain'): mirrors the same fix from
    // `@open-design/contracts`'s composer. The daemon hits this path for
    // any plain-stream adapter (e.g. DeepSeek), so without pinning the
    // override above DISCOVERY_AND_PHILOSOPHY here too, those daemon
    // agents still emit the `<todo-list>` / `[读取 X]` pseudo-tool
    // markup described in #313. Keep the wording byte-identical to the
    // contracts copy so both code paths produce the same observable
    // behaviour.
    if (streamFormat === 'plain') {
        parts.push(API_MODE_OVERRIDE);
        parts.push('\n\n---\n\n');
    }
    if (metadata?.skipDiscoveryBrief === true) {
        parts.push(SKIP_DISCOVERY_BRIEF_OVERRIDE);
        parts.push('\n\n---\n\n');
    }
    parts.push(DISCOVERY_AND_PHILOSOPHY, '\n\n---\n\n# Identity and workflow charter (background)\n\n', BASE_SYSTEM_PROMPT);
    if (memoryBody && memoryBody.trim().length > 0) {
        parts.push(`\n\n## Personal memory (auto-extracted from past chats)\n\nThe following facts have been sedimented from this user's previous conversations and edited in the settings panel. Treat them as preferences and context, NOT hard rules: when they collide with the active design system tokens, the brand wins; when they collide with the active skill's workflow, the skill wins. They are still authoritative for tone, voice, terminology, and what the user already told you about themselves and their goals — never re-ask the user about something already captured here.\n\n${memoryBody.trim()}`);
    }
    if (userInstructions && userInstructions.trim().length > 0) {
        parts.push(`\n\n## Custom instructions (user-level)\n\nThe user has set the following persistent instructions. Apply them as defaults to every project. When a project-level instruction below contradicts a point here, the project-level version wins.\n\n${userInstructions.trim()}`);
    }
    if (projectInstructions && projectInstructions.trim().length > 0) {
        parts.push(`\n\n## Custom instructions (project-level)\n\nThe user has set the following instructions for this specific project. They take precedence over user-level custom instructions whenever both address the same topic (e.g. if user-level says "use spaces" but project-level says "use tabs", use tabs).\n\n${projectInstructions.trim()}`);
    }
    if (designSystemBody && designSystemBody.trim().length > 0) {
        parts.push(`\n\n## Active design system${designSystemTitle ? ` — ${designSystemTitle}` : ''}\n\nTreat the following DESIGN.md as authoritative for color, typography, spacing, and component rules. Do not invent tokens outside this palette. When you copy the active skill's seed template, bind these tokens into its \`:root\` block before generating any layout.\n\n${designSystemBody.trim()}`);
    }
    // Structured (compiled) form of the active brand. The DESIGN.md above
    // sets voice and intent; the tokens.css block below is the SAME
    // contract in machine-readable form — names + values the agent pastes
    // verbatim instead of re-deriving from prose. The components.html
    // fixture grounds the token vocabulary in worked component shapes
    // (button / card / type roles) so the agent can copy fragments
    // directly. Both blocks are individually gated: missing files (today,
    // every brand except `default` and `kami`) skip silently, preserving
    // the legacy DESIGN.md-only behaviour for the other ~138 brands.
    if (designSystemTokensCss && designSystemTokensCss.trim().length > 0) {
        parts.push(`\n\n## Active design system tokens${designSystemTitle ? ` — ${designSystemTitle}` : ''}\n\nThe block below is this brand's tokens.css contract — every \`:root\` custom property and any scoped override (e.g. \`:root[lang=...]\`) the brand defines. **Paste the unscoped \`:root { ... }\` block verbatim into the artifact's first \`<style>\`** so every \`var(--*)\` reference resolves at runtime.\n\nDo not invent new tokens. Do not redefine these values. Do not write raw hex outside this :root block. The DESIGN.md above is prose; this is the binding contract.\n\n\`\`\`css\n${designSystemTokensCss.trim()}\n\`\`\``);
    }
    if (designSystemFixtureHtml && designSystemFixtureHtml.trim().length > 0) {
        parts.push(`\n\n## Reference fixture${designSystemTitle ? ` — ${designSystemTitle}` : ''}\n\nA self-contained worked artifact in this design system. Match its component shapes (button structure, card structure, type-scale rhythm, focus ring, spacing cadence) when generating new artifacts. Copying fragments is encouraged as long as you keep the \`var(--*)\` references intact — they are already wired to the tokens above.\n\n\`\`\`html\n${designSystemFixtureHtml.trim()}\n\`\`\``);
    }
    if (craftBody && craftBody.trim().length > 0) {
        const sectionLabel = Array.isArray(craftSections) && craftSections.length > 0
            ? ` — ${craftSections.join(', ')}`
            : '';
        parts.push(`\n\n## Active craft references${sectionLabel}\n\nThe following craft rules are universal — they apply on top of the active design system above, regardless of brand. The DESIGN.md decides *which* tokens to use; craft rules decide *how* to use them. On any conflict between a craft rule and a brand DESIGN.md, the brand wins for token values; craft rules still apply to anything the brand does not override (letter-spacing, accent overuse caps, anti-slop patterns).\n\n${craftBody.trim()}`);
    }
    if (skillBody && skillBody.trim().length > 0) {
        const preflight = derivePreflight(skillBody);
        parts.push(`\n\n## Active skill${skillName ? ` — ${skillName}` : ''}\n\nFollow this skill's workflow exactly.${preflight}\n\n${skillBody.trim()}`);
    }
    const metaBlock = renderMetadataBlock(metadata, template, audioVoiceOptions, audioVoiceOptionsError);
    if (metaBlock)
        parts.push(metaBlock);
    // Decks have a load-bearing framework (nav, counter, scroll JS, print
    // stylesheet for PDF stitching). Pin it last so it overrides any softer
    // wording earlier in the stack ("write a script that handles arrows…").
    //
    // We fire on either (a) the active skill is a deck skill OR (b) the
    // project metadata declares kind=deck. Case (b) catches projects created
    // without a skill (skill_id null) — without this, a deck-kind project
    // with no bound skill gets neither a skill seed nor the framework
    // skeleton, and the agent writes scaling / nav / print logic from scratch
    // with the same buggy `place-items: center` + transform pattern we keep
    // having to fix at runtime. Skill seeds (when present) win — they
    // already define their own opinionated framework (simple-deck's
    // scroll-snap, guizang-ppt's magazine layout) and re-pinning the generic
    // skeleton would conflict. The skill-seed path takes over via
    // `derivePreflight` above, so we only fire the generic skeleton when no
    // skill seed is on offer.
    const isDeckProject = skillMode === 'deck' || metadata?.kind === 'deck';
    const hasSkillSeed = !!skillBody && /assets\/template\.html/.test(skillBody);
    if (isDeckProject && !hasSkillSeed) {
        parts.push(`\n\n---\n\n${DECK_FRAMEWORK_DIRECTIVE}`);
    }
    const isMediaSurface = skillMode === 'image' ||
        skillMode === 'video' ||
        skillMode === 'audio' ||
        metadata?.kind === 'image' ||
        metadata?.kind === 'video' ||
        metadata?.kind === 'audio';
    if (isMediaSurface) {
        parts.push(MEDIA_GENERATION_CONTRACT);
    }
    if (includeCodexImagegenOverride) {
        const codexImagegenOverride = renderCodexImagegenOverride(agentId, metadata);
        if (codexImagegenOverride) {
            parts.push(codexImagegenOverride);
        }
    }
    // Critique Theater addendum. When cfg.enabled is true the panel protocol
    // is pinned last so it overrides any softer critique wording earlier in the
    // stack. When disabled (the default) this block is a no-op so no consumer
    // needs to opt in.
    //
    // The panel block requires <ARTIFACT mime="text/html"> inside <CRITIQUE_RUN>,
    // which conflicts with MEDIA_GENERATION_CONTRACT (image/video/audio surfaces
    // explicitly forbid HTML output). Skip the addendum on media surfaces so
    // the critique flag is a no-op there until a media-aware panel template
    // lands.
    const cfg = critique ?? defaultCritiqueConfig();
    if (cfg.enabled && critiqueBrand && critiqueSkill && !isMediaSurface) {
        parts.push('\n\n' + renderPanelPrompt({ cfg, brand: critiqueBrand, skill: critiqueSkill }));
    }
    const mcpDirective = renderConnectedExternalMcpDirective(connectedExternalMcp);
    if (mcpDirective)
        parts.push(mcpDirective);
    // Claude only: nudge the model toward the `AskUserQuestion` tool for
    // mid-conversation clarifications. Without this hint Claude tends to fall
    // back to a markdown bulleted list of options, which the chat UI cannot
    // turn into clickable buttons. Discovery (turn 1) is still owned by the
    // `<question-form>` flow defined in DISCOVERY_AND_PHILOSOPHY; this only
    // covers follow-ups where the next action depends on a small set of
    // choices the user can pick quickly.
    if (agentId === 'claude') {
        parts.push("\n\n---\n\n## Clarifying questions\n\nWhen you need a mid-conversation clarification AND the natural answer is one of a small finite set of choices (2-4 options per question), call the `AskUserQuestion` tool instead of writing a bulleted list in markdown. The host chat renders the tool call as inline choice buttons; a markdown list renders as plain text and forces the user to type a reply. Skip the tool when the answer is naturally free-form text, when the answer needs more than ~4 options, or when you only have one yes/no choice to ask. First-turn discovery still uses the `<question-form id=\"discovery\">` workflow described earlier; `AskUserQuestion` is for follow-ups only.\n\n**When you call `AskUserQuestion`, that tool call is the entire response.** Do NOT also write the same questions or options as markdown text alongside it, do NOT add a trailing prose paragraph like \"what sounds right?\", do NOT hedge by listing the options twice. Emit the tool call and stop generating tokens. The host is waiting on the tool's `tool_result` and will resume your turn the moment the user answers. Anything you write before, between, or after the tool call in the same message just duplicates what the card already shows and confuses the user.");
    }
    return parts.join('');
}
/**
 * Top-anchored override for plain-stream daemon agents (#313). Mirrors
 * the contracts-package copy byte-for-byte; see that file for the full
 * rationale. Pinning it at the absolute top of the composed prompt is
 * what beats the discovery layer's own "these override anything later"
 * header — the old bottom-appended `## API mode rule` lost that
 * precedence war and let `<todo-list>` / `[读取 X]` pseudo-tool markup
 * leak into the chat.
 */
const API_MODE_OVERRIDE = `# API mode — no tools available (read first — overrides every rule below)

You are running through a plain Messages API. **No tools are wired through to you.** \`TodoWrite\`, \`Read\`, \`Write\`, \`Edit\`, \`Bash\`, and \`WebFetch\` are unavailable — calls to them will not execute and will not render in the UI.

Every later instruction in this prompt that tells you to "call TodoWrite", "run Bash", "read via Read", or otherwise invoke a tool is describing the daemon-mode workflow. In this API run those instructions are **overridden** — do not attempt them and do not pretend you did.

**Forbidden output:**
- Pseudo-tool markup such as \`<todo-list>...</todo-list>\`, \`<tool-call>\`, or invented XML wrappers around a plan.
- Fake-protocol prose such as \`[读取 template.html ...]\`, \`[读取 layouts.md ...]\`, \`[正在调用 TodoWrite ...]\`, or any \`[doing X]\` placeholder narrating a tool you cannot run.
- Statements like "I'll call TodoWrite to track this" or "let me read the skill file first" — there is no TodoWrite and no Read in this run.

**Allowed output:**
- Plain chat prose to the user (in their language). State your plan as prose — a short numbered list in markdown is fine; it just must not be wrapped in \`<todo-list>\` or claim to be a tool call.
- A final \`<artifact type="text/html">...</artifact>\` block containing a complete \`<!doctype html>\` document when the brief is ready to deliver.
- \`<question-form>\` blocks for discovery on turn 1, exactly as the rules below describe — question-form is markup the UI parses, not a tool call.

If the rules below tell you to plan with TodoWrite, write the plan as prose instead. If they tell you to read skill side files before writing, describe in one sentence which patterns/conventions you're going to apply and proceed. If they tell you to run brand-spec extraction via Bash + Read + WebFetch, ask the user the missing brand questions in the discovery form instead.`;
// Defense-in-depth against Claude Code's synthetic OAuth tools.
//
// When Claude Code's built-in HTTP MCP transport gets a 401 on its first
// initialize (transient propagation lag, edge cache miss, header
// re-canonicalization quirk, etc.), it injects two synthetic tools per
// server — `mcp__<server>__authenticate` and
// `mcp__<server>__complete_authentication` — that drive a per-process
// OAuth dance with a `localhost:<random>/callback` redirect_uri. That
// listener dies with the agent process, so the round-trip never
// completes, and meanwhile the model burns a turn pasting an
// unreachable URL into the chat. By the time the user is back, our
// daemon-issued Bearer is already in `.mcp.json` and the real tools
// (`generate_image`, `models_explore`, …) are reachable on the next
// turn — but the model doesn't know that and keeps escalating the
// fake auth flow.
//
// The fix is to tell the model up front: these specific servers are
// already authenticated by the daemon, do NOT call any
// `*_authenticate` / `*_complete_authentication` tool for them. If
// the real tools really are missing, surface that as a separate
// failure instead of pivoting to the synthetic flow.
function renderConnectedExternalMcpDirective(connectedExternalMcp) {
    if (!connectedExternalMcp || connectedExternalMcp.length === 0)
        return '';
    const lines = connectedExternalMcp
        .map((s) => {
        const id = typeof s?.id === 'string' ? s.id.trim() : '';
        if (!id)
            return null;
        const label = typeof s?.label === 'string' && s.label.trim() ? s.label.trim() : id;
        return `- \`${id}\`${label !== id ? ` (${label})` : ''}`;
    })
        .filter((line) => typeof line === 'string');
    if (lines.length === 0)
        return '';
    return [
        '\n\n---\n\n',
        '## External MCP servers — already authenticated\n\n',
        'The following external MCP servers are already authenticated for this run via an OAuth Bearer token the daemon injected into `.mcp.json`. You can call their real tools directly:\n\n',
        lines.join('\n'),
        '\n\n',
        '**Do NOT call any tool whose name matches `mcp__<server>__authenticate` or `mcp__<server>__complete_authentication` for the servers above.** Those are synthetic fallback tools Claude Code exposes when its first HTTP connect briefly flipped the server into a needs-auth state. The flow they drive (a `localhost:<random>/callback` redirect) cannot complete in this environment, and the real tools (e.g. `generate_image`, `models_explore`, `balance`, …) are already reachable.\n\n',
        'If a real tool actually fails with an auth-related error, report the exact tool name and error text and stop — the user will reconnect the server in Settings → External MCP. Do not retry by invoking any `*_authenticate` tool.\n',
    ].join('');
}
const CODEX_IMAGEGEN_MODEL_IDS = new Set(IMAGE_MODELS.filter((model) => model?.provider === 'openai' &&
    typeof model?.id === 'string' &&
    model.id.startsWith('gpt-image-')).map((model) => model.id));
export function resolveCodexImagegenModelId(metadata) {
    const imageModel = typeof metadata?.imageModel === 'string' ? metadata.imageModel.trim() : '';
    return CODEX_IMAGEGEN_MODEL_IDS.has(imageModel) ? imageModel : '';
}
export function shouldRenderCodexImagegenOverride(agentId, metadata) {
    const normalizedAgentId = typeof agentId === 'string' ? agentId.trim().toLowerCase() : '';
    return (normalizedAgentId === 'codex' &&
        metadata?.kind === 'image' &&
        resolveCodexImagegenModelId(metadata).length > 0);
}
export function renderCodexImagegenOverride(agentId, metadata) {
    if (!shouldRenderCodexImagegenOverride(agentId, metadata)) {
        return '';
    }
    const imageModel = resolveCodexImagegenModelId(metadata);
    return `

---

## Codex built-in imagegen override (load-bearing — Codex only)

The active agent is Codex and this image project selected \`${imageModel}\`.
For this specific case, use Codex's built-in image generation capability
instead of \`"$OD_NODE_BIN" "$OD_BIN" media generate\` for the first generation
attempt. This is an intentional exception to the media generation contract and
the active image skill's dispatcher wording.

Do not require, request, or mention \`OPENAI_API_KEY\` before trying the
built-in path. Reuse the project metadata, reference prompt template, aspect
ratio, style notes, and the user's current brief to form the final image
prompt. Generate the image with Codex built-in imagegen, then use the actual
output path returned by the built-in imagegen result as the source file first.
Only if the built-in result does not return a usable path should you search
\`\${CODEX_HOME:-$HOME/.codex}/generated_images/.../ig_*.png\` as a fallback
source. Never leave a project-referenced asset only under \`$CODEX_HOME\`.

Copy or move the selected generated file into \`$OD_PROJECT_DIR\` with a short
descriptive filename, then verify the exact destination file exists under
\`$OD_PROJECT_DIR\` before claiming success. If reading the source path,
creating the destination directory, copying/moving, or verifying the copied
asset fails, report the exact source path, destination path, and access/copy
error. Do not claim success, silently fall back, or ask about OpenAI/Azure
fallback after a generated image exists but the project copy fails; stop after
reporting the failure unless the user explicitly chooses fallback in a later
turn, because fallback may create a different image.

After the file exists under \`$OD_PROJECT_DIR\`, reply with the project-local
filename and a short summary of the prompt used. Do not emit an \`<artifact>\`
block for media.

If Codex built-in imagegen is unavailable or generation fails before producing
an image, surface the actual failure message and ask the user for one-time
confirmation before falling back to the existing OpenAI/Azure API-key provider
path via \`"$OD_NODE_BIN" "$OD_BIN" media generate --surface image --model ${imageModel}\`.
Do not silently fall back.`;
}
function renderMetadataBlock(metadata, template, audioVoiceOptions, audioVoiceOptionsError) {
    if (!metadata)
        return '';
    const lines = [];
    lines.push('\n\n## Project metadata');
    lines.push('These are the structured choices the user made (or skipped) when creating this project. Treat known fields as authoritative; for any field marked "(unknown — ask)" you MUST include a matching question in your turn-1 discovery form.');
    lines.push('');
    lines.push(`- **kind**: ${metadata.kind}`);
    if (metadata.platform) {
        lines.push(`- **platform**: ${metadata.platform}`);
    }
    else if (metadata.kind === 'prototype' || metadata.kind === 'template' || metadata.kind === 'other') {
        lines.push('- **platform**: (unknown — ask: responsive web, desktop web, iOS app, Android app, tablet app, or desktop app?)');
    }
    if (Array.isArray(metadata.platformTargets) && metadata.platformTargets.length > 0) {
        lines.push(`- **platformTargets**: ${metadata.platformTargets.join(', ')}`);
    }
    if (metadata.platform === 'responsive' || metadata.platformTargets?.includes('responsive')) {
        lines.push('- **responsive web contract**: `responsive` means one web product experience that adapts across modern browser/device ranges, not only legacy desktop/tablet/mobile buckets. It is not an iOS app, Android app, or native tablet app target. Show responsive behavior through real product layout changes; do not render viewport labels as user-facing product content. Cover 2025–2026 breakpoints: mobile compact 360px, mobile standard 390–430px, foldable/small tablet 600–744px, tablet portrait 768–834px, tablet landscape/large tablet 1024–1180px, laptop 1280–1366px, desktop 1440–1536px, and wide 1920px. Use fluid `clamp()` scales, container queries where useful, and explicit layout changes at semantic thresholds. Verify no horizontal scroll at 360px, 390px, 430px, 768px, 820px, 1024px, 1366px, 1440px, and 1920px unless the brief explicitly asks for a pan/board canvas.');
    }
    if ((metadata.platformTargets?.length ?? 0) > 1) {
        lines.push('- **cross-platform deliverable rule**: each selected target keeps the same product goal but MUST be delivered as its own product screen/file when more than one concrete target is selected. Use clear files such as `landing.html` (if enabled), `mobile-ios.html`, `mobile-android.html`, `tablet.html`, `desktop.html`, plus shared `css/` and `js/` when useful. `index.html` may be a launcher/overview that links to these files, but it must not be the only place where mobile/tablet/desktop designs live. Do not collapse cross-platform work into a single tabbed demo, selector UI, comparison board, platform map, or labelled documentation section inside one mock product page.');
    }
    if (metadata.kind === 'prototype' || metadata.kind === 'template' || metadata.kind === 'other') {
        lines.push('- **screen-file-first rule**: each distinct user-facing screen or surface MUST be delivered as its own HTML file unless the user explicitly asks for a single-page scroll or single-file artifact. Do not combine landing pages, product app screens, dashboards, history, pricing, settings, mobile app, tablet app, desktop app, or OS widget surfaces into one long page. Use `index.html` as a launcher/overview that links to screen files when more than one screen exists; it may summarize the product and show screen cards, but it must not contain the full design for every screen.');
        lines.push('- **product-realism rule**: final artifacts must look like real end-user product UI. Do not render project metadata, screen counts, target counts, state counts, "demo only" labels, "settings" panels for choosing platforms, "full design target" badges, viewport/device selector controls, theme/style knobs, platform output maps, behavior-spec sections, or design-process cards inside the product unless the user explicitly asks for a design spec/dashboard. Any navigation/tabs inside the artifact must be real product navigation, not designer controls for switching generated mockups.');
        lines.push('- **visual-system rule**: when the user does not specify colors, layout, or visual direction, you must still make an intentional product-appropriate visual system. Infer a palette from the product category and audience with at least: neutral surface tokens, a primary action color, a secondary/domain accent, and status colors. Avoid plain monochrome/unstyled greyscale outputs. Use tasteful gradients, illustrations, iconography, device/product mockups, and colored state moments where they clarify the product, while still avoiding generic beige/peach/pink/brown AI washes.');
        lines.push('- **app-specific modules rule**: include domain-specific in-app modules/components by default (cards, panels, controls, charts, lists, quick actions, status modules, mini players, checkout/cart summaries, etc. as appropriate). These are product UI modules, not OS home-screen widgets. Give each major module a clear purpose, states, and responsive behavior instead of generic card grids.');
        lines.push('- **CJX-ready UX rule**: the artifact must be implementation-ready, not a static screenshot. Structure CSS tokens/components/responsive sections clearly; include real JavaScript behavior for meaningful UX such as tabs, dialogs, drawers, filters, generation/copy actions, validation, playback controls, or state transitions. If keeping a self-contained `index.html`, put the CSS/JS in clearly labelled blocks; for complex UX, generate `css/` and `js/` files when useful.');
        lines.push('- **interaction-fidelity rule**: when the requested screen includes user input, generation, copying, validation, login, checkout, filtering, or any action verb, build real interactive controls for that screen. Do not substitute static text rows, prefilled-only mockups, screenshot-like device frames, or decorative state cards for editable inputs and working actions.');
    }
    if (metadata.includeLandingPage) {
        lines.push('- **includeLandingPage**: true — create `landing.html` as a separate responsive marketing companion surface in addition to the selected product/app screens. Do not implement the landing page only as a section inside `index.html`, even for responsive-web-only projects. If there is a working product/app screen, create it as a separate file such as `app.html`, `dashboard.html`, or a domain-specific screen name. `index.html` should be a lightweight launcher/overview when multiple files exist. Include hero, value props, product screenshots/device mockups, proof/features, and an appropriate CTA such as waitlist, download, or contact sales.');
    }
    if (metadata.includeOsWidgets) {
        lines.push('- **includeOsWidgets**: true — add platform-native OS home-screen / lock-screen / quick-access widget surfaces where relevant. These are outside-the-app widgets (for example iOS WidgetKit, Android home screen widget, Live Activity/lock screen, tablet glance panel), not in-app cards. Include realistic widget sizes and direct quick actions for the domain.');
    }
    if (metadata.intent === 'live-artifact') {
        lines.push('- **intent**: live-artifact — the user chose New live artifact. The first output should be a live artifact/dashboard/report, not a one-off static mockup. Prefer the `live-artifact` skill workflow when available, keep source data compact, and register through the daemon live-artifact tool path once that wrapper/tooling is available.');
        lines.push('- **connector-source rule**: if the user names a connector/source (for example Notion) and daemon connector tools are available, list connectors before asking where the data comes from. When the named connector is `connected`, use its read-only tools and ask follow-up questions only for missing topic/page/database details, multiple equally plausible matches, or an unconnected/missing connector.');
    }
    if (metadata.kind === 'prototype') {
        lines.push(`- **fidelity**: ${metadata.fidelity ?? '(unknown — ask: wireframe vs high-fidelity)'}`);
    }
    if (metadata.kind === 'deck') {
        lines.push(`- **speakerNotes**: ${typeof metadata.speakerNotes === 'boolean' ? metadata.speakerNotes : '(unknown — ask: include speaker notes?)'}`);
    }
    if (metadata.kind === 'template') {
        lines.push(`- **animations**: ${typeof metadata.animations === 'boolean' ? metadata.animations : '(unknown — ask: include motion/animations?)'}`);
        if (metadata.templateLabel) {
            lines.push(`- **template**: ${metadata.templateLabel}`);
        }
    }
    if (metadata.kind === 'image') {
        lines.push(`- **imageModel**: ${metadata.imageModel ?? '(unknown — ask: which image model to use)'}`);
        lines.push(`- **aspectRatio**: ${metadata.imageAspect ?? '(unknown — ask: 1:1, 16:9, 9:16, 4:3, 3:4)'}`);
        if (metadata.imageStyle) {
            lines.push(`- **styleNotes**: ${metadata.imageStyle}`);
        }
        if (metadata.promptTemplate?.title &&
            typeof metadata.promptTemplate.prompt === 'string' &&
            metadata.promptTemplate.prompt.trim().length > 0) {
            lines.push(`- **referenceTemplate**: ${metadata.promptTemplate.title}`);
        }
        lines.push('');
        lines.push('This is an **image** project. Plan the prompt carefully, then dispatch via the **media generation contract** using `"$OD_NODE_BIN" "$OD_BIN" media generate --surface image --model <imageModel>`. Do NOT emit `<artifact>` HTML for media surfaces.');
    }
    if (metadata.kind === 'video') {
        lines.push(`- **videoModel**: ${metadata.videoModel ?? '(unknown — ask: which video model to use)'}`);
        lines.push(`- **lengthSeconds**: ${typeof metadata.videoLength === 'number' ? metadata.videoLength : '(unknown — ask: 3s / 5s / 10s)'}`);
        lines.push(`- **aspectRatio**: ${metadata.videoAspect ?? '(unknown — ask: 16:9, 9:16, 1:1)'}`);
        if (metadata.promptTemplate?.title &&
            typeof metadata.promptTemplate.prompt === 'string' &&
            metadata.promptTemplate.prompt.trim().length > 0) {
            lines.push(`- **referenceTemplate**: ${metadata.promptTemplate.title}`);
        }
        lines.push('');
        lines.push('This is a **video** project. Plan the shotlist and motion, then dispatch via the **media generation contract** using `"$OD_NODE_BIN" "$OD_BIN" media generate --surface video --model <videoModel> --length <seconds> --aspect <ratio>`. Do NOT emit `<artifact>` HTML.');
        if (metadata.videoModel === 'hyperframes-html') {
            lines.push('Special case: `hyperframes-html` is a local HTML-to-MP4 renderer, not a photoreal text-to-video model. Treat it like a motion design renderer, ask at most one clarifying question, then dispatch immediately.');
        }
    }
    if (metadata.kind === 'audio') {
        lines.push(`- **audioKind**: ${metadata.audioKind ?? '(unknown — ask: music / speech / sfx)'}`);
        lines.push(`- **audioModel**: ${metadata.audioModel ?? '(unknown — ask: which audio model to use)'}`);
        lines.push(`- **durationSeconds**: ${typeof metadata.audioDuration === 'number' ? metadata.audioDuration : '(unknown — ask: target duration)'}`);
        if (metadata.voice) {
            lines.push(`- **voice**: ${metadata.voice}`);
        }
        else if (metadata.audioKind === 'speech') {
            lines.push('- **voice**: (unknown — ask: voice id / accent / pacing)');
        }
        const voiceOptions = shouldRenderElevenLabsVoiceOptions(metadata, audioVoiceOptions)
            ? audioVoiceOptions ?? []
            : [];
        if (voiceOptions.length > 0) {
            lines.push('- **ElevenLabs voice options**: Ask the user to choose from a dropdown select. The visible labels are voice descriptions; the selected value must be the exact `voice_id` passed to `--voice`. Do not ask the user to type an id.');
            if (voiceOptions.length > ELEVENLABS_VOICE_PROMPT_OPTION_LIMIT) {
                lines.push(`- **ElevenLabs voice options**: showing the first ${ELEVENLABS_VOICE_PROMPT_OPTION_LIMIT} of ${voiceOptions.length} available voices.`);
            }
            lines.push('');
            lines.push('<question-form id="elevenlabs-voice" title="Choose an ElevenLabs voice">');
            lines.push(JSON.stringify(renderElevenLabsVoiceQuestionForm(voiceOptions), null, 2));
            lines.push('</question-form>');
        }
        else {
            const audioVoiceOptionsPromptError = formatElevenLabsVoiceOptionsErrorForPrompt(audioVoiceOptionsError);
            if (audioVoiceOptionsPromptError) {
                lines.push(`- **ElevenLabs voice options**: ${audioVoiceOptionsPromptError}`);
            }
        }
        if (metadata.audioKind === 'sfx') {
            lines.push('- **SFX discovery**: Ask about the sound source/action, materials, intensity, acoustic space, timing/tail, loop/non-loop, and "avoid" constraints. Do not ask for language or voice for SFX.');
        }
        lines.push('');
        lines.push('This is an **audio** project. Lock the content intent first, then dispatch via the **media generation contract** using `"$OD_NODE_BIN" "$OD_BIN" media generate --surface audio --audio-kind <kind> --model <audioModel> --duration <seconds>` and add `--voice <voice-id>` for speech when you have a provider-specific voice id. Do NOT emit `<artifact>` HTML.');
    }
    if (metadata.inspirationDesignSystemIds && metadata.inspirationDesignSystemIds.length > 0) {
        lines.push(`- **inspirationDesignSystemIds**: ${metadata.inspirationDesignSystemIds.join(', ')} — the user picked these systems as *additional* inspiration alongside the primary one. Borrow palette accents, typographic personality, or component patterns from them; don't replace the primary system's tokens.`);
    }
    // Curated prompt template reference for image/video projects. Inlined
    // verbatim (with light truncation) so the agent can borrow structure,
    // mood and phrasing without a separate fetch. The user may have edited
    // the body before clicking Create — those edits land here and are now
    // authoritative for the brief.
    if ((metadata.kind === 'image' || metadata.kind === 'video') &&
        metadata.promptTemplate &&
        typeof metadata.promptTemplate.prompt === 'string' &&
        metadata.promptTemplate.prompt.trim().length > 0) {
        const tpl = metadata.promptTemplate;
        lines.push('');
        lines.push(`### Reference prompt template — "${tpl.title ?? 'untitled'}"`);
        const meta = [];
        if (tpl.category)
            meta.push(`category: ${tpl.category}`);
        if (tpl.model)
            meta.push(`suggested model: ${tpl.model}`);
        if (tpl.aspect)
            meta.push(`aspect: ${tpl.aspect}`);
        if (Array.isArray(tpl.tags) && tpl.tags.length > 0) {
            meta.push(`tags: ${tpl.tags.join(', ')}`);
        }
        if (meta.length > 0)
            lines.push(meta.join(' · '));
        if (tpl.summary) {
            lines.push('');
            lines.push(tpl.summary);
        }
        lines.push('');
        lines.push('The user picked this template as inspiration. Treat it as a structural and stylistic reference: borrow composition, palette cues, lighting language, lens/motion direction, and the level of detail. Adapt the wording to the user\'s actual subject and brief — do NOT generate the template subject verbatim. If a field above is unknown the user wants you to follow the template\'s defaults.');
        // Escape triple-backticks so a user who pastes ``` into the editable
        // template body can't break out of the markdown fence below and inject
        // free-form instructions into the agent's system prompt.
        const safe = (tpl.prompt ?? '').replace(/```/g, '`\u200b`\u200b`');
        const truncated = safe.length > 4000
            ? `${safe.slice(0, 4000)}\n… (truncated ${safe.length - 4000} chars)`
            : safe;
        lines.push('');
        lines.push('```text');
        lines.push(truncated);
        lines.push('```');
        if (tpl.source) {
            const author = tpl.source.author ? ` by ${tpl.source.author}` : '';
            lines.push('');
            lines.push(`Source: ${tpl.source.repo}${author} — license ${tpl.source.license ?? 'unspecified'}. Preserve attribution if you echo the template language directly.`);
        }
    }
    if (metadata.kind === 'template' && template && template.files.length > 0) {
        lines.push('');
        lines.push(`### Template reference — "${template.name}"${template.description ? ` (${template.description})` : ''}`);
        lines.push('These HTML snapshots are what the user wants to start FROM. Read them as a stylistic + structural reference. You may copy structure, palette, typography, and component patterns; you may adapt them to the new brief; do NOT ship them verbatim. The agent should still produce its own artifact, just one that visibly inherits this template\'s design language.');
        for (const f of template.files) {
            // Cap each file at ~12k chars so a giant template doesn't blow out
            // the system prompt budget. The agent gets enough to read structure.
            const truncated = f.content.length > 12000
                ? `${f.content.slice(0, 12000)}\n<!-- … truncated (${f.content.length - 12000} chars omitted) -->`
                : f.content;
            lines.push('');
            lines.push(`#### \`${f.name}\``);
            lines.push('```html');
            lines.push(truncated);
            lines.push('```');
        }
    }
    return lines.join('\n');
}
function shouldRenderElevenLabsVoiceOptions(metadata, audioVoiceOptions) {
    return metadata.kind === 'audio'
        && metadata.audioKind === 'speech'
        && metadata.audioModel === 'elevenlabs-v3'
        && !metadata.voice
        && Array.isArray(audioVoiceOptions)
        && audioVoiceOptions.length > 0;
}
function renderElevenLabsVoiceQuestionForm(voiceOptions) {
    const options = voiceOptions.slice(0, ELEVENLABS_VOICE_PROMPT_OPTION_LIMIT).map((option) => ({
        label: formatElevenLabsVoiceLabel(option),
        value: option.voiceId,
    }));
    return {
        description: 'Pick a voice by description. The selected answer will be the exact voice_id passed to the renderer.',
        questions: [
            {
                id: 'voice',
                label: 'Voice',
                type: 'select',
                required: true,
                placeholder: 'Choose a voice',
                help: 'Select a voice description; the answer submits the matching Voice ID.',
                options,
            },
        ],
        submitLabel: 'Use voice',
    };
}
function formatElevenLabsVoiceLabel(option) {
    const labels = option.labels && typeof option.labels === 'object'
        ? Object.values(option.labels)
            .map((value) => (typeof value === 'string' ? value.trim() : ''))
            .filter(Boolean)
        : [];
    const bits = [...labels];
    if (bits.length > 0)
        return `${option.name} — ${bits.join(' · ')}`;
    const category = typeof option.category === 'string' ? option.category.trim() : '';
    return category ? `${option.name} — ${category}` : option.name;
}
/**
 * Detect the seed/references pattern shipped by the upgraded
 * web-prototype / mobile-app / simple-deck / guizang-ppt skills, and
 * inject a hard pre-flight rule that lists which side files to Read
 * before doing anything else. The skill body's own workflow already says
 * this — but skills get truncated under context pressure and the agent
 * sometimes skips Step 0. A short up-front directive helps.
 *
 * Returns an empty string when the skill ships no side files (legacy
 * SKILL.md-only skills) so we don't add noise.
 */
function derivePreflight(skillBody) {
    const refs = [];
    if (/assets\/template\.html/.test(skillBody))
        refs.push('`assets/template.html`');
    if (/references\/layouts\.md/.test(skillBody))
        refs.push('`references/layouts.md`');
    if (/references\/themes\.md/.test(skillBody))
        refs.push('`references/themes.md`');
    if (/references\/components\.md/.test(skillBody))
        refs.push('`references/components.md`');
    if (/references\/checklist\.md/.test(skillBody))
        refs.push('`references/checklist.md`');
    // The hyperframes skill ships an html-in-canvas reference next to the
    // VFX catalog blocks. The chat handler at server.ts:4138 routes through
    // this composer (not the contracts copy), so the case must live here
    // too — otherwise live agent runs miss the preflight directive even
    // when the skill body explicitly lists the file.
    if (/references\/html-in-canvas\.md|html-in-canvas\.md/.test(skillBody)) {
        refs.push('`references/html-in-canvas.md`');
    }
    if (refs.length === 0)
        return '';
    return ` **Pre-flight (do this before any other tool):** Read ${refs.join(', ')} via the path written in the skill-root preamble. The seed template defines the class system you'll paste into; the layouts file is the only acceptable source of section/screen/slide skeletons; the checklist is your P0/P1/P2 gate before emitting \`<artifact>\`. Skipping this step is the #1 reason output regresses to generic AI-slop.`;
}
//# sourceMappingURL=system.js.map