forked from nexu-io/open-design
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem.ts
More file actions
593 lines (559 loc) · 27.9 KB
/
Copy pathsystem.ts
File metadata and controls
593 lines (559 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
/**
* 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, type CritiqueConfig } from '@open-design/contracts/critique';
type ProjectMetadata = {
kind?: string;
intent?: string | null;
fidelity?: string | null;
speakerNotes?: boolean | null;
animations?: boolean | null;
templateId?: string | null;
templateLabel?: string | null;
inspirationDesignSystemIds?: string[];
imageModel?: string | null;
imageAspect?: string | null;
imageStyle?: string | null;
videoModel?: string | null;
videoLength?: number | null;
videoAspect?: string | null;
audioKind?: string | null;
audioModel?: string | null;
audioDuration?: number | null;
voice?: string | null;
promptTemplate?: {
id?: string | null;
surface?: 'image' | 'video' | null;
title?: string | null;
prompt?: string | null;
summary?: string | null;
category?: string | null;
tags?: string[] | null;
model?: string | null;
aspect?: string | null;
source?: {
repo?: string | null;
license?: string | null;
author?: string | null;
url?: string | null;
} | null;
} | null;
};
type ProjectTemplate = { name: string; description?: string | null; files: Array<{ name: string; content: string }> };
export const BASE_SYSTEM_PROMPT = OFFICIAL_DESIGNER_PROMPT;
export interface ComposeInput {
agentId?: string | null | undefined;
includeCodexImagegenOverride?: boolean | undefined;
skillBody?: string | undefined;
skillName?: string | undefined;
skillMode?:
| 'prototype'
| 'deck'
| 'template'
| 'design-system'
| 'image'
| 'video'
| 'audio'
| undefined;
designSystemBody?: string | undefined;
designSystemTitle?: string | undefined;
// Craft references the active skill opted into via `od.craft.requires`.
// The daemon resolves the slug list to file contents and concatenates
// them with section headers; we inject them between the DESIGN.md and
// the skill body so brand tokens win on conflict but craft rules
// (letter-spacing, accent caps, anti-slop) cover everything below.
craftBody?: string | undefined;
craftSections?: string[] | undefined;
// Project-level metadata captured by the new-project panel. Drives the
// agent's understanding of artifact kind, fidelity, speaker-notes intent
// and animation intent. Missing fields here are exactly what the
// discovery form should re-ask the user about on turn 1.
metadata?: ProjectMetadata | undefined;
// The template the user picked in the From-template tab, when present.
// Snapshot of HTML files that the agent should treat as a starting
// reference rather than a fixed deliverable.
template?: ProjectTemplate | undefined;
// When present and enabled, the Critique Theater protocol addendum is
// concatenated to the end of the composed prompt. Omitting this field
// (or passing cfg.enabled === false) preserves legacy behavior unchanged.
critique?: CritiqueConfig | undefined;
// Brand name and DESIGN.md body. Required when critique is enabled;
// ignored when critique is disabled or omitted.
critiqueBrand?: { name: string; design_md: string } | undefined;
// Skill identifier. Required when critique is enabled;
// ignored when critique is disabled or omitted.
critiqueSkill?: { id: string } | undefined;
// External MCP servers the daemon already holds a valid OAuth Bearer
// token for at spawn time. We surface the list to the model so it does
// NOT chase Claude Code's synthetic `*_authenticate` /
// `*_complete_authentication` tools that get injected when the HTTP
// transport's first connect transiently flips a server into
// needs-auth state — the Bearer is in `.mcp.json`, the real tools are
// available, and burning a turn on a redundant OAuth dance just
// confuses the user.
connectedExternalMcp?: ReadonlyArray<{ id: string; label?: string | undefined }>
| undefined;
}
export function composeSystemPrompt({
agentId,
includeCodexImagegenOverride = true,
skillBody,
skillName,
skillMode,
designSystemBody,
designSystemTitle,
craftBody,
craftSections,
metadata,
template,
critique,
critiqueBrand,
critiqueSkill,
connectedExternalMcp,
}: ComposeInput): string {
// 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: string[] = [
DISCOVERY_AND_PHILOSOPHY,
'\n\n---\n\n# Identity and workflow charter (background)\n\n',
BASE_SYSTEM_PROMPT,
];
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()}`,
);
}
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);
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);
return parts.join('');
}
// 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:
| ReadonlyArray<{ id: string; label?: string | undefined }>
| undefined,
): string {
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): line is string => 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: ProjectMetadata | undefined,
): string {
const imageModel =
typeof metadata?.imageModel === 'string' ? metadata.imageModel.trim() : '';
return CODEX_IMAGEGEN_MODEL_IDS.has(imageModel) ? imageModel : '';
}
export function shouldRenderCodexImagegenOverride(
agentId: string | null | undefined,
metadata: ProjectMetadata | undefined,
): boolean {
const normalizedAgentId =
typeof agentId === 'string' ? agentId.trim().toLowerCase() : '';
return (
normalizedAgentId === 'codex' &&
metadata?.kind === 'image' &&
resolveCodexImagegenModelId(metadata).length > 0
);
}
export function renderCodexImagegenOverride(
agentId: string | null | undefined,
metadata: ProjectMetadata | undefined,
): string {
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: ProjectMetadata | undefined,
template: ProjectTemplate | undefined,
): string {
if (!metadata) return '';
const lines: string[] = [];
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.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)');
}
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');
}
/**
* 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: string): string {
const refs: string[] = [];
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`');
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.`;
}