@ggui-ai/ui-gen 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/adapters/generation-dispatch.d.ts +10 -0
  2. package/dist/adapters/generation-dispatch.js +172 -1392
  3. package/dist/adapters/generation-dispatch.js.map +1 -1
  4. package/dist/advanced/index.d.ts +1 -1
  5. package/dist/advanced/index.js +191 -1403
  6. package/dist/advanced/index.js.map +1 -1
  7. package/dist/boilerplate.js +3 -2
  8. package/dist/boilerplate.js.map +1 -1
  9. package/dist/compose.js +5 -5
  10. package/dist/compose.js.map +1 -1
  11. package/dist/{create-ui-generator-GX7tvbyH.d.ts → create-ui-generator-B9kV4U9h.d.ts} +13 -0
  12. package/dist/evaluation/axis-checks/index.js +32 -1
  13. package/dist/evaluation/axis-checks/index.js.map +1 -1
  14. package/dist/evaluation/axis-checks/registry.js +32 -1
  15. package/dist/evaluation/axis-checks/registry.js.map +1 -1
  16. package/dist/evaluation/index.js +57 -12
  17. package/dist/evaluation/index.js.map +1 -1
  18. package/dist/fragments/index.js +5 -5
  19. package/dist/fragments/index.js.map +1 -1
  20. package/dist/harness/index.d.ts +4 -125
  21. package/dist/harness/index.js +34 -19
  22. package/dist/harness/index.js.map +1 -1
  23. package/dist/harness/runtime.d.ts +9 -0
  24. package/dist/harness/runtime.js +3 -2
  25. package/dist/harness/runtime.js.map +1 -1
  26. package/dist/harness/types-public.js +8 -7
  27. package/dist/harness/types-public.js.map +1 -1
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.js +191 -1403
  30. package/dist/index.js.map +1 -1
  31. package/dist/llm-router-1TyI0_TV.d.ts +156 -0
  32. package/dist/providers/index.d.ts +35 -93
  33. package/dist/providers/index.js +13 -8
  34. package/dist/providers/index.js.map +1 -1
  35. package/dist/validation/index.js +2 -2
  36. package/dist/validation/index.js.map +1 -1
  37. package/package.json +18 -18
  38. package/src/adapters/generation-dispatch.ts +19 -2
  39. package/src/boilerplate/system-prompt.ts +3 -2
  40. package/src/create-ui-generator.ts +44 -11
  41. package/src/evaluation/axis-checks/checks/state-merge.ts +1 -1
  42. package/src/evaluation/axis-checks/checks/universal.ts +39 -0
  43. package/src/evaluation/llm-evaluator.ts +13 -3
  44. package/src/evaluation/visual-evaluator.ts +5 -1
  45. package/src/fragments/realtime.ts +3 -3
  46. package/src/fragments/state.ts +2 -2
  47. package/src/harness/coding/init-session.ts +4 -1
  48. package/src/harness/coding/run-eval-round.ts +6 -0
  49. package/src/harness/llm-router.ts +59 -14
  50. package/src/harness/runtime.ts +8 -0
  51. package/src/providers/bedrock.ts +84 -22
  52. package/src/validation/ui-compiler.ts +2 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/boilerplate/render.ts","../src/boilerplate/json-schema-ts.ts","../src/boilerplate/generate.ts","../src/evaluation/types-public.ts","../src/internal/extract-call-signatures.ts","../src/boilerplate/system-prompt.ts"],"names":["__dirname"],"mappings":";;;;;;;AAYA,IAAMA,WAAA,GAAY,OAAA,CAAQ,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAC,CAAA;AAiBxD,IAAM,aAAA,GAAgB;AAAA,EACpB,OAAA,CAAQA,aAAW,WAAW,CAAA;AAAA,EAC9B,OAAA,CAAQA,WAAA,EAAW,IAAA,EAAM,KAAA,EAAO,eAAe,WAAW,CAAA;AAAA,EAC1D,QAAQA,WAAA,EAAW,IAAA,EAAM,IAAA,EAAM,KAAA,EAAO,eAAe,WAAW,CAAA;AAAA,EAChE,QAAQA,WAAA,EAAW,IAAA,EAAM,MAAM,IAAA,EAAM,KAAA,EAAO,eAAe,WAAW,CAAA;AAAA,EACtE,OAAA,CAAQA,aAAW,IAAA,EAAM,IAAA,EAAM,MAAM,IAAA,EAAM,KAAA,EAAO,eAAe,WAAW;AAC9E,CAAA;AAEA,IAAI,SAAA,GAA2B,IAAA;AAC/B,IAAM,WAAA,uBAAkB,GAAA,EAAoB;AA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A;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4FAAA,CAAA","file":"boilerplate.js","sourcesContent":["// packages/ui-gen/src/boilerplate/render.ts\n//\n// Loads base.tsx.tmpl + layout files from disk, caches them in memory,\n// and replaces {{MARKER}} placeholders with generated content.\n//\n// Package-private — consumers use `generateBoilerplate()` from\n// `@ggui-ai/ui-gen/boilerplate`; this file is not re-exported.\n\nimport { readFileSync } from 'node:fs';\nimport { resolve, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// `@ggui-ai/ui-gen` ships both `src/` and `dist/` (see package.json `files`).\n// Templates always live at `<pkg-root>/src/boilerplate/templates/` (kept in\n// the published tarball via `files: ['src', 'dist', ...]`). Render.ts gets\n// inlined into multiple dist entrypoints by tsup (`boilerplate.js`,\n// `harness/runtime.js`, `harness/index.js`, …), so `__dirname` varies. We\n// enumerate every reasonable location:\n//\n// - From tsx (`src/boilerplate/render.ts`): `./templates`\n// - Bundled into `dist/boilerplate.js`: `../src/boilerplate/templates`\n// - Bundled into `dist/harness/runtime.js`: `../../src/boilerplate/templates`\n// - Bundled into `dist/harness/coding/X.js`: `../../../src/boilerplate/templates`\n//\n// Step 3 (2026-04-27): the harness cluster ported in from cloud added the\n// `dist/harness/` and `dist/harness/coding/` entrypoints — needed deeper\n// upward walks than the pre-step-3 single-level `dist/`.\nconst TEMPLATE_DIRS = [\n resolve(__dirname, 'templates'),\n resolve(__dirname, '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', '..', '..', 'src', 'boilerplate', 'templates'),\n];\n\nlet baseCache: string | null = null;\nconst layoutCache = new Map<string, string>();\n\nfunction loadBase(): string {\n if (baseCache) return baseCache;\n\n for (const dir of TEMPLATE_DIRS) {\n try {\n baseCache = readFileSync(resolve(dir, 'base.tsx.tmpl'), 'utf-8');\n return baseCache;\n } catch { continue; }\n }\n\n throw new Error('No base.tsx.tmpl found');\n}\n\nfunction loadLayout(shellType: string, screen: string): string {\n const key = `${shellType}-${screen}`;\n if (layoutCache.has(key)) return layoutCache.get(key)!;\n\n // Try exact match, then fallback to universal, then fullscreen-universal\n const candidates = [\n `${shellType}-${screen}.tsx.tmpl`,\n `${shellType}-universal.tsx.tmpl`,\n `fullscreen-universal.tsx.tmpl`, // final fallback\n ];\n\n for (const filename of candidates) {\n for (const dir of TEMPLATE_DIRS) {\n try {\n const content = readFileSync(resolve(dir, 'layouts', filename), 'utf-8');\n layoutCache.set(key, content);\n return content;\n } catch { continue; }\n }\n }\n\n throw new Error(`No layout found for ${key}`);\n}\n\nexport interface BoilerplateMarkers {\n REACT_IMPORT: string;\n ALL_DESIGN: string;\n WIRE_IMPORT: string;\n PROPS_INTERFACE: string;\n ACTION_TYPES: string;\n STREAM_TYPES: string;\n /** `useGguiContext` destructure lines, one per declared `contextSpec`\n * slot. Emitted at the top of the user component body. The runtime\n * owns useState + Provider per slot; the LLM only reads `<slotKey>`\n * and writes via `set<SlotKey>`. Empty when contextSpec is absent or\n * empty. */\n CONTEXT_HOOKS: string;\n WIRE_HOOKS: string;\n AXIS_SECTIONS: string;\n}\n\nexport function renderBoilerplate(\n shellType: string,\n screen: string,\n markers: BoilerplateMarkers,\n): string {\n let template = loadBase();\n const layout = loadLayout(shellType, screen);\n template = template.replace('{{LAYOUT}}', layout);\n\n for (const [key, value] of Object.entries(markers)) {\n template = template.replaceAll(`{{${key}}}`, value);\n }\n\n return template;\n}\n","// packages/ui-gen/src/boilerplate/json-schema-ts.ts\n//\n// JSON Schema → TypeScript type string converter.\n//\n// Pure, self-contained, no env reads, no framework deps. Exposed\n// publicly on `@ggui-ai/ui-gen/boilerplate` because it's the primitive\n// that turns a contract's JSON Schema into the `interface Props { ... }`\n// block the boilerplate generator writes.\n\nimport type { JsonSchema } from '@ggui-ai/protocol';\n\n/**\n * Convert a JsonSchema to a TypeScript type string — recursive.\n *\n * Handles: string, number, integer, boolean, null, array (+ tuples), object,\n * enum, oneOf/anyOf (unions), nullable, const, additionalProperties.\n */\nexport function jsonSchemaTypeToTs(schema: JsonSchema): string {\n // ── Union types (oneOf / anyOf) ──\n const unionMembers = schema.oneOf ?? schema.anyOf;\n if (unionMembers?.length) {\n const types = [...new Set(unionMembers.map(s => jsonSchemaTypeToTs(s)))];\n return types.length === 1 ? types[0] : types.join(' | ');\n }\n\n // ── Const (literal type) ──\n if (schema.const !== undefined) {\n return typeof schema.const === 'string' ? `'${schema.const}'` : String(schema.const);\n }\n\n // ── Enum (union of literals) ──\n if (schema.enum?.length) {\n return schema.enum\n .map(v => typeof v === 'string' ? `'${v}'` : String(v))\n .join(' | ');\n }\n\n let result: string;\n\n switch (schema.type) {\n case 'string':\n result = 'string';\n break;\n case 'number':\n case 'integer':\n result = 'number';\n break;\n case 'boolean':\n result = 'boolean';\n break;\n case 'null':\n return 'null';\n\n case 'array': {\n if (schema.items) {\n const itemType = jsonSchemaTypeToTs(schema.items);\n // Use Array<T> for complex object types, T[] for simple\n result = (schema.items.type === 'object' && schema.items.properties)\n ? `Array<${itemType}>`\n : (itemType.includes('|') ? `(${itemType})[]` : `${itemType}[]`);\n } else {\n result = 'unknown[]';\n }\n break;\n }\n\n case 'object': {\n if (schema.properties) {\n const required = schema.required ?? [];\n const fields = Object.entries(schema.properties)\n .map(([key, prop]) => {\n const opt = !required.includes(key);\n return `${key}${opt ? '?' : ''}: ${jsonSchemaTypeToTs(prop)}`;\n })\n .join('; ');\n result = `{ ${fields} }`;\n } else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {\n result = `Record<string, ${jsonSchemaTypeToTs(schema.additionalProperties)}>`;\n } else {\n result = 'Record<string, unknown>';\n }\n break;\n }\n\n default:\n result = 'unknown';\n }\n\n // Apply nullable (OpenAPI 3.0 shorthand)\n if (schema.nullable && result !== 'unknown') {\n return `${result} | null`;\n }\n\n return result;\n}\n","// packages/ui-gen/src/boilerplate/generate.ts\n//\n// Typed boilerplate generator. Takes a data contract (propsSpec /\n// actionSpec / streamSpec / contextSpec + agentCapabilities.tools +\n// clientCapabilities.gadgets catalogs) and a rendering context\n// (shell + screen) and produces the starting `.tsx` boilerplate the\n// coding agent fills in via apply_changes.\n//\n// `agentCapabilities.tools` entries do NOT emit component hooks. They\n// are catalog declarations the AGENT invokes; component code references\n// them indirectly via `actionSpec.nextStep` (advisory hint surfacing on\n// action events) and `streamSpec.source.tool` (transport-negotiated\n// source).\n//\n// `clientCapabilities.gadgets` entries DO emit component-side gadget\n// plumbing. Gadgets are direct-imported: the generator emits one\n// combined `import { … } from '<package>'` per registered gadget\n// package, above a `// DO NOT EDIT` banner. Hook exports additionally\n// get a pre-emitted `const binding = hook();` call site; component\n// exports are import-only — the LLM renders `<X … />` in the JSX tree\n// itself. The deterministic `gadget_preservation` check rejects the\n// code if a gadget import disappears.\n//\n// Pure function — deterministic, no env reads, no I/O other than\n// `renderBoilerplate` reading the template files.\n\nimport type {\n ActionSpec,\n GadgetDescriptor,\n ContextSpec,\n DataContract,\n JsonObject,\n JsonValue,\n StreamSpec,\n} from \"@ggui-ai/protocol\";\nimport { HOOK_NAME_RE, listContractGadgets } from \"@ggui-ai/protocol\";\nimport { renderBoilerplate } from \"./render.js\";\nimport { jsonSchemaTypeToTs } from \"./json-schema-ts.js\";\n\n/** Shell layout modes supported by the boilerplate templates. */\nexport type ShellType = \"chat\" | \"fullscreen\" | \"spatial\";\n\n/** Target screen size. */\nexport type ScreenSize = \"mobile\" | \"tablet\" | \"desktop\" | \"universal\";\n\n// =============================================================================\n// Design-system surface (pre-imported in every boilerplate)\n// =============================================================================\n\nconst ALL_PRIMITIVES = [\n \"Container\",\n \"Card\",\n \"Stack\",\n \"Row\",\n \"Grid\",\n \"Box\",\n \"Divider\",\n \"Spacer\",\n \"Text\",\n \"Heading\",\n \"Button\",\n \"Input\",\n \"TextArea\",\n \"Select\",\n \"Checkbox\",\n \"Toggle\",\n \"RadioGroup\",\n \"Slider\",\n \"Badge\",\n \"Spinner\",\n \"Skeleton\",\n \"Avatar\",\n \"Alert\",\n \"Progress\",\n \"Image\",\n \"Icon\",\n \"Link\",\n \"Tooltip\",\n \"Table\",\n \"Tabs\",\n \"Toast\",\n \"Accordion\",\n \"MotionKeyframes\",\n \"useMotion\",\n \"useAnimationKey\",\n].join(\", \");\n\nconst ALL_COMPONENTS = [\n \"SearchField\",\n \"FormField\",\n \"MenuItem\",\n \"Tag\",\n \"Dropdown\",\n \"Autocomplete\",\n \"Breadcrumb\",\n \"Pagination\",\n \"EmptyState\",\n \"Stat\",\n \"Stepper\",\n \"Markdown\",\n \"MarkdownInline\",\n].join(\", \");\n\n// Mirrors the actual @ggui-ai/design compositions exports. The 2026-07-29\n// composite-roster wave (#306) deleted the six zero-consumer composites\n// (MakeTabLayout, MarketingHero/CTA/Features, IncidentTimeline,\n// UserProfileCard) from the design package; this list shrank with it.\n// The data-URL shim's allowlist must mirror this list (enforced by\n// verify-shim-allowlists.test.ts).\nconst ALL_COMPOSITIONS = [\n \"Header\",\n \"Sidebar\",\n \"CardGrid\",\n \"CommentThread\",\n \"DataTable\",\n \"ChatWindow\",\n \"NavigationBar\",\n \"FileUploader\",\n \"NotificationCenter\",\n \"Modal\",\n \"CommandPalette\",\n \"Footer\",\n \"Hero\",\n].join(\", \");\n\nconst ALL_INTERACT = [\"Clickable\", \"Hoverable\", \"Pressable\"].join(\", \");\n\n// D1: the whole design system is imported through one specifier\n// (`@ggui-ai/design`), so the boilerplate emits a single import line.\nconst ALL_DESIGN = [\n ALL_PRIMITIVES,\n ALL_COMPONENTS,\n ALL_COMPOSITIONS,\n ALL_INTERACT,\n].join(\", \");\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/** Infer a TypeScript type string from an example value (when no JSON Schema is available). */\nfunction inferTypeFromExample(example: JsonObject): string {\n const fields: string[] = [];\n for (const [k, v] of Object.entries(example)) {\n let t: string;\n if (v === null || v === undefined) t = \"unknown\";\n else if (typeof v === \"string\") t = \"string\";\n else if (typeof v === \"number\") t = \"number\";\n else if (typeof v === \"boolean\") t = \"boolean\";\n else if (Array.isArray(v)) {\n if (v.length === 0) t = \"unknown[]\";\n else if (typeof v[0] === \"string\") t = \"string[]\";\n else if (typeof v[0] === \"number\") t = \"number[]\";\n else if (typeof v[0] === \"object\" && v[0] !== null)\n t = `Array<${inferTypeFromExample(v[0] as JsonObject)}>`;\n else t = \"unknown[]\";\n } else if (typeof v === \"object\") {\n t = inferTypeFromExample(v as JsonObject);\n } else {\n t = \"unknown\";\n }\n fields.push(`${k}: ${t}`);\n }\n return `{ ${fields.join(\"; \")} }`;\n}\n\n// =============================================================================\n// Boilerplate generator\n// =============================================================================\n\nexport function generateBoilerplate(\n _userPrompt: string,\n contract?: DataContract,\n shellType?: ShellType,\n screen?: ScreenSize,\n /** Axis-composed boilerplate sections — fragments produced by `compose()`. */\n composedSections?: string,\n /**\n * Registered gadget catalog. The boilerplate emits a direct\n * `import { … } from '<package>'` per gadget package from the\n * contract's declarations; this catalog supplies the descriptor\n * metadata (`description` / `usage` / `example`) used to prime each\n * pre-emitted gadget call site so the LLM has a working starting\n * point rather than an empty `useFoo()` it might delete.\n */\n appGadgets?: readonly GadgetDescriptor[],\n): string {\n // ── Props interface from data contract (data only — NO action callbacks) ──\n // Contract shape (PropsSpec is ALWAYS the wrapper — never flat):\n // { properties: { fieldName: { schema, required, description } } }\n const propsFields: string[] = [];\n const propsProperties = contract?.propsSpec?.properties ?? {};\n for (const [key, entry] of Object.entries(propsProperties)) {\n const required = entry.required !== false;\n const nullable = entry.schema.nullable === true;\n const tsType = jsonSchemaTypeToTs(entry.schema);\n const fullType = nullable ? `${tsType} | null` : tsType;\n // Build comment: description + default value hint\n const parts: string[] = [];\n if (entry.description) parts.push(entry.description);\n if (entry.default !== undefined) parts.push(`(default: ${JSON.stringify(entry.default)})`);\n const desc = parts.length > 0 ? ` // ${parts.join(' ')}` : \"\";\n propsFields.push(` ${key}${required ? \"\" : \"?\"}: ${fullType};${desc}`);\n }\n\n // ── Actions (useAction hooks — fire-and-forget to agent) ──\n // Contract shape: { actionSpec: { actionName: { label, description, schema?, example?, nextStep? } } }\n // ActionEntry.nextStep: optional hint naming the MCP tool the AGENT\n // should invoke on its next turn after this action fires. Actions have\n // exactly one routing target — the agent; there is NO synchronous\n // server-side dispatch. The name is informational here (use it for\n // button labels, icons, copy).\n const actionTypeAliases: string[] = [];\n const actionHookCalls: string[] = [];\n const actionReturnFields: string[] = [];\n const actionsMap: ActionSpec = contract?.actionSpec ?? {};\n for (const [key, entry] of Object.entries(actionsMap)) {\n const label = entry.label ?? key;\n const desc = entry.description ?? \"\";\n const tool = entry.nextStep ?? \"\";\n const typeName = `Action${key.charAt(0).toUpperCase()}${key.slice(1)}Payload`;\n\n // Derive TypeScript type: schema > example > void (fire-and-forget)\n let tsType = \"void\";\n if (entry.schema) {\n tsType = jsonSchemaTypeToTs(entry.schema);\n } else if (entry.example && typeof entry.example === \"object\" && !Array.isArray(entry.example)) {\n tsType = inferTypeFromExample(entry.example as JsonObject);\n }\n\n const toolNote = tool ? ` (label \"${label}\", nextStep hint → ${tool})` : \"\";\n actionTypeAliases.push(\n `/** Action payload: ${desc || label}${toolNote} */\\ntype ${typeName} = ${tsType};`\n );\n // Inline signature tells the LLM exactly how to call this action\n const callSig = tsType === \"void\" ? \"() => void — fire and forget\" : `(data: ${tsType}) => void`;\n const toolHint = tool ? ` → nextStep: ${tool}` : \"\";\n actionHookCalls.push(` const ${key} = useAction<${typeName}>('${key}'); // ${callSig}${toolHint}`);\n actionReturnFields.push(key);\n }\n\n // ── Stream channels (useStream hooks — real-time from agent) ──\n // Stream spec: flat map { channelName: { schema, description, example } }\n const streamChannels: StreamSpec = contract?.streamSpec ?? {};\n const streamChannelEntries = Object.entries(streamChannels);\n\n const streamTypeAliases: string[] = [];\n const streamHookCalls: string[] = [];\n const streamReturnFields: string[] = [];\n for (const [channelName, entry] of streamChannelEntries) {\n const desc = entry.description ?? \"\";\n const typeName = `Stream${channelName.charAt(0).toUpperCase()}${channelName.slice(1)}`;\n const tsType = entry.schema\n ? jsonSchemaTypeToTs(entry.schema)\n : \"unknown\";\n streamTypeAliases.push(`/** Stream channel: ${desc} */\\ntype ${typeName} = ${tsType};`);\n // Show .latest/.all types so the LLM knows how to access stream data\n streamHookCalls.push(\n ` const ${channelName} = useStream<${typeName}>('${channelName}'); // .latest: ${typeName} | null, .all: ${typeName}[]`\n );\n streamReturnFields.push(channelName);\n }\n\n // ── agentCapabilities.tools catalog (NO component-side hook emission) ──\n // `agentCapabilities.tools[*]` declares tools the AGENT invokes —\n // referenced from the contract via `actionSpec[*].nextStep` (advisory\n // hint forwarded on action events) and `streamSpec[*].source.tool`\n // (channel data source). The component never calls these tools\n // directly; there is no `useWiredTool(name)` hook. The boilerplate\n // therefore emits no per-tool hook line, no request/response type\n // aliases, and no useWiredTool import.\n\n // ── Client capabilities (browser-capability gadget hooks declared in contract) ──\n // Contract shape: { gadgets: { '<package>': { '<exportName>': { description?, usage? } } } }\n // package-keyed two-level map. `listContractGadgets` flattens it to\n // `GadgetUse[]` — one record per used export with `package`, `name`,\n // and optional `description` / `usage` overrides. The export NAME\n // grammar discriminates kind (`use`-prefixed → hook, PascalCase →\n // component).\n // No type aliases — gadget hooks own their typed return shape.\n // No wire-import side effect — gadgets are imported from `package`\n // (default `@ggui-ai/gadgets`), not from `@ggui-ai/wire`.\n //\n // Group-by-package — emit ONE combined `import { hookA, hookB } from '<pkg>'`\n // per declared package, NOT one import per hook. Hooks ordered\n // alphabetically within each package for stable diffs across same-\n // contract regens.\n const gadgetUses = contract ? listContractGadgets(contract) : [];\n\n // Gadgets are DIRECT-imported from their package, grouped\n // per package below. Build a hook-name → registry export lookup so\n // each contract-declared gadget binding can be enriched with the\n // catalog's description / usage / example fields. Mirrors how wire\n // boilerplate emits typed action signatures + nextStep hints —\n // gadgets get the same priming so the LLM has a working call site to\n // start from rather than an empty `useFoo()` it might delete.\n //\n // Each `GadgetDescriptor` is a PACKAGE with `exports[]`;\n // flatten to the hook exports, keyed by hook name.\n const gadgetCatalog = new Map<\n string,\n {\n readonly description?: string;\n readonly usage?: string;\n readonly example?: JsonValue;\n }\n >();\n for (const descriptor of appGadgets ?? []) {\n for (const exp of descriptor.exports) {\n // `GadgetExport` is a type-exclusive union (`hook?: never` on the\n // component member); discriminate by VALUE presence — `\"hook\" in\n // exp` no longer narrows now that `hook` is an optional key of\n // both members.\n if (exp.hook === undefined) continue;\n gadgetCatalog.set(exp.hook, {\n description: exp.description,\n usage: exp.usage,\n example: exp.example,\n });\n }\n }\n // Gadget imports grouped by package: `package → set of export names`\n // (hook AND component exports). One combined\n // `import { … } from '<pkg>'` is emitted per package.\n const gadgetImportsByPackage = new Map<string, Set<string>>();\n const gadgetHookCalls: string[] = [];\n for (const use of gadgetUses) {\n const exportName = use.name;\n // Both hooks and components are DIRECT-imported from their\n // package — add every contract-declared export to the per-package\n // import group.\n const pkgExports = gadgetImportsByPackage.get(use.package);\n if (pkgExports !== undefined) pkgExports.add(exportName);\n else gadgetImportsByPackage.set(use.package, new Set([exportName]));\n\n // Kind discrimination is by the export-name grammar.\n // A component name (PascalCase) is import-only — the LLM renders\n // `<X … />` in the JSX tree itself, so there is no pre-emitted call\n // site. Hook names (`use`-prefixed) additionally get a pre-emitted\n // call line below so the LLM has a working invocation.\n if (!HOOK_NAME_RE.test(exportName)) continue;\n const hook = exportName;\n // Contract entry's local override wins; registry catalog is the\n // fallback (most plugin descriptors live on the registry side).\n // The wire `GadgetUse` carries only `description` / `usage`\n // overrides — `example` lives solely on the registered export.\n const contractDesc = use.description;\n const contractUsage = use.usage;\n const catalog = gadgetCatalog.get(hook) ?? {};\n const desc = contractDesc ?? catalog.description ?? hook;\n const usage = contractUsage ?? catalog.usage;\n const example = catalog.example;\n\n // Pre-emit the hook call so the LLM sees a working invocation\n // (and doesn't delete it as \"unused\"). Mirrors wire's typed-\n // signature pattern. Two example shapes in the wild:\n // (a) plain literal — `{ center: [0,0], zoom: 12 }` — the\n // descriptor IS the call args; inline as the call arg.\n // (b) shaped object — `{ call: '<full TS expression>',\n // returns: <typed return shape> }` — the canonical\n // sample/leaflet descriptor shape; emit the `call` as a\n // separate EXAMPLE comment so the LLM sees the literal TS\n // it should produce.\n let callArgs = '';\n let exampleComment = '';\n if (example !== undefined && example !== null) {\n const callLine =\n typeof example === 'object' &&\n !Array.isArray(example) &&\n typeof example.call === 'string'\n ? example.call\n : undefined;\n if (callLine !== undefined) {\n exampleComment = `\\n // EXAMPLE: ${callLine.trim()}`;\n } else {\n callArgs = JSON.stringify(example);\n }\n }\n const usageNote = usage ? ` USE: ${usage}` : '';\n // Local binding name: strip the `use` prefix + lowercase the first\n // char so `useGeolocation` → `geolocation`. The wire no longer\n // carries an explicit binding name (the export name IS the inner\n // key), so the boilerplate derives a stable, readable one.\n const bindingName =\n hook.length > 3\n ? hook.charAt(3).toLowerCase() + hook.slice(4)\n : hook;\n gadgetHookCalls.push(\n ` const ${bindingName} = ${hook}(${callArgs}); // ${desc}${usageNote}${exampleComment}`,\n );\n }\n // Gadgets are DIRECT-imported, one combined\n // `import { hookA, hookB } from '<pkg>'` per registered package\n // (packages + hooks sorted for stable diffs across same-contract\n // regens). The `DO NOT EDIT` banner + tier-0 `gadget_preservation`\n // keep the LLM from deleting an import it (correctly) intuits is\n // runtime-resolved — the banner alone makes direct imports survive\n // multi-turn generation. Tier-0 verifies each registered hook is\n // still imported from its package.\n const gadgetImportLine =\n gadgetImportsByPackage.size > 0\n ? \"// DO NOT EDIT — gadget imports. Each export is resolved by the iframe \" +\n \"runtime; keep every import line and export name. self_check fails with \" +\n \"gadget_preservation:<export> if a gadget import is removed.\\n\" +\n Array.from(gadgetImportsByPackage.entries())\n .sort(([a], [b]) => a.localeCompare(b))\n .map(\n ([pkg, hooks]) =>\n `import { ${Array.from(hooks).sort().join(\", \")} } from '${pkg}';`,\n )\n .join(\"\\n\")\n : \"\";\n // ── Props interface (data only — no action callbacks) ──\n const propsInterface =\n propsFields.length > 0\n ? `// DO NOT EDIT — generated from data contract. Changing this will fail validation.\\ninterface Props {\\n${propsFields.join(\"\\n\")}\\n}`\n : `// DO NOT EDIT — generated from data contract.\\ninterface Props {\\n [key: string]: string | number | boolean | null | object;\\n}`;\n\n // ── Context slots — `useGguiContext` hook ──\n // For each declared `contextSpec` slot, emit ONE destructure line\n // at the top of the user component:\n // const [<slotKey>, set<PascalSlotKey>] =\n // useGguiContext<TS>('<slotKey>');\n // The runtime owns useState per slot and wraps the user component\n // in nested SingleSlotProvider components — the user only reads\n // the live tuple via the hook. There must be NO `useState` and NO\n // `<Provider>` wrap anywhere in the LLM-authored JSX.\n const contextSpec: ContextSpec = contract?.contextSpec ?? {};\n const contextSpecEntries = Object.entries(contextSpec);\n let contextHooks = \"\";\n if (contextSpecEntries.length > 0) {\n const hookLines: string[] = [];\n for (const [slotKey, entry] of contextSpecEntries) {\n const valueType = entry.schema\n ? jsonSchemaTypeToTs(entry.schema)\n : \"unknown\";\n const setterName = `set${slotKey.charAt(0).toUpperCase()}${slotKey.slice(1)}`;\n hookLines.push(\n ` const [${slotKey}, ${setterName}] = useGguiContext<${valueType}>('${slotKey}');`,\n );\n }\n contextHooks =\n ` // DO NOT EDIT — auto-generated per contextSpec slot.\\n` +\n ` // Read \\`<slotKey>\\` to render, write via \\`set<SlotKey>\\` to\\n` +\n ` // surface the change to the agent's LLM context (debounced).\\n` +\n ` // The runtime owns the underlying useState + Provider; you\\n` +\n ` // write plain JSX, no wrap.\\n` +\n `${hookLines.join(\"\\n\")}\\n`;\n }\n\n // ── Determine which wire hooks are needed ──\n const hasActions = actionHookCalls.length > 0;\n const hasStream = streamHookCalls.length > 0;\n // Gates the gadget hook-CALL body section. A component gadget\n // contributes an import but no call site, so this is false for a\n // component-only contract — the import line is gated separately on\n // `gadgetImportLine` below.\n const hasGadgetHookCalls = gadgetHookCalls.length > 0;\n const hasContext = contextSpecEntries.length > 0;\n // `hasAnyHook` gates the \"DO NOT EDIT wire hooks\" header + body.\n // Client gadget HOOKS contribute call sites alongside the\n // @ggui-ai/wire hooks — their declaration needs the same emitted\n // header so the LLM sees the binding lines pre-declared and doesn't\n // strip / duplicate them. (Component gadgets add no body line.)\n const hasAnyHook =\n hasActions || hasStream || hasContext || hasGadgetHookCalls;\n const hasAnyWireFromWire = hasActions || hasStream || hasContext;\n\n const wireHooks: string[] = [];\n if (hasActions) wireHooks.push(\"useAction\");\n if (hasStream) wireHooks.push(\"useStream\");\n if (hasContext) wireHooks.push(\"useGguiContext\");\n const wireImport = hasAnyWireFromWire\n ? `import { ${wireHooks.join(\", \")} } from '@ggui-ai/wire';\\n`\n : \"\";\n // The gadget import line is emitted whenever ANY gadget export is\n // declared — hook OR component. (`gadgetImportLine` is non-empty iff\n // `gadgetImportsByPackage` has an entry; component-only contracts\n // have an import but no `hasGadgetHookCalls`.)\n const gadgetImport =\n gadgetImportLine.length > 0 ? `${gadgetImportLine}\\n` : \"\";\n\n // ── React import — only include hooks that are actually needed ──\n const reactHooks = [\"useState\", \"useCallback\", \"useMemo\", \"useEffect\", \"useRef\"];\n const reactImport = `import React, { ${reactHooks.join(\", \")} } from 'react';`;\n\n // ── Hook body ──────────────────────────────────────────\n // Wire hooks are placed inside render(), before the return statement.\n const hookParts: string[] = [];\n if (hasActions) {\n hookParts.push(\" // ── Actions (contract-typed, fire-and-forget to agent) ──\");\n hookParts.push(\" // Call these to send user interactions to the agent. Types are enforced by the compiler.\");\n hookParts.push(...actionHookCalls);\n }\n if (hasStream) {\n hookParts.push(\"\");\n hookParts.push(\" // ── Streams (contract-typed, real-time from agent) ──\");\n hookParts.push(\" // .latest is the most recent event (or null). .all is the full history array.\");\n hookParts.push(...streamHookCalls);\n }\n if (hasGadgetHookCalls) {\n hookParts.push(\"\");\n hookParts.push(\" // ── Gadgets (browser-capability hooks; UI-owned lifecycle) ──\");\n hookParts.push(\" // Read .value / .status; call .start() to invoke. Surface .value through\");\n hookParts.push(\" // an actionSpec payload or contextSpec slot if the agent needs to observe it.\");\n hookParts.push(...gadgetHookCalls);\n }\n\n // Only emit the \"DO NOT EDIT wire hooks\" header when there ARE wire-side\n // OR gadget-side hook bindings to surface. An orphaned header on\n // no-wire fixtures (e.g. weather-card) makes the LLM hallucinate\n // hooks for an empty section and burn turns on missing imports.\n const hookBody = hasAnyHook\n ? ` // DO NOT EDIT wire hooks — auto-generated from the data contract\\n${hookParts.join(\"\\n\")}\\n`\n : \"\";\n\n // ── Type alias blocks ───────────────────────────────────\n // Auto-generated type aliases serve as documentation for the LLM. Some are\n // referenced by the wire-hook calls below (e.g. `useAction<ActionXPayload>`)\n // but request types are typically only mentioned in trailing comments —\n // ESLint flags them as unused. Without `eslint-disable` here, the LLM\n // enters a fix-rename oscillation loop (prefix `_`, break prop access,\n // revert, retry…) that drives up to 27% of cap-hit selfCheckFails on\n // wire-bearing fixtures. Suppress no-unused-vars for the generated\n // type-alias block; \"DO NOT EDIT\" comments + tier-0 wire-preservation\n // already prevent the LLM from removing them.\n const wrapTypes = (label: string, body: string): string =>\n `\\n/* eslint-disable no-unused-vars */\\n// DO NOT EDIT — ${label}\\n${body}\\n/* eslint-enable no-unused-vars */\\n`;\n\n const actionTypesBlock =\n actionTypeAliases.length > 0\n ? wrapTypes(\"action payload types generated from action contract.\", actionTypeAliases.join(\"\\n\\n\"))\n : \"\";\n const streamTypesBlock =\n streamTypeAliases.length > 0\n ? wrapTypes(\"stream event types generated from stream contract.\", streamTypeAliases.join(\"\\n\\n\"))\n : \"\";\n // `clientCapabilities.gadgets` ship NO type-alias block — gadget\n // hooks own their typed return shape internally; the contract surface\n // is pure declaration.\n\n return renderBoilerplate(shellType ?? \"fullscreen\", screen ?? \"universal\", {\n REACT_IMPORT: reactImport,\n ALL_DESIGN,\n WIRE_IMPORT: wireImport + gadgetImport,\n PROPS_INTERFACE: propsInterface,\n ACTION_TYPES: actionTypesBlock,\n STREAM_TYPES: streamTypesBlock,\n CONTEXT_HOOKS: contextHooks,\n WIRE_HOOKS: hookBody,\n AXIS_SECTIONS: composedSections ?? \"\",\n });\n}\n","// Evaluation type vocabulary shared between the harness runtime and its\n// check/evaluator surfaces. This is the narrow contract layer — the\n// type language every harness leg is written against:\n//\n// - `EvalIssue` — the single issue shape everything produces.\n// - `EvalTier` / `EvalOutcome` / `EvalCategory` — the issue's axes.\n// - `Priority` — P0/P1/P2 ranking referenced by the retry formatter.\n// - `EvalResult` — aggregate shape a runner returns.\n// - `QualityMode` / `QualityConfig` / `DEFAULT_QUALITY_CONFIG` —\n// the quality-mode knob the adapter surface consumes.\n// - `priorityForIssue` / `isBlocked` / `getActionableIssues` — the\n// purely-typed helpers over the vocabulary.\n//\n// `EvalIssue` is referenced by `PatchFn`, `TierCheck`, `LLMEvaluator`,\n// and `RuntimeRenderCheck` in the harness types hub.\n\n// ─── Priority ──────────────────────────────────────────────────────────────\n// P0 = must (compile + complete), P1 = should (safety), P2 = nice (quality).\n// Single source of truth for the retry-formatter ranking.\n\nexport type Priority = \"P0\" | \"P1\" | \"P2\";\n\n// ─── Issue shape ───────────────────────────────────────────────────────────\n\nexport type EvalTier = 0 | 1 | 2;\nexport type EvalOutcome = \"fail\" | \"warn\" | \"pass\";\n\nexport type EvalCategory =\n | \"compile\"\n | \"security\"\n | \"contract\"\n | \"types\"\n | \"imports\"\n | \"tokens\" // tier 0\n | \"mode\" // tier 0 — per-mode deterministic\n | \"functionality\"\n | \"crash\" // tier 1\n | \"interactivity\"\n | \"accessibility\"\n | \"layout\"\n | \"loading\"\n | \"visual\"; // tier 2\n\nexport interface EvalIssue {\n tier: EvalTier;\n result: EvalOutcome;\n category: EvalCategory;\n /**\n * Priority tier — threaded through to the retry formatter so the LLM can\n * rank its next patch against the prompt's P0/P1/P2 priority schema.\n * Derived from (category, result) via {@link priorityForIssue} when not\n * explicitly set. Optional on construction; check-runners typically\n * populate it before returning.\n */\n priority?: Priority;\n subcategory?: string;\n severity?: \"critical\" | \"major\";\n description: string;\n fix: string;\n line?: number;\n}\n\n/**\n * Runtime-render probe execution status — three-valued so \"the probe\n * never ran\" is never conflated with \"the probe ran clean\".\n *\n * - `ran` — probe executed; its findings (possibly none) are\n * in the issue stream under `runtime:*` subcategories.\n * - `infra-skipped` — probe could NOT execute (environment failure:\n * happy-dom load, user-event document capture,\n * ESM/CJS interop). Carries ZERO probe evidence;\n * consumers MUST NOT count it as a pass.\n * - `not-applicable`— nothing to probe (no compiled code, no contract\n * surface, or no runtimeRender check configured).\n */\nexport type RuntimeProbeStatus = \"ran\" | \"infra-skipped\" | \"not-applicable\";\n\n/**\n * Probe execution meta stamped onto an `EvalResult` at the exit-decision\n * points that invoke the probe. Absence of this field means the eval\n * path never reached a probe invocation at all — consumers treat that\n * the same as not-run, never as a pass.\n */\nexport interface RuntimeProbeMeta {\n readonly status: RuntimeProbeStatus;\n /** Populated for `infra-skipped` / `not-applicable` — why the probe didn't run. */\n readonly reason?: string;\n}\n\nexport interface EvalResult {\n issues: EvalIssue[];\n pass: string[];\n /**\n * Runtime-render probe execution meta. Stamped by the exit-decision\n * probe runner; absent on eval paths that never invoke the probe.\n */\n runtimeProbe?: RuntimeProbeMeta;\n}\n\n// ─── Quality mode ──────────────────────────────────────────────────────────\n\nexport type QualityMode = \"fast\" | \"auto-improve\" | \"high-quality\";\n\nexport interface QualityConfig {\n quality: QualityMode;\n visualEval: boolean;\n maxCostPerGeneration: number;\n model?: { provider?: string; model?: string };\n}\n\nexport const DEFAULT_QUALITY_CONFIG: QualityConfig = {\n quality: \"fast\",\n visualEval: false,\n maxCostPerGeneration: 3,\n};\n\n// ─── Axis-check types ──────────────────────────────────────────────────────\n// The `AxisCheck` type vocabulary lives here. The check bodies\n// themselves (REGISTRY, per-axis implementations) live under\n// `./axis-checks/`.\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { AxisVector, Classification } from \"../classifier/axes.js\";\nimport type { AxisKey } from \"../fragments/index.js\";\n\nexport interface AxisCheckInput {\n sourceCode: string;\n compiledCode: string | null;\n contract?: DataContract;\n originalPrompt: string;\n /** Full classification — checks may read sibling axes. */\n classification: Classification;\n}\n\n/**\n * A gated check. Runs only when the classification's axis value matches\n * one of the gate's accepted values. Multiple gates (implicit AND) support\n * cross-axis combinations.\n */\nexport interface AxisCheck {\n /** Stable id used in issue subcategories. */\n id: string;\n /** Primary axis this check gates on. */\n axis: AxisKey;\n /** Which values of that axis activate the check. */\n values: readonly string[];\n /** Optional extra gate on a sibling axis (e.g., only when state=merge AND writes=per-item). */\n and?: { axis: AxisKey; values: readonly string[] };\n /** Execute the check and emit zero or more issues. */\n run(input: AxisCheckInput): EvalIssue[];\n}\n\n/**\n * Whether a check's gate(s) match the given axis vector. Pure function,\n * no issue emission.\n */\nexport function matches(vector: AxisVector, check: AxisCheck): boolean {\n const primary = vector[check.axis] as string;\n if (!check.values.includes(primary)) return false;\n if (check.and) {\n const sibling = vector[check.and.axis] as string;\n if (!check.and.values.includes(sibling)) return false;\n }\n return true;\n}\n\n// ─── Purely-typed helpers ──────────────────────────────────────────────────\n\n/**\n * Map a tier-0 issue category to the canonical P0/P1/P2 priority.\n *\n * Sourced from the criteria priority assignments:\n * - P0 (must): compile, security, imports, contract, types, mode\n * - P1 (safety): tokens, crash, functionality\n * - P2 (quality): interactivity, accessibility, layout, loading, visual\n */\nexport function priorityForIssue(category: EvalCategory): Priority {\n if (\n category === \"interactivity\" ||\n category === \"accessibility\" ||\n category === \"layout\" ||\n category === \"loading\" ||\n category === \"visual\"\n ) {\n return \"P2\";\n }\n if (category === \"tokens\" || category === \"crash\" || category === \"functionality\") {\n return \"P1\";\n }\n // compile, security, imports, contract, types, mode → P0.\n return \"P0\";\n}\n\n/** Whether any issue blocks shipping (has result = 'fail'). */\nexport function isBlocked(result: EvalResult): boolean {\n return result.issues.some((i) => i.result === \"fail\");\n}\n\n/**\n * Return the issues the agent should act on, depending on quality mode.\n * - fast: only fails (blocking issues)\n * - auto-improve / high-quality: fails + warns\n */\nexport function getActionableIssues(result: EvalResult, mode: QualityMode): EvalIssue[] {\n if (mode === \"fast\") {\n return result.issues.filter((i) => i.result === \"fail\");\n }\n return result.issues.filter((i) => i.result === \"fail\" || i.result === \"warn\");\n}\n\n// ─── Criteria (single source of truth for coding + eval sides) ─────────────\n//\n// Each criterion is defined ONCE with both sides of the contract:\n// - codingGuidance: what the coding agent should DO\n// - evalInstruction: what the eval agent should CHECK\n// They must be compatible — changing one means reviewing the other.\n//\n// This is *validated* shipping content: it's what the hosted runtime sends\n// to every generation today. External OSS implementers building their own\n// prompts should be able to use the same rubric — hence it's open.\n\nexport interface EvalCriterion {\n /** Unique identifier matching the eval tool name (e.g., 'functionality') */\n id: string;\n /** Human-readable name shown to both agents */\n name: string;\n /** Priority tier — P0 must, P1 should, P2 nice */\n priority: Priority;\n /** What the coding agent should DO to satisfy this criterion */\n codingGuidance: string;\n /** What the eval agent should CHECK — the evaluation prompt */\n evalInstruction: string;\n /** Tier 0 = programmatic, Tier 1 = LLM critical, Tier 2 = LLM quality */\n tier: 0 | 1 | 2;\n /** Eval outcome when this criterion fails */\n failOutcome: \"fail\" | \"warn\";\n}\n\nexport const CRITERIA: readonly EvalCriterion[] = [\n // ── P0: Correctness (must satisfy — failure = broken component) ──\n\n {\n id: \"compile\",\n name: \"Compile & type-check\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance:\n \"Code must compile. The typed Props and wire hook generics are enforced by the compiler.\",\n evalInstruction: \"Checked automatically by esbuild + TypeScript. No LLM evaluation needed.\",\n },\n {\n id: \"render-props\",\n name: \"Render all Props fields\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance: \"Render every Props field in JSX. Access via props.fieldName.\",\n evalInstruction:\n \"Check that every field from interface Props appears as props.fieldName in the function body.\",\n },\n {\n id: \"wire-hooks\",\n name: \"Wire all contract hooks\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Wire every useAction/useStream and every clientCapabilities.gadgets hook (e.g., useGeolocation) to a UI element. `agentCapabilities.tools` is a catalog the AGENT invokes — NOT a component hook surface.\",\n evalInstruction:\n \"Check that every hook variable from the boilerplate appears in the JSX or an effect.\",\n },\n {\n id: \"imports\",\n name: \"Valid imports only\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Only import from react, @ggui-ai/design/*, and @ggui-ai/wire.\",\n evalInstruction: \"Flag any import from a package not in the allowlist.\",\n },\n {\n id: \"security\",\n name: \"No eval/fetch/window\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Never use eval(), fetch(), or window. Data comes from props and hooks.\",\n evalInstruction: \"Flag any call to eval(), fetch(), or window access.\",\n },\n\n // ── P1: Safety (should satisfy — failure = crash or bad UX) ──\n\n {\n id: \"functionality\",\n name: \"All features implemented\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance: \"Implement ALL features from the request AND the data contract.\",\n evalInstruction: `Evaluate FUNCTIONALITY: Does this component implement ALL features from the request AND the data contract?\n\nCheck against BOTH sources:\n1. Original request — each feature must be coded AND rendered in JSX\n2. Data contract (if present) — verify:\n - Props fields are rendered in the UI. EXCEPTION: pure identifier fields (\\`id\\`, \\`*Id\\`, keys) that exist only to be echoed back inside an action payload do NOT need to be visibly rendered.\n - ALL useAction hooks are wired to clickable UI elements\n - ALL useStream hooks are consumed — the streamed data must reach the UI. Merging stream events into rendered state (a list, a counter, the displayed records) COUNTS as consuming the stream; it need not be a literal \\`.latest\\` render.\n - ALL clientCapabilities gadgets are used. \\`clientCapabilities.gadgets\\` is keyed by npm package: built-in browser capabilities (useGeolocation / useCamera / …) import from @ggui-ai/gadgets; registered third-party gadgets (e.g. useChartTheme) import from their OWN package. Any gadget the contract declares IS a contract feature — NEVER flag it as \"not part of the contract\".\n - \\`agentCapabilities.tools\\` is a catalog declaration only; do NOT flag missing component-side calls for it\n\nA contract hook that is declared but never used at all is a MISSING feature.\n\nCRITICAL: The \"issues\" array must ONLY contain features you are CERTAIN are missing or broken — never an implemented feature. (See \"Issue-array discipline\" above: no speculative, self-negating, or \"verify that…\" entries.)`,\n },\n {\n id: \"crash\",\n name: \"No crash scenarios\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance:\n \"Guard optional props (props.field?.x). stream.latest is T|null — always null-guard. .all is always an array.\",\n evalInstruction: `Evaluate CRASH SAFETY: Are there ACTUAL runtime crash scenarios?\n\nWILL crash (include in issues):\n- .map()/.filter()/.length on an uninitialized variable\n- Accessing property of undefined without guard\n- useStream().latest.field WITHOUT null guard — .latest is T | null\n- Optional Props field accessed as props.field.x without guard\n- Array item optional field: items.map(item => item.priority.toUpperCase()) when priority is optional\n\nSAFE (do NOT include):\n- Optional chaining: props.items?.map() — SAFE\n- Fallback: items || [] — SAFE\n- useState initializer: useState([]) — SAFE\n- Null check: items && items.map() — SAFE\n- stream.latest && stream.latest.field — SAFE, guarded\n- stream.all.map(...) — SAFE, .all is always an array\n- stream.all.length — SAFE, always a number\n\nThe \"issues\" array is ONLY for a specific line that WILL throw at runtime. NEVER put a line you have determined is safe into the issues array — not even to note that it is safe (\"…so this is safely guarded\", \"…so there is no crash\"). If you cannot name a concrete line that will throw, the answer is {\"pass\": true} — return that and an empty issues array.`,\n },\n {\n id: \"tokens\",\n name: \"Design system tokens\",\n priority: \"P1\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Use CSS variables for colors (var(--ggui-color-*)); use the spacing scale for gap/padding/margin (gap=\\\"md\\\", padding=\\\"lg\\\").\",\n evalInstruction:\n \"Flag hardcoded hex colors, rgba/hsl functions, and numeric or raw-CSS-length spacing props. A t-shirt-scale spacing name (gap=\\\"md\\\") IS a token — never flag it.\",\n },\n\n // ── P2: Quality (nice to have — failure = lower score, not broken) ──\n\n {\n id: \"interactivity\",\n name: \"Sufficient interactive elements\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Add appropriate interactive elements for the component purpose.\",\n evalInstruction: `Evaluate INTERACTIVITY: Does this component have sufficient interactive elements?\n\nConsider: forms need submit buttons, lists need selection, editable content needs save/cancel.\nContract actions (if present): every useAction hook should be triggered by a visible UI element.\n\nOnly list MISSING interactive elements. Use 'fail' only for issues blocking core purpose.`,\n },\n {\n id: \"accessibility\",\n name: \"Accessible markup\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance:\n \"Add labels on form inputs, alt text on images, semantic HTML, and state ARIA (aria-checked/pressed/selected/expanded) on hand-rolled interactive controls.\",\n evalInstruction: `Evaluate ACCESSIBILITY: missing labels, alt text, semantic HTML, keyboard support, ARIA state.\n\nggui primitives bake in their own ARIA — see \"Primitive Accessibility\" in the Design System context above. NEVER flag a ggui primitive (Input/Select/TextArea, RadioGroup, Checkbox, Toggle, Progress, Slider, Spinner, Skeleton, Tabs, Accordion, Alert, Toast, Tooltip, Clickable, Icon) for a missing role / aria-* / label / keyboard handler — it is already there and not visible in the source you are reading.\n\nFlag ONLY real gaps: a raw div/span used as an interactive control; a hand-rolled control whose checked/selected/expanded/pressed state is conveyed only by styling (strikethrough, color, a check icon) with no \\`aria-checked\\` / \\`aria-pressed\\` / \\`aria-selected\\` / \\`aria-expanded\\`; an image with no alt text; an Input/Select/TextArea with no \\`label\\` prop; an icon-only Button with no aria-label; live/streaming data not wrapped in an aria-live region; inverted heading hierarchy.\n\nOnly list MISSING accessibility features. Use 'fail' only if it blocks delivery.`,\n },\n {\n id: \"layout\",\n name: \"Clean layout\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use proper spacing and visual grouping.\",\n evalInstruction: `Evaluate LAYOUT: Check spacing, alignment, visual grouping, and composition.\n\nOnly list ACTUAL layout problems. Use 'fail' only for fundamentally broken layouts.`,\n },\n {\n id: \"loading\",\n name: \"Loading/empty/error states\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Handle async data, empty collections, and error cases.\",\n evalInstruction: `Evaluate LOADING/EMPTY/ERROR STATES: Does the component handle async data and edge cases?\n\nContract-specific: useStream should handle pre-data state. clientCapabilities hooks may return undefined / permission-denied — defensive guards expected before threading values into JSX.\nProps-only components (no async, no streams, no client capabilities) do NOT need loading states — return pass.\n\nOnly list MISSING states.`,\n },\n {\n id: \"visual\",\n name: \"Design system consistency\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use design system tokens consistently.\",\n evalInstruction: `Evaluate VISUAL CONSISTENCY: Is the component using the design system correctly?\n\nFlag: hardcoded colors instead of CSS variables, numeric or raw-CSS-length spacing instead of the t-shirt scale, style objects bypassing design system.\nA t-shirt-scale spacing name (gap=\"md\", padding=\"lg\") IS correct token usage — never flag it.\nIntentional custom colors (status indicators) are acceptable when no semantic token fits.\n\nOnly list ACTUAL violations. Use 'fail' only for pervasive violations.`,\n },\n] as const;\n\n/** Get all criteria for a specific priority level */\nexport function getCriteriaByPriority(priority: Priority): EvalCriterion[] {\n return CRITERIA.filter((c) => c.priority === priority);\n}\n\n/** Get a specific criterion by ID */\nexport function getCriterionById(id: string): EvalCriterion | undefined {\n return CRITERIA.find((c) => c.id === id);\n}\n\n/** Get all LLM-evaluated criteria (tier 1 + 2) */\nexport function getLLMCriteria(): EvalCriterion[] {\n return CRITERIA.filter((c) => c.tier > 0);\n}\n\n/**\n * Build the coding agent's criteria summary from the single source of truth.\n * Grouped by priority for the P0→P1→P2 hierarchy.\n */\nexport function buildCodingCriteriaSummary(): string {\n const lines: string[] = [\"## Priority (P0 first, then P1, then P2)\", \"\"];\n\n for (const priority of [\"P0\", \"P1\", \"P2\"] as Priority[]) {\n const label =\n priority === \"P0\"\n ? \"Must (compile + complete)\"\n : priority === \"P1\"\n ? \"Should (safety)\"\n : \"Nice (quality)\";\n const criteria = getCriteriaByPriority(priority);\n lines.push(`**${priority} — ${label}:**`);\n for (const c of criteria) {\n lines.push(`- ${c.codingGuidance}`);\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n","// packages/ui-gen/src/internal/extract-call-signatures.ts\n//\n// Internal gadget-signature extractor.\n//\n// Uses the TypeScript Compiler API to parse an in-memory wrapper `.d.ts`\n// STRING and, for each requested export, print a prompt-ready type:\n//\n// - `extractCallSignaturesFromDts` — for HOOK exports, prints the\n// callable signature as a self-contained TS function-type\n// expression (`(options?: { center: [number, number]; zoom: number })\n// => GadgetHookResult<...>`).\n// - `extractComponentPropsFromDts` (GG.8.5) — for COMPONENT exports,\n// prints the props-object shape (the first parameter's type,\n// structurally expanded) so the prompt can teach the LLM the JSX\n// props of `<Chart data={…} height={…} />`.\n//\n// Both take the wrapper's already-built `.d.ts` content AS A STRING —\n// the render handler fetches each non-stdlib gadget's `.d.ts` over HTTPS\n// and threads a `package -> dtsContent` map into the generator\n// (`UiGenerateInput.gadgetTypes`). The code-gen prompt builder calls\n// these helpers to render a `Type:` / `Props:` line per third-party\n// gadget so the LLM sees the real shape it otherwise can't know.\n//\n// Internal only — NOT re-exported from any public package entry. Lives\n// under `src/internal/` deliberately.\n\nimport ts from 'typescript';\n\n/**\n * Map of `hookName → call-signature string` produced by\n * {@link extractCallSignaturesFromDts}. Each value is a printed\n * function-type expression suitable for verbatim interpolation into a\n * prompt `Type:` line.\n *\n * Hooks whose signature could not be resolved are omitted — the caller\n * renders a `Type:` line only for hooks that appear here.\n */\nexport type CallSignatureMap = Record<string, string>;\n\n/**\n * Map of `componentName → props-object type string` produced by\n * {@link extractComponentPropsFromDts}. Each value is a printed object\n * type (`{ data: …; height?: number }`) suitable for a prompt `Props:`\n * line. Components whose props could not be resolved are omitted.\n */\nexport type ComponentPropsMap = Record<string, string>;\n\n// In-memory `.d.ts` is parsed under a synthetic file name. The leading\n// `/` matches the convention `getCurrentDirectory()` (also `/`) so the\n// compiler host's path probes line up.\nconst VIRTUAL_DTS_PATH = '/__gadget__.d.ts';\n\nconst EXTRACTOR_COMPILER_OPTIONS: ts.CompilerOptions = {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n allowJs: false,\n jsx: ts.JsxEmit.ReactJSX,\n noEmit: true,\n esModuleInterop: true,\n // skipLibCheck so an unresolvable wrapper-internal import (the\n // sandbox doesn't carry the wrapper's transitive deps) doesn't abort\n // the program before we can read the symbol's callable signature.\n skipLibCheck: true,\n strict: true,\n};\n\n/**\n * Process-lifetime memos. Building a `ts.Program` — including\n * default-lib reads — on every call is expensive, and each extractor is\n * invoked once per coding-agent turn while the `.d.ts` content + name\n * set stay constant across a generation. Keying on `(dtsContent, names)`\n * collapses the repeated work. The key set is tiny in practice (a\n * handful of gadgets per process).\n */\nconst callSignatureCache = new Map<string, CallSignatureMap>();\nconst componentPropsCache = new Map<string, ComponentPropsMap>();\n\n/**\n * One-shot extractor program for a wrapper `.d.ts`, with the resolved\n * call signatures of every requested export. Shared by both public\n * extractors — they differ only in how they format the result.\n */\ninterface ExtractorContext {\n readonly checker: ts.TypeChecker;\n /** Render a `ts.Type` as a self-contained, prompt-ready expression. */\n readonly renderType: (t: ts.Type, depth: number) => string;\n /**\n * Requested export name → its resolved call signatures, in\n * declaration order. Only exports that are callable (a hook or a\n * function component) appear; non-callable exports are omitted.\n */\n readonly signaturesByName: ReadonlyMap<string, readonly ts.Signature[]>;\n}\n\n/**\n * Build a single-file TS Program over `dtsContent`, resolve the call\n * signatures of every requested export name, and expose the checker +\n * a structural type renderer. Returns `undefined` when the `.d.ts`\n * cannot be parsed.\n */\nfunction buildExtractorContext(\n dtsContent: string,\n names: readonly string[],\n): ExtractorContext | undefined {\n // Build a fresh `.d.ts` source file. `setParentNodes: true` is\n // required so the checker can walk the AST.\n const sourceFile = ts.createSourceFile(\n VIRTUAL_DTS_PATH,\n dtsContent,\n ts.ScriptTarget.ESNext,\n /* setParentNodes */ true,\n ts.ScriptKind.TS,\n );\n\n // Minimal in-memory compiler host. Only the synthetic `.d.ts` plus\n // the TS default lib files are resolvable; everything else is absent\n // (skipLibCheck keeps that from aborting the program). The checker\n // still resolves intra-file named types, which is all structural\n // fallback needs to inline a self-contained signature.\n const defaultLibName = ts.getDefaultLibFileName(EXTRACTOR_COMPILER_OPTIONS);\n const host: ts.CompilerHost = {\n getSourceFile(fileName) {\n if (fileName === VIRTUAL_DTS_PATH) return sourceFile;\n // Default lib(s) — load from the real `typescript` install so the\n // checker has `lib.d.ts` ambient types. The dts may not need\n // them, but the program won't run without a default lib.\n const libContent = ts.sys.readFile(\n ts.getDefaultLibFilePath(EXTRACTOR_COMPILER_OPTIONS).replace(\n /[^/\\\\]+$/,\n fileName,\n ),\n );\n if (libContent !== undefined) {\n return ts.createSourceFile(\n fileName,\n libContent,\n ts.ScriptTarget.ESNext,\n true,\n ts.ScriptKind.TS,\n );\n }\n return undefined;\n },\n getDefaultLibFileName() {\n return defaultLibName;\n },\n writeFile() {\n // no-op — noEmit\n },\n getCurrentDirectory() {\n return '/';\n },\n getCanonicalFileName(f) {\n return f;\n },\n useCaseSensitiveFileNames() {\n return true;\n },\n getNewLine() {\n return '\\n';\n },\n fileExists(f) {\n if (f === VIRTUAL_DTS_PATH) return true;\n return ts.sys.fileExists(f);\n },\n readFile(f) {\n if (f === VIRTUAL_DTS_PATH) return dtsContent;\n return ts.sys.readFile(f);\n },\n };\n\n const program = ts.createProgram(\n [VIRTUAL_DTS_PATH],\n EXTRACTOR_COMPILER_OPTIONS,\n host,\n );\n const checker = program.getTypeChecker();\n const parsed = program.getSourceFile(VIRTUAL_DTS_PATH);\n if (parsed === undefined) {\n return undefined;\n }\n\n const requested = new Set(names);\n\n // True when a symbol's declaration originates from the wrapper's own\n // `.d.ts`. Only THESE named types get structurally expanded — types\n // from the TS DOM lib (`HTMLDivElement`), `@ggui-ai/gadgets`\n // (`GadgetHookResult`), or any external package keep their name,\n // because (a) the LLM already knows DOM / ggui types and (b)\n // expanding `HTMLDivElement` would dump hundreds of DOM members into\n // the prompt.\n function isWrapperLocal(symbol: ts.Symbol | undefined): boolean {\n const decls = symbol?.getDeclarations();\n if (decls === undefined) return false;\n return decls.some((d) => d.getSourceFile().fileName === VIRTUAL_DTS_PATH);\n }\n\n // Render a single `ts.Type` as a self-contained TS type expression.\n //\n // The TS node builder keeps a type's NAME whenever that name is\n // reachable in the program — for a `.d.ts` whose option/value types\n // are `export interface`s, that means the printed signature ends up\n // full of `LeafletMapOptions` references the LLM cannot resolve. To\n // produce a prompt-ready, self-contained signature we structurally\n // expand WRAPPER-LOCAL named object types one level: enumerate the\n // apparent properties and render each property's type (recursively,\n // depth-bounded). Non-local named types, primitives, unions, arrays,\n // tuples, and anonymous objects keep `typeToString`'s rendering.\n const MAX_DEPTH = 4;\n function renderType(t: ts.Type, depth: number): string {\n const plain = (): string =>\n checker.typeToString(t, undefined, ts.TypeFormatFlags.NoTruncation);\n\n // Bail to the plain stringifier once we hit the depth cap so a\n // cyclic / deeply-nested type can't blow the stack.\n if (depth >= MAX_DEPTH) return plain();\n\n // `boolean` is internally `true | false` — `isUnion()` is true for\n // it. Catch it before union-splitting so it prints as `boolean`.\n if ((t.getFlags() & ts.TypeFlags.Boolean) !== 0) return 'boolean';\n\n // Union types (e.g. `LeafletMapOptions | undefined` from an\n // optional param) — recurse into each constituent so a wrapper-\n // local named object member still expands structurally.\n if (t.isUnion()) {\n return t.types.map((member) => renderType(member, depth)).join(' | ');\n }\n // Intersections — same treatment.\n if (t.isIntersection()) {\n return t.types.map((member) => renderType(member, depth)).join(' & ');\n }\n\n const symbol = t.getSymbol() ?? t.aliasSymbol;\n\n // Callable types (e.g. `containerRef: (el) => void`) — render the\n // first call signature inline.\n const callSigs = t.getCallSignatures();\n if (callSigs.length > 0) {\n const cs = callSigs[0]!;\n const params = cs\n .getParameters()\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? checker.getTypeOfSymbolAtLocation(p, decl)\n : checker.getDeclaredTypeOfSymbol(p);\n const optional =\n decl !== undefined &&\n ts.isParameter(decl) &&\n (decl.questionToken !== undefined ||\n decl.initializer !== undefined);\n return `${p.getName()}${optional ? '?' : ''}: ${renderType(pType, depth + 1)}`;\n })\n .join(', ');\n const ret = renderType(cs.getReturnType(), depth + 1);\n return `(${params}) => ${ret}`;\n }\n\n const isObject = (t.getFlags() & ts.TypeFlags.Object) !== 0;\n const isArrayOrTuple =\n checker.isArrayType(t) || checker.isTupleType(t);\n\n // Generic instantiation of a non-local type (e.g.\n // `GadgetHookResult<LeafletMapValue>`) — keep the outer name (the\n // LLM knows the ggui types) but recurse into the type arguments so\n // a nested wrapper-local type still expands.\n const typeArgs = (t as ts.TypeReference).typeArguments;\n if (\n symbol !== undefined &&\n isObject &&\n !isArrayOrTuple &&\n !isWrapperLocal(symbol) &&\n typeArgs !== undefined &&\n typeArgs.length > 0\n ) {\n const args = typeArgs.map((a) => renderType(a, depth + 1)).join(', ');\n return `${symbol.getName()}<${args}>`;\n }\n\n // Wrapper-local named object — expand its property shape inline.\n if (\n symbol !== undefined &&\n isObject &&\n !isArrayOrTuple &&\n isWrapperLocal(symbol)\n ) {\n const props = checker.getPropertiesOfType(t);\n if (props.length > 0) {\n const body = props\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? checker.getTypeOfSymbolAtLocation(p, decl)\n : checker.getDeclaredTypeOfSymbol(p);\n const optional = (p.getFlags() & ts.SymbolFlags.Optional) !== 0;\n return `${p.getName()}${optional ? '?' : ''}: ${renderType(pType, depth + 1)}`;\n })\n .join('; ');\n return `{ ${body} }`;\n }\n }\n\n return plain();\n }\n\n // The exported binding may surface as either:\n // - `export declare const useLeafletMap: GguiGadget<...>` — a\n // variable statement, or\n // - `export declare function useLeafletMap(...): ...` — a function\n // declaration, or\n // - `export { useLeafletMap } from '...'` — a re-export.\n // The module-symbol export table covers all three uniformly, so we\n // walk the module symbol's exports rather than top-level statements.\n const moduleSymbol = checker.getSymbolAtLocation(parsed);\n const exportSymbols: ts.Symbol[] =\n moduleSymbol !== undefined ? checker.getExportsOfModule(moduleSymbol) : [];\n\n const signaturesByName = new Map<string, readonly ts.Signature[]>();\n for (const symbol of exportSymbols) {\n const name = symbol.getName();\n if (!requested.has(name)) continue;\n if (signaturesByName.has(name)) continue;\n\n // Resolve aliases (re-exports) so we read the real declaration.\n const resolved =\n (symbol.flags & ts.SymbolFlags.Alias) !== 0\n ? checker.getAliasedSymbol(symbol)\n : symbol;\n\n const declarations = resolved.getDeclarations();\n if (declarations === undefined || declarations.length === 0) continue;\n const declaration = declarations[0]!;\n\n const type = checker.getTypeOfSymbolAtLocation(resolved, declaration);\n const callSignatures = type.getCallSignatures();\n if (callSignatures.length === 0) continue;\n\n signaturesByName.set(name, callSignatures);\n }\n\n return { checker, renderType, signaturesByName };\n}\n\n/**\n * Print one call signature as a self-contained `(params) => ret`\n * expression.\n */\nfunction printCallSignature(sig: ts.Signature, ctx: ExtractorContext): string {\n const params = sig\n .getParameters()\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? ctx.checker.getTypeOfSymbolAtLocation(p, decl)\n : ctx.checker.getDeclaredTypeOfSymbol(p);\n const optional =\n decl !== undefined &&\n ts.isParameter(decl) &&\n (decl.questionToken !== undefined || decl.initializer !== undefined);\n return `${p.getName()}${optional ? '?' : ''}: ${ctx.renderType(pType, 0)}`;\n })\n .join(', ');\n const ret = ctx.renderType(sig.getReturnType(), 0);\n return `(${params}) => ${ret}`.trim();\n}\n\n/**\n * Render a function component's props — the first parameter's type,\n * structurally expanded into a self-contained object type. A\n * zero-parameter component yields `{}`. Returns `undefined` when the\n * expander bottoms out on an unresolvable token.\n */\nfunction printComponentProps(\n sig: ts.Signature,\n ctx: ExtractorContext,\n): string | undefined {\n const params = sig.getParameters();\n // A zero-parameter component takes no props.\n if (params.length === 0) return '{}';\n const propsParam = params[0]!;\n const decl = propsParam.valueDeclaration ?? propsParam.declarations?.[0];\n const propsType =\n decl !== undefined\n ? ctx.checker.getTypeOfSymbolAtLocation(propsParam, decl)\n : ctx.checker.getDeclaredTypeOfSymbol(propsParam);\n const rendered = ctx.renderType(propsType, 0);\n // A surviving virtual-file qualifier means the structural expander\n // bottomed out on something it couldn't inline — drop it rather than\n // feed the LLM an unresolvable `import(\"/__gadget__\")` token.\n if (rendered.length === 0 || rendered.includes('import(\"')) return undefined;\n return rendered;\n}\n\n/**\n * Print the inferred call signature of every requested HOOK found in\n * the supplied wrapper `.d.ts` string.\n *\n * For each exported declaration whose name matches a requested hook,\n * the checker's callable signature is printed with structural-fallback\n * so wrapper-specific named types expand to their structural form — the\n * resulting string is self-contained and safe to drop into a prompt. A\n * hook declared with multiple overloads renders each, joined with ` | `.\n *\n * Hooks that aren't found, or that resolve to a value with no callable\n * signature, are omitted from the result (no throw) — the caller is\n * expected to render a `Type:` line only for hooks that resolved.\n *\n * Memoized on `(dtsContent, hookNames)`.\n */\nexport function extractCallSignaturesFromDts(\n dtsContent: string,\n hookNames: readonly string[],\n): CallSignatureMap {\n if (hookNames.length === 0 || dtsContent.trim().length === 0) {\n return {};\n }\n\n const cacheKey = `${dtsContent}\u0000${[...hookNames].sort().join(',')}`;\n const cached = callSignatureCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const result: CallSignatureMap = {};\n const ctx = buildExtractorContext(dtsContent, hookNames);\n if (ctx === undefined) {\n callSignatureCache.set(cacheKey, result);\n return result;\n }\n\n for (const [name, signatures] of ctx.signaturesByName) {\n // A hook declared with multiple overloads renders ALL of them,\n // joined as a union of function types. A surviving virtual-file\n // qualifier means the structural expander bottomed out on something\n // it couldn't inline — drop that overload rather than feed the LLM\n // an unresolvable `import(\"/__gadget__\")` token.\n const printed = signatures\n .map((sig) => printCallSignature(sig, ctx))\n .filter((s) => s.length > 0 && !s.includes('import(\"'))\n .join(' | ');\n if (printed.length > 0) {\n result[name] = printed;\n }\n }\n\n callSignatureCache.set(cacheKey, result);\n return result;\n}\n\n/**\n * Print the props-object shape of every requested COMPONENT found in\n * the supplied wrapper `.d.ts` string (GG.8.5).\n *\n * A function component's props are its first parameter's type. The\n * type is structurally expanded the same way hook signatures are, so\n * the printed value (`{ data: …; height?: number }`) is self-contained\n * and prompt-ready — the code-gen prompt renders it as a `Props:` line\n * so the LLM knows the JSX attributes of `<Component … />`.\n *\n * Components not found, or that resolve to a non-callable value, are\n * omitted (no throw). Memoized on `(dtsContent, componentNames)`.\n */\nexport function extractComponentPropsFromDts(\n dtsContent: string,\n componentNames: readonly string[],\n): ComponentPropsMap {\n if (componentNames.length === 0 || dtsContent.trim().length === 0) {\n return {};\n }\n\n const cacheKey = `${dtsContent}\u0000${[...componentNames].sort().join(',')}`;\n const cached = componentPropsCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const result: ComponentPropsMap = {};\n const ctx = buildExtractorContext(dtsContent, componentNames);\n if (ctx === undefined) {\n componentPropsCache.set(cacheKey, result);\n return result;\n }\n\n for (const [name, signatures] of ctx.signaturesByName) {\n // A component is single-signature by convention — use the first.\n const first = signatures[0];\n if (first === undefined) continue;\n const props = printComponentProps(first, ctx);\n if (props !== undefined) {\n result[name] = props;\n }\n }\n\n componentPropsCache.set(cacheKey, result);\n return result;\n}\n","// packages/ui-gen/src/boilerplate/system-prompt.ts\n//\n// System-prompt skeleton for the coding agent. Deterministic assembly;\n// injection points for funnel content (pitfalls) and for large content\n// blocks that are OWNED BY OTHER PACKAGES (design-system docs,\n// primitives doc, wire doc). Those blocks travel as strings so ui-gen\n// doesn't silently pull in megabytes of auto-generated content from\n// `@ggui-ai/design` / `@ggui-ai/wire` that those packages authoritatively\n// own.\n//\n// The only content this skeleton carries by default is the coding-\n// criteria summary (`buildCodingCriteriaSummary()` over the open\n// `CRITERIA` single-source-of-truth). Everything else defaults to empty\n// string — the skeleton still renders cleanly for OSS callers who don't\n// pass doc blocks.\n\nimport { resolveAppGadgets } from \"@ggui-ai/protocol\";\nimport type {\n GadgetDescriptor,\n GadgetExport,\n GadgetHookExport,\n GadgetComponentExport,\n} from \"@ggui-ai/protocol\";\nimport { buildCodingCriteriaSummary } from \"../evaluation/types-public.js\";\nimport {\n extractCallSignaturesFromDts,\n extractComponentPropsFromDts,\n} from \"../internal/extract-call-signatures.js\";\n\n/** Narrow a {@link GadgetExport} to its hook variant by field presence. */\nfunction isHookExport(exp: GadgetExport): exp is GadgetHookExport {\n return \"hook\" in exp;\n}\n\n/** Narrow a {@link GadgetExport} to its component variant by field presence. */\nfunction isComponentExport(exp: GadgetExport): exp is GadgetComponentExport {\n return \"component\" in exp;\n}\n\nexport interface SystemPromptInputs {\n /** The user's original request. */\n userRequest: string;\n /** Shell layout mode. */\n shellType?: string;\n /** Target screen size. */\n screen?: string;\n /** Axis-conditioned prompt fragments (from `compose()`). */\n axisDelta?: string;\n /**\n * Funnel content injection — env-gated pitfalls block rendered by the\n * caller. OSS default: `\"\"`. The hosted runtime's core wrapper passes\n * `renderPitfallsBlock()` which honors `GGUI_PITFALLS` /\n * `GGUI_NEW_PITFALLS` env vars.\n */\n pitfallsBlock?: string;\n /**\n * Pre-rendered criteria block. Defaults to\n * `buildCodingCriteriaSummary()` over the open CRITERIA registry.\n * Callers that want to override (e.g. a trimmed summary for fast mode)\n * pass their own string.\n */\n criteriaBlock?: string;\n /** Hand-written design-token reference. Owned by `@ggui-ai/design`. */\n designSystemDocs?: string;\n /** Auto-generated primitives reference. Owned by `@ggui-ai/design`. */\n primitivesDoc?: string;\n /** Auto-generated wire-hooks reference. Owned by `@ggui-ai/wire`. */\n wireDoc?: string;\n /**\n * Per-app gadget catalog. When provided, replaces the default\n * `STDLIB_GADGETS`-only table in the\n * `clientCapabilities — registered catalog` section so registered\n * third-party gadgets (Leaflet, Mapbox, Stripe, …) instruct the\n * code-gen LLM with the same teaching text the synth + decision LLMs\n * see.\n *\n * When omitted, the section renders the standard-library seed (the\n * first-party browser-capability hooks).\n */\n appGadgets?: readonly GadgetDescriptor[];\n /**\n * A `package -> .d.ts content` map for THIRD-PARTY gadget wrappers\n * (the render handler parallel-fetches each non-stdlib gadget's\n * `.d.ts`). When a gadget's `package` has an entry here,\n * `formatGadgetsSection` renders a `**Type**:` line carrying the\n * hook's extracted call signature — the LLM sees the real call shape\n * of a wrapper it cannot otherwise know.\n *\n * Stdlib gadgets (`@ggui-ai/gadgets`) get NO `Type:` line — they\n * already carry an `example` and are well-known; extracting stdlib\n * signatures is deliberately out of scope. Omit for STDLIB-only\n * callers (the section stays byte-identical).\n */\n gadgetTypes?: Readonly<Record<string, string>>;\n}\n\nconst SHELL_DESCRIPTIONS: Record<string, string> = {\n chat: \"inline component inside ChatShell message bubble (~400px wide, compact)\",\n fullscreen: \"full viewport, responsive layout\",\n spatial: \"floating AR/VR panel (~600px, touch-friendly)\",\n};\n\nconst SCREEN_DESCRIPTIONS: Record<string, string> = {\n mobile: \"single column, large touch targets\",\n tablet: \"flexible columns, medium spacing\",\n desktop: \"multi-column, dense layout\",\n universal: \"responsive across all breakpoints\",\n};\n\n/**\n * Render the `clientCapabilities — registered catalog` table from the\n * per-app gadget catalog. Each registered gadget renders one row\n * with hook + permission + the `description`-or-`usage` field as the\n * \"what it does\" column. Permission falls back to `(none)` when the\n * descriptor doesn't declare one.\n *\n * The table is built dynamically from the catalog so all three triad\n * surfaces (synth contract authoring, decision LLM, code-gen system\n * prompt) instruct the model uniformly about which gadgets are\n * available.\n *\n * Rows are emitted in catalog order. An empty catalog produces a hint\n * to seed it via `app.gadgets` rather than an empty table.\n *\n * When `gadgetTypes` carries a `.d.ts` for a gadget's `package`, a\n * `**Type**:` block is appended after the table with one line per\n * THIRD-PARTY gadget: `\\`<hook>\\`: <extracted call signature>`. The\n * signature is extracted from the wrapper's `.d.ts` via\n * `extractCallSignaturesFromDts`. Stdlib gadgets (`@ggui-ai/gadgets`)\n * get NO `Type:` line — they already carry an `example` and are\n * well-known. A hook whose signature can't be extracted is silently\n * skipped.\n *\n * Pure helper. Exported for unit testing.\n */\nexport function formatGadgetsSection(\n appGadgets: readonly GadgetDescriptor[],\n gadgetTypes?: Readonly<Record<string, string>>,\n): string {\n if (appGadgets.length === 0) {\n return [\n \"When the contract declares a `clientCapabilities.gadgets` entry,\",\n \"the hook MUST be one the operator has registered on\",\n \"`App.gadgets`. The default ggui server seeds the 7\",\n \"first-party STDLIB hooks; this server has none registered (the\",\n \"operator's `ggui.json#app.gadgets` is empty). Don't\",\n \"declare `clientCapabilities.gadgets` until a hook is registered.\",\n ].join(\" \");\n }\n // The LLM DIRECT-IMPORTS gadget hooks. The boilerplate emits\n // one combined `import { hookA, hookB } from '<package>'` line per\n // registered gadget package, above a `DO NOT EDIT` banner. The\n // `Package` column below IS the import specifier — it is load-bearing.\n //\n // Each `GadgetDescriptor` is a PACKAGE with `exports[]`;\n // flatten to the hook exports (one table row per hook), carrying\n // package identity through for the Package column.\n const hookExports = appGadgets.flatMap((descriptor) =>\n descriptor.exports\n .filter(isHookExport)\n .map((exp) => ({ exp, descriptor })),\n );\n // Component exports get their own table + render teaching.\n const componentExports = appGadgets.flatMap((descriptor) =>\n descriptor.exports\n .filter(isComponentExport)\n .map((exp) => ({ exp, descriptor })),\n );\n const header =\n \"When the contract declares a hook gadget on `clientCapabilities.gadgets`, the hook MUST be one of the registered hooks below. The boilerplate has already emitted a direct import per gadget package — `import { <hook>, … } from '<package>'` — above a `// DO NOT EDIT` banner. KEEP those imports exactly; they are the runtime-resolution anchor and self_check rejects the code if one disappears. Import each STDLIB hook from `@ggui-ai/gadgets`; import each third-party hook from the package named in the `Package` column. DO NOT invent your own import paths. Available registered hooks:\";\n const tableHead = [\n \"| Hook | Package (import from here) | Permission | What it does |\",\n \"| --------------------- | ---------------------------------- | ------------------ | ------------------------------------------- |\",\n ];\n const rows = hookExports.map(({ exp, descriptor }) => {\n const hookCol = `\\`${exp.hook}\\``.padEnd(21, \" \");\n const pkgCol = `\\`${descriptor.package}\\``.padEnd(34, \" \");\n const permCol = exp.permission\n ? `\\`${exp.permission}\\``.padEnd(18, \" \")\n : \"(none)\".padEnd(18, \" \");\n const what = (exp.usage ?? exp.description ?? \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 80);\n return `| ${hookCol} | ${pkgCol} | ${permCol} | ${what.padEnd(43, \" \")} |`;\n });\n\n // `**Type**:` lines for THIRD-PARTY gadgets. A gadget is third-party\n // when its `package` has a `.d.ts` entry in `gadgetTypes` (stdlib\n // `@ggui-ai/gadgets` is never in the map). The LLM can't know a\n // third-party wrapper's call shape; the extracted signature gives it\n // the exact param/return type to code against.\n // Stdlib gadgets get nothing here by design — `example` covers them.\n const typeLines: string[] = [];\n if (gadgetTypes !== undefined) {\n for (const { exp, descriptor } of hookExports) {\n const dts = gadgetTypes[descriptor.package];\n if (dts === undefined) continue; // stdlib or no `.d.ts` fetched.\n const signatures = extractCallSignaturesFromDts(dts, [exp.hook]);\n const sig = signatures[exp.hook];\n if (sig === undefined) continue; // graceful — couldn't extract.\n typeLines.push(`- \\`${exp.hook}\\`: \\`${sig}\\``);\n }\n }\n const typeBlock =\n typeLines.length > 0\n ? [\n \"\",\n \"**Type** (third-party gadgets — call signature from the wrapper's published `.d.ts`):\",\n \"\",\n ...typeLines,\n ]\n : [];\n\n const hookSection =\n hookExports.length > 0\n ? [header, \"\", ...tableHead, ...rows, ...typeBlock].join(\"\\n\")\n : \"\";\n\n // Component gadgets: their own table + RENDER (not call)\n // teaching. A component export is mounted as a JSX element; the LLM\n // never invokes it like a hook.\n const componentRows = componentExports.map(({ exp, descriptor }) => {\n const compCol = `\\`${exp.component}\\``.padEnd(21, \" \");\n const pkgCol = `\\`${descriptor.package}\\``.padEnd(34, \" \");\n const what = (exp.usage ?? exp.description ?? \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 80);\n return `| ${compCol} | ${pkgCol} | ${what.padEnd(53, \" \")} |`;\n });\n\n // `**Props**:` lines for THIRD-PARTY component gadgets. The\n // props-object shape is extracted from the wrapper's published\n // `.d.ts` so the LLM knows the exact JSX attributes of `<X … />`. A\n // component whose `package` has no `.d.ts` entry is skipped\n // (graceful — the `example` still covers it).\n const componentPropsLines: string[] = [];\n if (gadgetTypes !== undefined) {\n for (const { exp, descriptor } of componentExports) {\n const dts = gadgetTypes[descriptor.package];\n if (dts === undefined) continue; // stdlib or no `.d.ts` fetched.\n const propsMap = extractComponentPropsFromDts(dts, [exp.component]);\n const props = propsMap[exp.component];\n if (props === undefined) continue; // graceful — couldn't extract.\n componentPropsLines.push(`- \\`${exp.component}\\`: \\`${props}\\``);\n }\n }\n const componentPropsBlock =\n componentPropsLines.length > 0\n ? [\n \"\",\n \"**Props** (third-party component gadgets — prop shape from the wrapper's published `.d.ts`):\",\n \"\",\n ...componentPropsLines,\n ]\n : [];\n\n const componentSection =\n componentExports.length > 0\n ? [\n \"When the contract declares a component gadget on `clientCapabilities.gadgets`, the export is a COMPONENT — RENDER it as a JSX element (`<X … />`) in the tree you return. Do NOT call it like a hook. The boilerplate has already emitted a direct import per gadget package — `import { <Component>, … } from '<package>'` — above a `// DO NOT EDIT` banner. KEEP those imports exactly; they are the runtime-resolution anchor and self_check rejects the code if one disappears. Import each component from the package named in the `Package` column. Available registered components:\",\n \"\",\n \"| Component | Package (import from here) | What it does |\",\n \"| --------------------- | ---------------------------------- | ----------------------------------------------------- |\",\n ...componentRows,\n ...componentPropsBlock,\n ].join(\"\\n\")\n : \"\";\n\n return [hookSection, componentSection]\n .filter((section) => section.length > 0)\n .join(\"\\n\\n\");\n}\n\n/**\n * Assemble the coding-agent system prompt. Deterministic — the only\n * variable content comes from the caller-supplied injection fields.\n */\nexport function buildSystemPrompt(inputs: SystemPromptInputs): string {\n const shell = inputs.shellType ?? \"fullscreen\";\n const scr = inputs.screen ?? \"universal\";\n const shellDesc = SHELL_DESCRIPTIONS[shell] ?? SHELL_DESCRIPTIONS.fullscreen;\n const screenDesc = SCREEN_DESCRIPTIONS[scr] ?? SCREEN_DESCRIPTIONS.universal;\n\n const criteriaBlock = inputs.criteriaBlock ?? buildCodingCriteriaSummary();\n const pitfallsBlock = inputs.pitfallsBlock ?? \"\";\n const designSystemDocs = inputs.designSystemDocs ?? \"\";\n const primitivesDoc = inputs.primitivesDoc ?? \"\";\n const wireDoc = inputs.wireDoc ?? \"\";\n // Default to the standard-library seed when no per-app catalog is\n // supplied. Callers that resolve `App.gadgets` thread it through here.\n //\n // `gadgetTypes` carries third-party wrapper `.d.ts` content;\n // `formatGadgetsSection` renders a `Type:` line per third-party\n // gadget from it. When omitted, no `Type:` lines are rendered.\n const gadgetsSection = formatGadgetsSection(\n resolveAppGadgets(inputs.appGadgets),\n inputs.gadgetTypes,\n );\n\n const axisSection =\n inputs.axisDelta && inputs.axisDelta.trim().length > 0\n ? `\\n## Shape Guidance\\n${inputs.axisDelta}\\n`\n : \"\";\n\n return `You are ggui's UI builder. You receive a typed boilerplate and fill it in using apply_changes.\n\n## Your Task\n${inputs.userRequest}\n\n## Rendering Context\n- **Shell**: \\`${shell}\\` — ${shellDesc}\n- **Screen**: \\`${scr}\\` — ${screenDesc}\n\n## How It Works\n1. Read the boilerplate — typed Props, wire hooks, and layout container are pre-configured\n2. Respond with one apply_changes call — add state, helpers, and JSX\n3. If compilation or evaluation fails, you'll get errors to fix in the next turn\n\n${criteriaBlock}\n${axisSection}\n## Protocol Notes\nThe boilerplate pre-declares every wire hook the contract requires (\\`useAction\\`, \\`useStream\\`, \\`useGguiContext\\`, plus capability hooks from \\`@ggui-ai/gadgets\\` when the contract declares \\`clientCapabilities\\`). Three rules:\n1. **Do NOT delete any pre-declared hook.** \\`self_check\\` fails with \\`wire_preservation:<kind>:<name>\\` if you remove one.\n2. **Consume every hook binding** somewhere in the component — in JSX, a callback, or an effect. Unused bindings fail lint with \\`no-unused-vars\\`.\n3. **Do NOT invent new wire calls.** Every \\`useAction('X')\\`, \\`useStream('X')\\`, \\`useGguiContext('X')\\` etc. MUST correspond to a declared entry on the contract. Calling one that isn't declared fails \\`self_check\\` with \\`wire_undeclared:<kind>:<name>\\` because the runtime has no Context/registration for it and would throw at first paint. If you need a new wire surface, that's a contract authoring step the agent owns — your job is to honor what's declared.\n\nRenaming a binding is fine — the wiring is the string-literal argument, not the identifier.\n\n## Contract surface — four specs + two catalogs\n\nA \\`DataContract\\` declares everything a GguiSession exchanges with the outside world. **Four typed specs** for the four data-flow directions, **two reference catalogs** for tool / hook lookups:\n\n| Surface | Direction | Role |\n| -------------------- | -------------------------- | -------------------------------------------------------------------- |\n| \\`propsSpec\\` | server → UI (one-shot) | Initial render values delivered once at \\`ggui_render\\` |\n| \\`streamSpec\\` | agent → UI (many) | Typed channels for live updates via \\`ggui_emit\\` |\n| \\`actionSpec\\` | UI → agent (events) | Discrete events driving the agent's next turn (consumed via \\`ggui_consume\\`) |\n| \\`contextSpec\\` | UI → server (state mirror) | UI state the agent observes between turns |\n| \\`agentCapabilities.tools\\` | catalog | Tools the contract references via \\`actionSpec[*].nextStep\\` and \\`streamSpec[*].source.tool\\` |\n| \\`clientCapabilities.gadgets\\` | catalog | Browser-capability gadget hooks the component code mounts (e.g., \\`useGeolocation\\`) |\n\n**Placement rule for inbound specs**: actions drive turns; context observes state. There is no third category.\n\n**Data vs behavior**: the contract describes data flow; the component code describes behavior. Scroll, focus, toast, animation, clipboard write — all component code, never contract fields.\n\n## Defensive coding for absent / late-arriving data\n\nProps arrive via \\`ggui_update\\` and may be partial on first render. Stream channels start empty and fill over time. Context slots start at their declared default (often \\`null\\`). **Never assume a field exists before you read it.**\n\n- **Array iteration**: always default to \\`[]\\` before \\`.map\\`/\\`.filter\\`/\\`.length\\`. Use \\`(props.items ?? []).map(...)\\` not \\`props.items.map(...)\\`. Same for stream.all, stream.latest, etc.\n- **Object access**: optional-chain through nested fields. \\`props.user?.name ?? 'Anonymous'\\` not \\`props.user.name\\`.\n- **Number ops**: default before arithmetic. \\`(props.count ?? 0) + 1\\` not \\`props.count + 1\\`.\n- **Stream latest**: \\`useStream\\` returns \\`{latest: T | null, all: T[], isComplete: boolean}\\`. The default \\`all\\` is \\`[]\\` so it's safe to map; \\`latest\\` is null until the first frame arrives — guard before reading \\`.foo\\`.\n- **Stream reconciliation**: when a stream event carries an \\`action\\` discriminant (e.g. \\`create | move | edit | delete\\`), the channel is a CRUD feed — your handler MUST branch on EVERY value: append on \\`create\\`, drop on \\`delete\\`, replace-by-id on \\`move\\` / \\`edit\\`. Merging only the \"edit\" case silently loses created and deleted items. Reconcile into the SAME state that seeds from \\`props\\` (e.g. \\`useState(() => props.tasks ?? [])\\`) so the seed data and the live feed render as one list — and handle an event whose id is not yet present (a \\`create\\` for an unknown item) by inserting it, not ignoring it.\n- **Loading state**: while data is still absent, render \\`<Skeleton>\\` placeholders — never a blank screen. \\`<Skeleton variant=\"text\" />\\` for a text line, \\`variant=\"circle\"\\` for an avatar slot, default \\`rect\\` for a block.\n- **Empty state**: when a list or results array is empty, render \\`<EmptyState title=\"…\" description=\"…\" />\\` — a region that renders nothing when empty looks broken to the user.\n\nUnhandled \\`Cannot read properties of undefined\\` errors trip the iframe error boundary and the user sees \"Something went wrong\" — a regression class the runtime can't recover from.\n\n## Picking the right primitive for user gestures\n\nChoose by what the user is DOING, not where the result goes — the runtime handles the routing.\n\n| Gesture intent | LLM writes | Notes |\n| -------------- | ---------- | ----- |\n| Fire a server-side action | \\`useAction(name)\\` + call \\`dispatch(name, payload)\\` | Every action is agent-routed. The runtime emits an event on \\`ggui_consume\\`; the agent reacts on its next turn. If the contract entry declares \\`nextStep: 'X'\\`, that names the tool the agent SHOULD call next — advisory hint forwarded as event metadata. |\n| Surface state to the agent's context | the auto-generated \\`setSlotName\\` setter (from the boilerplate's \\`useGguiContext\\` line) | The runtime owns useState + Provider; the boilerplate emits one \\`const [slot, setSlot] = useGguiContext<T>('slot')\\` line per declared \\`contextSpec\\` slot. Write plain JSX, no \\`useState\\`, no Provider wrap. Every value change auto-flows to the host LLM (debounced). One-way client → agent — see \"Observable state via \\`contextSpec\\`\" below. |\n| Use a browser capability (camera, mic, geolocation, clipboard, file picker, notifications) | call the hook the contract declared, e.g., \\`const loc = useGeolocation();\\` and \\`await loc.start()\\` | The contract's \\`clientCapabilities.gadgets\\` declares which gadget exports the UI uses. The hook implementations live in \\`@ggui-ai/gadgets\\` (or a third-party package named in the \\`Package\\` column). Read \\`status\\` (\"idle\" / \"prompting\" / \"active\" / \"completed\" / \"denied\" / \"error\") to gate UI, and thread the resolved \\`value\\` into a contextSpec slot or actionSpec payload if the agent needs to see it. |\n| Open external link | Plain \\`<a href=\"https://...\">\\` (or \\`target=\"_blank\"\\`) | External cross-origin clicks are intercepted and routed through the host (security warnings, app-internal navigation, audit). Same-origin links and \\`#fragment\\` jumps stay native. |\n| Toggle fullscreen / chrome | Plain \\`el.requestFullscreen()\\` / \\`document.exitFullscreen()\\` | The native browser API is intercepted; the host adjusts iframe chrome accordingly. Returns a resolved promise so \\`.then()\\` / \\`await\\` chains don't break. |\n\nEvery gesture fires a uniform server-side audit envelope (\\`ggui_runtime_submit_action\\`) so operators see all three patterns in RenderInspector with the same shape.\n\n**Don't import wire hooks for link / display-mode.** \\`useAction\\` is the only wire hook for user gestures; links and fullscreen use plain HTML / browser APIs.\n\n**All actions are agent-routed.** Every action emits an event the agent reacts to on its next turn via \\`ggui_consume\\`. The optional \\`nextStep: '<tool>'\\` field on an \\`actionSpec\\` entry is a HINT naming the tool the agent SHOULD call next — the contract author's recommendation, NOT a binding directive. The agent decides whether to honor it. If you want to declare a tool catalog entry the contract references, add it to \\`agentCapabilities.tools[<name>]\\` with input/output schemas; the cross-ref linter rejects dangling \\`nextStep\\` values that don't resolve to a declared catalog entry.\n\n## Making a primitive interactive — \\`as={Trait}\\`\n\nStructural primitives (\\`Box\\`, \\`Stack\\`, \\`Row\\`, \\`Card\\`) have NO \\`onClick\\` by default. Add interactivity with the \\`as\\` prop — a trait, not a wrapper:\n\n\\`\\`\\`tsx\n<Card as={Clickable} onClick={() => dispatch('select', { id })}\n hoverStyle={{ boxShadow: 'var(--ggui-shape-shadow-lg)' }}>…</Card>\n\\`\\`\\`\n\n- \\`as={Clickable}\\` → \\`onClick\\` + keyboard activation (Enter/Space) + \\`role=\"button\"\\` + \\`hoverStyle\\`/\\`activeStyle\\`/\\`cursor\\`.\n- \\`as={Hoverable}\\` → \\`hoverStyle\\` only (no click). \\`as={Pressable}\\` → \\`onPress\\` + \\`pressStyle\\`.\n\n\\`as={Trait}\\` is a PROP — it does NOT re-nest the JSX. Never write \\`<Clickable>…</Clickable>\\` around a primitive; put \\`as={Clickable}\\` on the primitive itself. The trait carries the keyboard + ARIA wiring, so don't hand-write \\`onKeyDown\\` / \\`role\\`. Trait components (\\`Clickable\\`, \\`Hoverable\\`, \\`Pressable\\`) import from \\`@ggui-ai/design\\` like everything else — the boilerplate already imports them.\n\n**Semantic components are already interactive** — \\`Button\\` (\\`onClick\\`), \\`Link\\` (\\`href\\`), \\`Input\\` / \\`Select\\` (\\`onChange\\`). Use their own props; never put \\`as\\` on them. \\`Text\\` picks its element with \\`is\\` (\\`<Text is=\"label\">\\`), not \\`as\\`.\n\n**Never nest two interactive elements.** Interactive content MUST NOT contain other interactive content — a gesture on the inner control bubbles to the outer one and fires BOTH handlers (one user click → the action dispatched twice). Do NOT put a \\`Button\\`, \\`Checkbox\\`, \\`Input\\`, \\`Select\\`, \\`Link\\`, or another \\`as={Clickable}\\` primitive inside a \\`Card\\` / \\`Box\\` / \\`Row\\` / \\`Stack\\` that is itself \\`as={Clickable}\\`. Wire each \\`useAction\\` callback to exactly ONE surface: EITHER the whole card is the trigger (interactive container, no interactive children) OR an inner control is the trigger (plain container, no \\`as={Clickable}\\`) — never both. A row with a checkbox: put the action on the \\`Checkbox onChange\\` and leave the row plain.\n\n**\\`Text\\` / \\`Heading\\` accept NO event handlers and NO \\`as\\` — only \\`style\\` / \\`className\\` plus their own typed props.** \\`onClick\\`, \\`onDoubleClick\\`, \\`as={Clickable}\\`, \\`color\\` are all type errors on \\`Text\\`. When the request says a label is \"clickable\", \"editable\", \"edit on click / double-click\", or \"tap to …\", do ONE of these — never put the handler on \\`Text\\`:\n\n\\`\\`\\`tsx\n// Click-to-edit a label: wrap the Text in a Clickable structural primitive.\n<Box as={Clickable} onClick={() => setEditingId(task.id)}\n style={{ cursor: 'pointer' }}>\n <Text weight=\"semibold\">{task.title}</Text>\n</Box>\n\n// Or pair the label with an explicit edit Button (clearer affordance).\n<Row gap=\"xs\" align=\"center\">\n <Text weight=\"semibold\">{task.title}</Text>\n <Button variant=\"ghost\" size=\"xs\" aria-label=\"Edit title\"\n onClick={() => setEditingId(task.id)}>Edit</Button>\n</Row>\n\n// In edit mode, swap the Text for an Input.\n{editingId === task.id\n ? <Input value={draftTitle} onChange={setDraftTitle} label=\"Task title\" />\n : <Text weight=\"semibold\">{task.title}</Text>}\n\\`\\`\\`\n\n## Anti-patterns — DO NOT WRITE\n\nThe following identifiers / shapes are RETIRED from the contract surface as of 2026-05-11. Pre-2026-05-11 examples in your training data may include them; do not reproduce. The linter / CI grep gate rejects:\n\n- \\`useWiredTool\\`, \\`useClientTool\\` — retired hooks. Replace with \\`useAction\\` (events) and the named hook from \\`@ggui-ai/gadgets\\` (browser capabilities).\n- \\`dispatch: { kind: 'tool', tool: '...' }\\` / \\`dispatch: { kind: 'agent', intendedTool: '...' }\\` — retired discriminated-union. Use the flat optional \\`nextStep?: '<tool>'\\` instead.\n- \\`mode: 'host-routed'\\` / \\`mode: 'tool'\\` — retired \\`mode\\` field. Same fix: flat \\`nextStep?\\`.\n- \\`broadcast: {...}\\` on the contract — retired top-level field. Use \\`streamSpec[channel].source: {tool, args?}\\` to declare a tool-fed channel.\n- \\`wiredTools\\` / \\`agentTools\\` (top-level) — retired catalog names. Use \\`agentCapabilities.tools\\`.\n- \\`clientTools\\` / \\`clientCapabilities.capabilities\\` — retired catalog shapes. Use \\`clientCapabilities.gadgets\\` (entries declare hooks, not RPC).\n- \\`@ggui-ai/client-tools\\` — retired package name. Import gadget hooks from \\`@ggui-ai/gadgets\\`.\n- \\`intendedTool\\` — retired. Use \\`nextStep\\` (flat).\n- \\`props: { properties: {...} }\\` as a CONTRACT field — retired. The contract field is \\`propsSpec\\` (the wire \\`props\\` field on render / update still carries VALUES).\n\n## Cross-reference rules\n\nWhen you declare a reference, also declare the catalog entry it points at:\n\n- \\`actionSpec[X].nextStep = 'fetch_inbox'\\` → \\`agentCapabilities.tools.fetch_inbox = { toolInfo: { inputSchema, description?, outputSchema? }, usage?, example? }\\` MUST exist. Cross-ref code: \\`CTR_REF_NEXT_STEP\\`.\n- \\`streamSpec[X].source.tool = 'list_messages'\\` → \\`agentCapabilities.tools.list_messages\\` MUST exist. Cross-ref code: \\`CTR_REF_STREAM_SOURCE\\`.\n- The catalog entry's schemas MUST be a superset of the referencing spec's schema. Cross-ref code: \\`CTR_SCHEMA_INCOMPAT\\`.\n\n## clientCapabilities — registered catalog\n\n${gadgetsSection}\n\nEach hook conforms to \\`GadgetHook<TOutput, TOptions>\\`: call \\`start(opts?)\\` to fire, read \\`{value, status, error, stop?}\\`. \\`status\\` walks through \\`idle → prompting → active|completed\\` or routes to \\`denied\\` / \\`error\\` on failure.\n\n3rd-party plugins (Leaflet maps, Mapbox, Stripe, Chart.js, …) are registered via \\`createGguiGadget\\` from \\`@ggui-ai/gadgets\\` and surface in this same table when the operator has added them to \\`App.gadgets\\`. Reference any registered hook by name — render validation rejects hooks not in this catalog with \\`gadget_not_registered\\`.\n\n## Observable state via \\`contextSpec\\`\n\nWhen the contract declares \\`contextSpec\\`, the boilerplate auto-generates one \\`useGguiContext\\` call per slot at the top of your component. The runtime owns the underlying \\`useState\\` and the Provider tree — **you do NOT write \\`useState\\` or any \\`<Provider>\\` wrap yourself**:\n\n\\`\\`\\`tsx\nimport { useGguiContext } from '@ggui-ai/wire';\n\nexport default function Component(props: Props) {\n // AUTO-GENERATED — do not remove or rename:\n const [currentStep, setCurrentStep] = useGguiContext<number>('currentStep');\n const [draftText, setDraftText] = useGguiContext<string>('draftText');\n\n // Plain JSX. No Provider wrap. The runtime already wrapped your\n // component in nested SingleSlotProviders before this code ran.\n return (\n <Container>\n <Text>Step {currentStep}</Text>\n <Input value={draftText} onChange={(e) => setDraftText(e.target.value)} />\n <Button onClick={() => setCurrentStep((s) => s + 1)}>Next</Button>\n </Container>\n );\n}\n\\`\\`\\`\n\nFor every declared slot you have **\\`slotName\\` + \\`setSlotName\\`** in scope:\n- **Read** the value to render: \\`<Text>Step {currentStep}</Text>\\`\n- **Write** via the setter: \\`setCurrentStep(s => s + 1)\\` (in callbacks, effects, anywhere)\n\nEvery value change is mirrored to the host LLM's context automatically (debounced, default 300ms — adjustable per-slot via \\`entry.debounceMs\\` in the contract). The agent sees the user's interaction state — drafts, current step, hover, selection — without you calling any API.\n\n**When to use the auto-generated state.** Any slot the contract declared. If \\`contextSpec.draftText\\` exists, bind \\`<Input value={draftText} onChange={e => setDraftText(e.target.value)}>\\` so the agent sees the typing live. If \\`contextSpec.currentStep\\` exists, render the step indicator from \\`currentStep\\` and bump it via \\`setCurrentStep\\` in your \"next\" callback.\n\n**When NOT to use it.** Local UI state the contract did NOT declare — \\`isDropdownOpen\\`, hover flags, animation phase, ephemeral toggles. For those, use a plain \\`useState\\` directly. The runtime ignores undeclared state.\n\n**\\`contextSpec\\` direction is one-way: client → agent.** The agent uses \\`propsSpec\\` (via \\`ggui_update\\`) and \\`streamSpec\\` (via the live channel) to push state TO the client. Don't try to write to the agent via \\`contextSpec\\` — there is no return path.\n\n**Schema mismatches drop silently.** If you set a value that doesn't match the slot's schema (e.g. a string into a \\`{type: 'number'}\\` slot), the runtime logs a dev \\`console.warn\\` and skips the post. Make sure your setter calls produce values that match the declared shape.\n\n${pitfallsBlock}\n\n## Reference: Wire Hooks\n${wireDoc}\n\n${DESIGN_SYSTEM_GUIDANCE}\n\n### CSS Token Documentation\n${designSystemDocs}\n\n### Component Reference\n${primitivesDoc}\n`;\n}\n\n/**\n * Hand-written design-system guidance embedded in every coding-agent\n * system prompt. Lists prop-value enums, branded color strategy, and\n * responsive/parameterization rules that make a generated component\n * feel polished — the system prompt without it would only list\n * primitive *names*. Exported so `prompt-type-drift.test.ts` can\n * verify its enum claims against the auto-generated primitive catalog.\n */\nexport const DESIGN_SYSTEM_GUIDANCE = `## Imports & Component Surface\n\nImport ONLY from: \\`react\\`, \\`@ggui-ai/design\\`, \\`@ggui-ai/wire\\`. The ENTIRE design system — every primitive, component, composition and trait — is exported from the single \\`@ggui-ai/design\\` entry: \\`import { Card, Grid, Stack, Modal, Clickable } from '@ggui-ai/design'\\`. There are NO subpaths (\\`/primitives\\`, \\`/components\\`, …) — never import from them. Use the design components — DO NOT use raw HTML elements (\\`<button>\\`, \\`<input>\\`, \\`<div>\\` for layout) or Tailwind classes; those render unstyled in the iframe runtime.\n\nAvailable primitives (all from \\`@ggui-ai/design\\`):\n- Layout: Box, Container, Stack, Row, Grid, Spacer, Divider\n- Typography: Heading, Text, Link\n- Form: Button, Input, TextArea, Checkbox, Toggle, RadioGroup, Select, Slider\n- Display: Card, Alert, Badge, Avatar, Image, Icon, Progress, Spinner, Skeleton, Tooltip\n- Composite: Accordion, Tabs, Table, Toast\n\nAvailable compound components (all from \\`@ggui-ai/design\\`):\n- Autocomplete, Breadcrumb, Dropdown, EmptyState, FormField, Markdown, MarkdownInline, MenuItem, Pagination, SearchField, Stat, Stepper, Tag\n\n**Choosing between similar components** — pick by intent, don't guess:\n- **Pick from options**: one value from a short fixed list (a form field) → \\`Select\\`. Type-to-filter a long list, then pick → \\`Autocomplete\\`. A menu of actions off a button (edit / delete / …) → \\`Dropdown\\`. A search box that filters displayed content → \\`SearchField\\`.\n- **Tabular data** → \\`Table\\`. Reach for \\`DataTable\\` ONLY when you need built-in sorting / pagination / row-selection.\n- **Messaging**: an inline message in the layout flow → \\`Alert\\`. A transient popup → \\`Toast\\`. A panel listing many notifications → \\`NotificationCenter\\`.\n- **Step progress**: a wizard's step indicator → \\`Stepper\\`. NOT \\`Tabs\\` (implies free navigation), NOT \\`Progress\\` (continuous bar), NOT \\`Breadcrumb\\` (hierarchy).\n- **Containers**: width-constrain a page region → \\`Container\\`. A visually-contained surface (background + shadow + border) → \\`Card\\`. Plain grouping / spacing with no chrome → \\`Box\\`.\n\nEXACT primitive prop values (other values are silently ignored — the design system maps them to defaults):\n- \\`<Text size=\"...\">\\` — ONLY \\`xs | sm | base | lg | xl | 2xl | 3xl | 4xl\\`. For a HUGE number/temperature, use \\`<Text size=\"4xl\" weight=\"bold\">\\`. \\`caps\\` uppercases with letter-spacing — the eyebrow/overline label look is \\`<Text size=\"xs\" weight=\"semibold\" caps tone=\"muted\">\\`.\n- \\`<Text weight=\"...\">\\` — \\`normal | medium | semibold | bold\\`.\n- \\`<Text tone=\"...\">\\` — typed semantic slot. \\`default | muted | subtle | emphasized | loud | success | warning | error | info | inverse | inherit\\`. The theme decides what each tone LOOKS like — \\`muted\\` is a quiet warm grey on Claudic, a cool slate on Indigo. \\`tone\\` is the ONLY way to set Text color; the legacy \\`color=\"...\"\\` prop has been removed.\n- \\`<Heading level={1|2|3|4|5|6}>\\` — sizes are preset by level (h1 = 4xl bold, h2 = 3xl bold, h3 = 2xl semibold). Pass a number, not \\`level=\"h1\"\\`. Heading uses the same \\`tone\\` slot vocabulary as Text.\n- \\`<Icon name=\"...\" tone=\"...\">\\` / \\`<Spinner tone=\"...\">\\` / \\`<Link href=\"...\" tone=\"...\">\\` / \\`<Divider tone=\"...\">\\` — same \\`tone\\` vocabulary as Text. Default = \\`currentColor\\` (Icon), primary-tinted (Spinner / Link), outlineVariant (Divider). Use \\`tone=\"inherit\"\\` when you want the element to track the parent's foreground color (e.g. an Icon next to muted text).\n- \\`<Button variant=\"...\">\\` — \\`primary | secondary | outline | ghost | danger\\`. Sizes \\`xs | sm | md | lg\\`. Use \\`primary\\` for the main action — renders in the brand color automatically.\n- \\`<Card padding=\"lg\" shadow=\"md\" radius=\"lg\" surface=\"default\">\\` — shadow \\`none|sm|md|lg|xl\\`, radius \\`none|sm|md|lg|xl\\`. \\`surface\\` slot picks the fill: \\`default | elevated | sunken | accent | inverted | transparent\\`. Use \\`inverted\\` for dark testimonial-style cards on a light theme; \\`accent\\` for branded fills.\n- \\`<Box surface=\"...\">\\` — same surface slots as Card. \\`surface\\` is the ONLY theme-tracking background prop; the legacy \\`background=\"...\"\\` prop has been removed. For non-theme-mapped brand colors (a partner's exact brand hex like Stripe purple), use the typed escape \\`<Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">\\` — both props are required, and \\`assetSemantic\\` MUST be a non-empty human-readable label. Tier-0 self-check rejects every other hex / rgba on Box.\n- \\`<Stack gap=\"...\">\\` / \\`<Row gap=\"...\">\\` — \\`gap\\` takes the **spacing scale** (next bullet). \\`align\\` (cross-axis) is ONLY \\`start | center | end | stretch\\` and \\`justify\\` (main-axis) is ONLY \\`start | center | end | between | around | evenly\\` — NEVER the raw CSS values \\`flex-start\\` / \\`flex-end\\` / \\`space-between\\`, which are type errors.\n- **Spacing scale** — \\`gap\\` (Stack / Row / Grid) and \\`padding\\` (Card / Box / Container) take a t-shirt size: \\`none | xs | sm | md | lg | xl | 2xl\\`. Each resolves to a \\`--ggui-spacing-*\\` token (xs≈4px, sm≈8px, md≈16px, lg≈24px, xl≈32px, 2xl≈48px). A bare number is treated as pixels. NEVER pass a raw CSS length such as \\`gap=\"8px\"\\` — it is silently dropped by the browser and the gap collapses to 0; use the scale name (\\`gap=\"sm\"\\`).\n- \\`<Grid columns={N} gap=\"md\">\\` — 2-D layout (rows AND columns). Reach for it for card galleries, stat grids and dashboards — NEVER hand-roll \\`style={{ display: 'grid' }}\\`. When the request names exact per-breakpoint counts (\"3 per row on desktop, 1 on mobile\"), pass a map: \\`<Grid columns={{ base: 1, md: 3 }}>\\` (breakpoints \\`sm\\`/\\`md\\`/\\`lg\\`/\\`xl\\`; the design system emits the media queries). For an open-ended gallery where any column count is fine, use \\`<Grid minColumnWidth={220}>\\` — it fits as many equal columns as the width allows. \\`radius\\` (Card / Box / Image) takes the scale \\`none | sm | md | lg | xl\\`.\n- \\`<Stat label=\"…\" value=\"…\" delta=\"+12%\" trend=\"up\">\\` — KPI display (label + big value + trend-coloured delta + optional \\`icon\\`). \\`trend\\` is \\`up | down | neutral\\` (delta renders green / red / muted). Reach for it for any \"show a number\" UI; drop several into a \\`<Grid>\\` for a stat grid instead of hand-building label+value pairs.\n- \\`<Stepper steps={STEPS} current={step} />\\` — display-only step indicator for wizards/checkouts. \\`steps\\` is a top-level \\`const\\` array of labels; \\`current\\` is YOUR zero-indexed \\`useState\\` value; \\`orientation\\` is \\`horizontal | vertical\\`; optional \\`onStepClick={(i) => …}\\` makes steps clickable. Stepper never owns navigation state — your Next/Back handlers move \\`current\\`.\n- \\`<Badge variant=\"...\">\\` — \\`default | primary | secondary | success | warning | error | info\\` for colored pills. Great for status/condition labels. There is NO \\`neutral\\` variant — use \\`default\\` (or \\`secondary\\`) for an un-tinted pill.\n\n**Color choice rule of thumb.** Reach for typed slots first: Button \\`variant\\`, Badge \\`variant\\`, Alert \\`variant\\`, Text/Heading/Icon/Spinner/Link/Divider \\`tone\\`, Box/Card \\`surface\\`. NEVER hardcode hex \\`#XXXXXX\\`, rgba, or hsl — tier-0 self-check rejects them with \\`tokens:hex-color\\` / \\`tokens:hardcoded-color-fn\\` and the LLM must remediate. Hardcoded colors break the operator's theme switch (Indigo → Claudic → Cyberpunk preset has zero effect on a card hardcoded with \\`background: '#000'\\`).\n\n**Asset-color escape (Box only).** When you genuinely need a non-theme color — a partner's exact brand hex (Stripe purple \\`#635BFF\\`, Slack aubergine \\`#4A154B\\`), a fixed product surface — use \\`<Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">…</Box>\\`. The \\`assetSemantic\\` is REQUIRED and MUST be a non-empty human-readable label that documents intent. Tier-0 allows hex inside this typed pair; one without the other fails the check. Reach for \\`surface\\` first — \\`assetColor\\` is rare.\n\n## Accessibility (REQUIRED)\n\nThe design-system primitives are accessible by construction — they emit their own roles, labels, keyboard handlers, and error wiring. Your job is to USE them correctly, NOT to re-declare ARIA on top of them.\n\n1. **Form inputs** — give every \\`Input\\` / \\`TextArea\\` / \\`Select\\` a \\`label\\` prop. The primitive renders its own \\`<label htmlFor>\\`, and exposes \\`aria-invalid\\` + \\`aria-describedby\\` for errors. Do NOT add a separate \\`<Text>\\` label or your own \\`htmlFor\\` — that double-labels the field.\n \\`\\`\\`tsx\n <Input label=\"Email\" value={email} onChange={setEmail} type=\"email\" />\n \\`\\`\\`\n2. **Don't re-declare built-in ARIA.** \\`Progress\\`, \\`RadioGroup\\`, \\`Tabs\\`, \\`Toggle\\`, \\`Slider\\`, \\`Spinner\\`, \\`Alert\\`, \\`Accordion\\` already carry the correct \\`role\\` / \\`aria-*\\`. \\`Card as={Clickable}\\` already adds \\`role=\"button\"\\` + keyboard activation. Adding your own is redundant and often wrong.\n3. **Icons are decorative by default** — \\`<Icon name=\"check\" />\\` is hidden from screen readers, which is correct for an icon sitting next to text. Add \\`aria-label\\` ONLY for a standalone, meaning-bearing icon with no adjacent text. Icon-only \\`Button\\`s still need \\`aria-label\\` on the **Button** itself.\n4. **Live & streaming data** — wrap any region whose content updates on its own (a \\`useStream\\` \\`.latest\\` value, a live clock, an \"N new\" counter, a flashing price) in an element with \\`aria-live=\"polite\"\\` so screen readers announce the change.\n5. **Headings nest** — one \\`<Heading level={1}>\\` per screen, \\`level={2}\\` for sections, \\`level={3}\\` for subsections. Never skip or invert levels.\n6. **Buttons** — descriptive text content; icon-only buttons need \\`aria-label\\`. Announce busy state: \\`<Button disabled={isLoading} aria-busy={isLoading}>{isLoading ? 'Submitting…' : 'Submit'}</Button>\\`.\n7. **Stateful controls announce their state.** Toggleable / selectable / expandable things use the primitive that carries the semantics (\\`Checkbox\\`, \\`Toggle\\`, \\`Tabs\\`, \\`Accordion\\`) — never a styled \\`Box\\`/\\`Icon\\` that only *looks* checked. When you hand-roll one with \\`as={Clickable}\\`, \\`Clickable\\` adds button + keyboard semantics but NOT state — add it yourself: \\`role=\"checkbox\"\\` + \\`aria-checked={done}\\` on a toggleable row, \\`aria-pressed\\` on a toggle button, \\`aria-selected\\` on the chosen item, \\`aria-expanded\\` on an open/close affordance. Styling (strikethrough, color, a check icon) must never be the only carrier of state.\n\n## Design System Usage (CRITICAL)\n\nEVERY color, spacing, typography, shadow, and radius value MUST come from design-system CSS variables. The runtime injects them on \\`:root\\`.\n\nMANDATORY:\n1. NEVER use hardcoded hex colors like \\`#7c3aed\\` — ONLY \\`var(--ggui-color-*)\\` tokens.\n2. NEVER use CSS gradients with custom colors. If you need a gradient: \\`linear-gradient(to bottom, var(--ggui-color-primary-500, #0ea5e9), var(--ggui-color-primary-700, #0369a1))\\`.\n3. NEVER invent your own palette. The system provides primary, neutral, success, warning, error, and info — use ONLY these.\n4. ALWAYS include fallback values: \\`var(--ggui-color-primary-600, #0284c7)\\`.\n\nToken categories:\n- Brand: \\`var(--ggui-color-primary-600, #0284c7)\\`, \\`var(--ggui-color-primary-50, #f0f9ff)\\`\n- Text: \\`var(--ggui-color-onSurface, #18181b)\\`, \\`var(--ggui-color-onSurfaceVariant, #52525b)\\`\n- Backgrounds: \\`var(--ggui-color-surface, #fafafa)\\`, \\`var(--ggui-color-surfaceVariant, #f4f4f5)\\`\n- Borders: \\`var(--ggui-color-outline, #d4d4d8)\\`\n- Spacing: \\`var(--ggui-spacing-4, 16px)\\`, \\`var(--ggui-spacing-6, 24px)\\`\n- Typography: \\`var(--ggui-font-size-sm, 14px)\\`, \\`var(--ggui-font-weight-semibold, 600)\\`\n- Shadows: \\`var(--ggui-shape-shadow-sm)\\`, \\`var(--ggui-shape-shadow-md)\\`, \\`var(--ggui-shape-shadow-lg)\\`\n- Radius: \\`var(--ggui-shape-radius-md, 8px)\\`, \\`var(--ggui-shape-radius-lg, 12px)\\`\n\nPrefer primitives' built-in styling props over inline styles when possible.\n\n### Branded Color Strategy\n\nUse the FULL primary palette throughout the component — NOT only on submit buttons. A well-themed component feels distinctly branded, not gray-with-one-colored-button.\n\n| Element | Token | Purpose |\n|---------|-------|---------|\n| Section headers, hero areas, highlight strips | \\`primary-50\\` / \\`primary-100\\` | Subtle branded backgrounds |\n| Borders, dividers, focus rings, input focus | \\`primary-200\\` / \\`primary-300\\` | Branded structure |\n| Icons, links, labels, active indicators | \\`primary-500\\` / \\`primary-600\\` | Core accent color |\n| Buttons, CTAs, filled interactive elements | \\`primary-600\\` / \\`primary-700\\` | Primary actions |\n| Headings on light primary backgrounds | \\`primary-800\\` / \\`primary-900\\` | High-contrast branded text |\n\nUse semantic tokens (\\`onSurface\\`, \\`onSurfaceVariant\\`) for body text and secondary info. NEVER use raw \\`neutral-*\\` or \\`gray-*\\` for body text — they break in dark themes.\n\n### Theme-Agnostic Design\n\nComponents MUST be theme-agnostic — they reference CSS variables but NEVER assume a specific style. The theme decides what \\`primary-600\\` looks like.\n\nDO:\n- Use \\`var(--ggui-color-primary-*)\\` for brand elements — the theme controls what \"primary\" means\n- Use \\`var(--ggui-shape-shadow-*)\\` for depth, \\`var(--ggui-shape-radius-*)\\` for corners\n- Use semantic color roles: primary for brand, surface/onSurface for structure, success/error/warning for state\n\nDON'T:\n- Don't assume primary is blue — could be red, green, purple\n- Don't hardcode gradients tuned for a specific theme\n- Don't use fixed shadow values\n\nVisual hierarchy via tokens:\n- Elevated sections: \\`var(--ggui-shape-shadow-md)\\` + \\`var(--ggui-shape-radius-lg)\\`\n- Highlighted regions: \\`var(--ggui-color-primary-50)\\` background\n- Active/selected: \\`var(--ggui-color-primary-100)\\` background\n- Section headers: \\`var(--ggui-color-primary-600)\\` text or border-bottom\n\n## Responsive Design (CRITICAL)\n\nGenerated components become reusable blueprints — the same blueprint serves phones, tablets, desktops, spatial headsets. Design for ALL screen sizes:\n\n1. Design tokens for ALL spacing — never hardcode pixel values for padding/margins/gaps. Use the named spacing scale on props (\\`gap=\"md\"\\`, \\`padding=\"lg\"\\`); for inline \\`style\\` use \\`var(--ggui-spacing-*, …)\\`.\n2. Relative/fluid units — prefer \\`%\\`, \\`em\\`, \\`rem\\`, \\`min()\\`, \\`max()\\`, \\`clamp()\\` over fixed \\`px\\`.\n3. Fluid widths — \\`max-width\\` with \\`width: 100%\\`. Never set a fixed width.\n4. Compact padding — components are embedded in containers that provide their own chrome.\n5. No raw \\`@media\\` queries in component code — for a layout that must change by breakpoint, use \\`<Grid columns={{ base: 1, md: 3 }}>\\` (the design system emits the media queries for you) or a fluid \\`minColumnWidth\\` grid.\n\n## Data Parameterization (CRITICAL)\n\nGenerated components are CACHED blueprints reused across requests. NEVER hardcode request-specific data (names, cities, numbers, dates) into the component body. Define data as default prop values so the blueprint works for ANY similar request:\n\n\\`\\`\\`tsx\n// BAD — hardcoded, only works for Tokyo\nconst city = \"Tokyo\";\nconst temp = 18;\n\n// GOOD — parameterized via props with defaults from the request\ninterface Props {\n city?: string;\n temperature?: number;\n}\nexport default function WeatherCard({ city = \"Tokyo\", temperature = 18 }: Props) {\n // A controller can override for Seoul, Paris, etc.\n}\n\\`\\`\\`\n\nRules:\n1. All request-specific data → props with defaults. City names, tickers, user names, dates, counts.\n2. Layout and styling are universal. Colors, spacing, structure — these are the reusable part.\n3. Default values come from the current request — so the component renders correctly standalone.\n4. Props interface must be typed and exported.\n\n## Component Structure\n\nKeep JSX nesting depth to 3–5 levels. When deeper, extract repeated/complex sections into helper components — named functions defined above the main Component in the same file. Helpers take data + callbacks via props; they don't own state.\n\n\\`\\`\\`tsx\nimport { useState } from 'react';\nimport { Container, Card, Stack, Text, Button, Input } from '@ggui-ai/design';\n\ninterface Props {\n onSubmit?: (data: unknown) => void;\n}\n\nfunction ItemCard({ item, onEdit }: { item: Item; onEdit: (id: string) => void }) {\n return <Card padding=\"md\">…</Card>;\n}\n\nexport default function GeneratedComponent({ onSubmit }: Props) {\n return (\n <Container>\n {items.map((item) => <ItemCard key={item.id} item={item} onEdit={handleEdit} />)}\n </Container>\n );\n}\n\\`\\`\\`\n\n## Aesthetic Guidance (READ CAREFULLY — this is what separates \"polished\" from \"ok\")\n\n### Visual hierarchy — the SCALE GAP rule\n\nA polished UI has ONE hero that dominates. Everything else supports it. Bad layouts have everything at similar sizes — the eye has nowhere to land. The rule:\n\n**Hero metric vs supporting text must have a 2–3× size gap.** If the hero is the temperature, score, count, status, price — it's ENORMOUS. Use \\`<Text size=\"4xl\" weight=\"bold\">\\` — the largest \\`size\\` the type allows (\\`4xl\\` = 36px). Pair it with a small supporting label (\\`size=\"sm\"\\`, ~14px) so the gap reads as 2–3×. The hero number should feel oversized compared to the location/title around it. \\`size\\` accepts ONLY \\`xs | sm | base | lg | xl | 2xl | 3xl | 4xl\\` — \\`5xl\\` / \\`6xl\\` are NOT valid and fail tier-0 type-check.\n\n\\`\\`\\`tsx\n// BAD — temperature is the same size as the location heading\n<Heading level={1}>Seoul, South Korea</Heading>\n<Text size=\"lg\" weight=\"bold\">18°C</Text>\n\n// GOOD — temperature dominates (4xl), location supports it (sm)\n<Text size=\"sm\" tone=\"muted\">Seoul, South Korea</Text>\n<Text size=\"4xl\" weight=\"bold\">18°C</Text>\n<Text size=\"lg\" tone=\"muted\">Partly Cloudy · Feels like 16°C</Text>\n\\`\\`\\`\n\n### Color discipline — the 60/30/10 rule\n\nDon't paint everything in primary. Use:\n- **60% surface** (\\`var(--ggui-color-surface)\\` / \\`onSurface\\`) — body text, default backgrounds, structure\n- **30% surfaceVariant + onSurfaceVariant** — secondary text, captions, labels, dividers\n- **10% primary** — hero number, ONE highlight element, CTAs, brand accent\n\nIf your component is 100% purple text on purple backgrounds, you've lost the eye. Headings can be \\`onSurface\\` (dark neutral) — they'll still feel weighty. Save the primary palette for one or two STAR moments.\n\n\\`\\`\\`tsx\n// BAD — everything purple, eye has no anchor\n<Heading tone=\"emphasized\">Title</Heading>\n<Text tone=\"emphasized\">42</Text>\n<Text tone=\"emphasized\">all body text</Text>\n\n// GOOD — hero pops, body is neutral, primary is reserved\n<Heading>Title</Heading> {/* defaults to onSurface */}\n<Text size=\"4xl\" weight=\"bold\" tone=\"emphasized\">42</Text>\n<Text tone=\"muted\">all body text</Text>\n\\`\\`\\`\n\n### Visual rhythm — vary your card treatments\n\nA row of identical flat tiles feels monotone. Use card-treatment variation to create rhythm:\n- **Hero card**: \\`<Card padding=\"xl\" shadow=\"lg\" radius=\"xl\">\\` with branded gradient background — anchors the eye\n- **Stat tiles**: \\`<Card padding=\"md\" shadow=\"sm\" radius=\"md\">\\` with surface bg — secondary\n- **Inline rows / list items**: no card chrome at all, just \\`<Stack gap=\"sm\">\\` with dividers — tertiary\n\nThe hero should literally have higher elevation than the supporting tiles. If everything has \\`shadow=\"md\"\\`, nothing does.\n\n### Iconography — emoji + Icon are visual weight on the cheap\n\nDon't render text-only metrics. A weather widget without a sun/cloud, a stock card without an arrow, a status panel without a colored dot — all feel undersold. Pair every hero metric with an icon or emoji at large size:\n\n\\`\\`\\`tsx\n<Row gap=\"md\" align=\"center\">\n <Text size=\"3xl\">☀️</Text>\n <Stack gap=\"xs\">\n <Text size=\"4xl\" weight=\"bold\">18°C</Text>\n <Text size=\"sm\" tone=\"muted\">Sunny · feels like 16°</Text>\n </Stack>\n</Row>\n\\`\\`\\`\n\nUse \\`<Icon name=\"...\" />\\` (Lucide icon names in kebab-case) for line icons; emoji directly for status/weather/mood. Both are valid. For per-stat tiny accents, use a small icon next to the label.\n\n### Spacing — generosity beats compactness\n\nHero sections should feel airy. Use \\`padding=\"xl\"\\` (32px) on the main card, not \\`padding=\"md\"\\`. Whitespace IS design. A cramped polished card looks worse than a roomy plain one.\n\n### Concrete recipes\n\n- **Hero metric card** (weather, stock, score): hero number at \\`size=\"4xl\"\\` (the max), icon/emoji at \\`size=\"3xl\"\\` next to it (use \\`<Row gap=\"md\">\\`), supporting label at \\`size=\"sm\"\\` muted, branded gradient bg, \\`shadow=\"lg\"\\`, \\`padding=\"xl\"\\`.\n- **Stat grid** (3–6 quick metrics): \\`<Grid columns={3} gap=\"md\">\\` of \\`<Stat>\\` — each \\`<Stat label=\"…\" value=\"…\" delta=\"…\" trend=\"…\" />\\` handles the label-on-top / value-below / trend-coloured-delta layout for you. Wrap each in a \\`<Card padding=\"md\" shadow=\"sm\">\\` if you want tile chrome.\n- **List item** (forecast day, todo, message): no card per item, use \\`<Stack gap=\"md\">\\` with each row as \\`<Row gap=\"md\">\\` of icon + content + meta. Add \\`<Divider>\\` between rows.\n- **Multi-step wizard** (survey, onboarding, checkout): \\`<Stepper steps={STEPS} current={step} />\\` at the top, the current step's fields below, Next/Back buttons that move \\`step\\`. Don't hand-roll a \"2 of 4\" indicator.\n- **Key-value rows** (specs, order summary, flight details): \\`<Stack gap=\"sm\">\\` of \\`<Row justify=\"between\">\\` — label as \\`<Text size=\"sm\" tone=\"muted\">\\`, value as \\`<Text size=\"sm\" weight=\"medium\">\\`.\n- **Section header**: \\`<Heading level={2}>\\` left-aligned, optional \\`<Badge>\\` to its right for count/status, optional muted caption below.\n- **CTA section**: ONE primary button. Other actions as ghost/outline. Don't stack three primary buttons.\n\n## Quality Checklist (verify before returning)\n\n- [ ] Imports ONLY from: react, @ggui-ai/design, @ggui-ai/wire\n- [ ] No raw HTML elements (\\`<button>\\`, \\`<input>\\`, \\`<div>\\` for layout) — uses primitives\n- [ ] ZERO hardcoded hex colors — every color is \\`var(--ggui-color-*, fallback)\\`\n- [ ] No raw pixel values for spacing — all via \\`var(--ggui-spacing-*)\\` tokens\n- [ ] Primary palette used throughout (headers, borders, icons) — not just buttons\n- [ ] Typed Props interface exported; request-specific data is a prop with default\n- [ ] Every Input/TextArea/Select has a \\`label\\` prop (no separate \\`<Text>\\` label)\n- [ ] Icon-only buttons have \\`aria-label\\`; no redundant \\`role\\`/\\`aria-*\\` on primitives\n- [ ] Toggleable/selected/expanded state is ARIA-expressed (\\`aria-checked\\`/\\`aria-pressed\\`/\\`aria-selected\\`/\\`aria-expanded\\`) — never style-only\n- [ ] Live/streaming regions wrapped in \\`aria-live=\"polite\"\\`\n- [ ] Headings nest — one \\`level={1}\\`, then \\`level={2}\\`/\\`{3}\\` — never skipped or inverted\n- [ ] Wire hooks (\\`useAction\\`, \\`useStream\\`) imported from \\`@ggui-ai/wire\\` and consumed`;\n"]}
1
+ {"version":3,"sources":["../src/boilerplate/render.ts","../src/boilerplate/json-schema-ts.ts","../src/boilerplate/generate.ts","../src/evaluation/types-public.ts","../src/internal/extract-call-signatures.ts","../src/boilerplate/system-prompt.ts"],"names":["__dirname"],"mappings":";;;;;;;AAYA,IAAMA,WAAA,GAAY,OAAA,CAAQ,aAAA,CAAc,MAAA,CAAA,IAAA,CAAY,GAAG,CAAC,CAAA;AAiBxD,IAAM,aAAA,GAAgB;AAAA,EACpB,OAAA,CAAQA,aAAW,WAAW,CAAA;AAAA,EAC9B,OAAA,CAAQA,WAAA,EAAW,IAAA,EAAM,KAAA,EAAO,eAAe,WAAW,CAAA;AAAA,EAC1D,QAAQA,WAAA,EAAW,IAAA,EAAM,IAAA,EAAM,KAAA,EAAO,eAAe,WAAW,CAAA;AAAA,EAChE,QAAQA,WAAA,EAAW,IAAA,EAAM,MAAM,IAAA,EAAM,KAAA,EAAO,eAAe,WAAW,CAAA;AAAA,EACtE,OAAA,CAAQA,aAAW,IAAA,EAAM,IAAA,EAAM,MAAM,IAAA,EAAM,KAAA,EAAO,eAAe,WAAW;AAC9E,CAAA;AAEA,IAAI,SAAA,GAA2B,IAAA;AAC/B,IAAM,WAAA,uBAAkB,GAAA,EAAoB;AAE5C,SAAS,QAAA,GAAmB;AAC1B,EAAA,IAAI,WAAW,OAAO,SAAA;AAEtB,EAAA,KAAA,MAAW,OAAO,aAAA,EAAe;AAC/B,IAAA,IAAI;AACF,MAAA,SAAA,GAAY,YAAA,CAAa,OAAA,CAAQ,GAAA,EAAK,eAAe,GAAG,OAAO,CAAA;AAC/D,MAAA,OAAO,SAAA;AAAA,IACT,CAAA,CAAA,MAAQ;AAAE,MAAA;AAAA,IAAU;AAAA,EACtB;AAEA,EAAA,MAAM,IAAI,MAAM,wBAAwB,CAAA;AAC1C;AAEA,SAAS,UAAA,CAAW,WAAmB,MAAA,EAAwB;AAC7D,EAAA,MAAM,GAAA,GAAM,CAAA,EAAG,SAAS,C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A;AAAA;AAAA;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4FAAA,CAAA","file":"boilerplate.js","sourcesContent":["// packages/ui-gen/src/boilerplate/render.ts\n//\n// Loads base.tsx.tmpl + layout files from disk, caches them in memory,\n// and replaces {{MARKER}} placeholders with generated content.\n//\n// Package-private — consumers use `generateBoilerplate()` from\n// `@ggui-ai/ui-gen/boilerplate`; this file is not re-exported.\n\nimport { readFileSync } from 'node:fs';\nimport { resolve, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// `@ggui-ai/ui-gen` ships both `src/` and `dist/` (see package.json `files`).\n// Templates always live at `<pkg-root>/src/boilerplate/templates/` (kept in\n// the published tarball via `files: ['src', 'dist', ...]`). Render.ts gets\n// inlined into multiple dist entrypoints by tsup (`boilerplate.js`,\n// `harness/runtime.js`, `harness/index.js`, …), so `__dirname` varies. We\n// enumerate every reasonable location:\n//\n// - From tsx (`src/boilerplate/render.ts`): `./templates`\n// - Bundled into `dist/boilerplate.js`: `../src/boilerplate/templates`\n// - Bundled into `dist/harness/runtime.js`: `../../src/boilerplate/templates`\n// - Bundled into `dist/harness/coding/X.js`: `../../../src/boilerplate/templates`\n//\n// Step 3 (2026-04-27): the harness cluster ported in from cloud added the\n// `dist/harness/` and `dist/harness/coding/` entrypoints — needed deeper\n// upward walks than the pre-step-3 single-level `dist/`.\nconst TEMPLATE_DIRS = [\n resolve(__dirname, 'templates'),\n resolve(__dirname, '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', '..', 'src', 'boilerplate', 'templates'),\n resolve(__dirname, '..', '..', '..', '..', 'src', 'boilerplate', 'templates'),\n];\n\nlet baseCache: string | null = null;\nconst layoutCache = new Map<string, string>();\n\nfunction loadBase(): string {\n if (baseCache) return baseCache;\n\n for (const dir of TEMPLATE_DIRS) {\n try {\n baseCache = readFileSync(resolve(dir, 'base.tsx.tmpl'), 'utf-8');\n return baseCache;\n } catch { continue; }\n }\n\n throw new Error('No base.tsx.tmpl found');\n}\n\nfunction loadLayout(shellType: string, screen: string): string {\n const key = `${shellType}-${screen}`;\n if (layoutCache.has(key)) return layoutCache.get(key)!;\n\n // Try exact match, then fallback to universal, then fullscreen-universal\n const candidates = [\n `${shellType}-${screen}.tsx.tmpl`,\n `${shellType}-universal.tsx.tmpl`,\n `fullscreen-universal.tsx.tmpl`, // final fallback\n ];\n\n for (const filename of candidates) {\n for (const dir of TEMPLATE_DIRS) {\n try {\n const content = readFileSync(resolve(dir, 'layouts', filename), 'utf-8');\n layoutCache.set(key, content);\n return content;\n } catch { continue; }\n }\n }\n\n throw new Error(`No layout found for ${key}`);\n}\n\nexport interface BoilerplateMarkers {\n REACT_IMPORT: string;\n ALL_DESIGN: string;\n WIRE_IMPORT: string;\n PROPS_INTERFACE: string;\n ACTION_TYPES: string;\n STREAM_TYPES: string;\n /** `useGguiContext` destructure lines, one per declared `contextSpec`\n * slot. Emitted at the top of the user component body. The runtime\n * owns useState + Provider per slot; the LLM only reads `<slotKey>`\n * and writes via `set<SlotKey>`. Empty when contextSpec is absent or\n * empty. */\n CONTEXT_HOOKS: string;\n WIRE_HOOKS: string;\n AXIS_SECTIONS: string;\n}\n\nexport function renderBoilerplate(\n shellType: string,\n screen: string,\n markers: BoilerplateMarkers,\n): string {\n let template = loadBase();\n const layout = loadLayout(shellType, screen);\n template = template.replace('{{LAYOUT}}', layout);\n\n for (const [key, value] of Object.entries(markers)) {\n template = template.replaceAll(`{{${key}}}`, value);\n }\n\n return template;\n}\n","// packages/ui-gen/src/boilerplate/json-schema-ts.ts\n//\n// JSON Schema → TypeScript type string converter.\n//\n// Pure, self-contained, no env reads, no framework deps. Exposed\n// publicly on `@ggui-ai/ui-gen/boilerplate` because it's the primitive\n// that turns a contract's JSON Schema into the `interface Props { ... }`\n// block the boilerplate generator writes.\n\nimport type { JsonSchema } from '@ggui-ai/protocol';\n\n/**\n * Convert a JsonSchema to a TypeScript type string — recursive.\n *\n * Handles: string, number, integer, boolean, null, array (+ tuples), object,\n * enum, oneOf/anyOf (unions), nullable, const, additionalProperties.\n */\nexport function jsonSchemaTypeToTs(schema: JsonSchema): string {\n // ── Union types (oneOf / anyOf) ──\n const unionMembers = schema.oneOf ?? schema.anyOf;\n if (unionMembers?.length) {\n const types = [...new Set(unionMembers.map(s => jsonSchemaTypeToTs(s)))];\n return types.length === 1 ? types[0] : types.join(' | ');\n }\n\n // ── Const (literal type) ──\n if (schema.const !== undefined) {\n return typeof schema.const === 'string' ? `'${schema.const}'` : String(schema.const);\n }\n\n // ── Enum (union of literals) ──\n if (schema.enum?.length) {\n return schema.enum\n .map(v => typeof v === 'string' ? `'${v}'` : String(v))\n .join(' | ');\n }\n\n let result: string;\n\n switch (schema.type) {\n case 'string':\n result = 'string';\n break;\n case 'number':\n case 'integer':\n result = 'number';\n break;\n case 'boolean':\n result = 'boolean';\n break;\n case 'null':\n return 'null';\n\n case 'array': {\n if (schema.items) {\n const itemType = jsonSchemaTypeToTs(schema.items);\n // Use Array<T> for complex object types, T[] for simple\n result = (schema.items.type === 'object' && schema.items.properties)\n ? `Array<${itemType}>`\n : (itemType.includes('|') ? `(${itemType})[]` : `${itemType}[]`);\n } else {\n result = 'unknown[]';\n }\n break;\n }\n\n case 'object': {\n if (schema.properties) {\n const required = schema.required ?? [];\n const fields = Object.entries(schema.properties)\n .map(([key, prop]) => {\n const opt = !required.includes(key);\n return `${key}${opt ? '?' : ''}: ${jsonSchemaTypeToTs(prop)}`;\n })\n .join('; ');\n result = `{ ${fields} }`;\n } else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {\n result = `Record<string, ${jsonSchemaTypeToTs(schema.additionalProperties)}>`;\n } else {\n result = 'Record<string, unknown>';\n }\n break;\n }\n\n default:\n result = 'unknown';\n }\n\n // Apply nullable (OpenAPI 3.0 shorthand)\n if (schema.nullable && result !== 'unknown') {\n return `${result} | null`;\n }\n\n return result;\n}\n","// packages/ui-gen/src/boilerplate/generate.ts\n//\n// Typed boilerplate generator. Takes a data contract (propsSpec /\n// actionSpec / streamSpec / contextSpec + agentCapabilities.tools +\n// clientCapabilities.gadgets catalogs) and a rendering context\n// (shell + screen) and produces the starting `.tsx` boilerplate the\n// coding agent fills in via apply_changes.\n//\n// `agentCapabilities.tools` entries do NOT emit component hooks. They\n// are catalog declarations the AGENT invokes; component code references\n// them indirectly via `actionSpec.nextStep` (advisory hint surfacing on\n// action events) and `streamSpec.source.tool` (transport-negotiated\n// source).\n//\n// `clientCapabilities.gadgets` entries DO emit component-side gadget\n// plumbing. Gadgets are direct-imported: the generator emits one\n// combined `import { … } from '<package>'` per registered gadget\n// package, above a `// DO NOT EDIT` banner. Hook exports additionally\n// get a pre-emitted `const binding = hook();` call site; component\n// exports are import-only — the LLM renders `<X … />` in the JSX tree\n// itself. The deterministic `gadget_preservation` check rejects the\n// code if a gadget import disappears.\n//\n// Pure function — deterministic, no env reads, no I/O other than\n// `renderBoilerplate` reading the template files.\n\nimport type {\n ActionSpec,\n GadgetDescriptor,\n ContextSpec,\n DataContract,\n JsonObject,\n JsonValue,\n StreamSpec,\n} from \"@ggui-ai/protocol\";\nimport { HOOK_NAME_RE, listContractGadgets } from \"@ggui-ai/protocol\";\nimport { renderBoilerplate } from \"./render.js\";\nimport { jsonSchemaTypeToTs } from \"./json-schema-ts.js\";\n\n/** Shell layout modes supported by the boilerplate templates. */\nexport type ShellType = \"chat\" | \"fullscreen\" | \"spatial\";\n\n/** Target screen size. */\nexport type ScreenSize = \"mobile\" | \"tablet\" | \"desktop\" | \"universal\";\n\n// =============================================================================\n// Design-system surface (pre-imported in every boilerplate)\n// =============================================================================\n\nconst ALL_PRIMITIVES = [\n \"Container\",\n \"Card\",\n \"Stack\",\n \"Row\",\n \"Grid\",\n \"Box\",\n \"Divider\",\n \"Spacer\",\n \"Text\",\n \"Heading\",\n \"Button\",\n \"Input\",\n \"TextArea\",\n \"Select\",\n \"Checkbox\",\n \"Toggle\",\n \"RadioGroup\",\n \"Slider\",\n \"Badge\",\n \"Spinner\",\n \"Skeleton\",\n \"Avatar\",\n \"Alert\",\n \"Progress\",\n \"Image\",\n \"Icon\",\n \"Link\",\n \"Tooltip\",\n \"Table\",\n \"Tabs\",\n \"Toast\",\n \"Accordion\",\n \"MotionKeyframes\",\n \"useMotion\",\n \"useAnimationKey\",\n].join(\", \");\n\nconst ALL_COMPONENTS = [\n \"SearchField\",\n \"FormField\",\n \"MenuItem\",\n \"Tag\",\n \"Dropdown\",\n \"Autocomplete\",\n \"Breadcrumb\",\n \"Pagination\",\n \"EmptyState\",\n \"Stat\",\n \"Stepper\",\n \"Markdown\",\n \"MarkdownInline\",\n].join(\", \");\n\n// Mirrors the actual @ggui-ai/design compositions exports. The 2026-07-29\n// composite-roster wave (#306) deleted the six zero-consumer composites\n// (MakeTabLayout, MarketingHero/CTA/Features, IncidentTimeline,\n// UserProfileCard) from the design package; this list shrank with it.\n// The data-URL shim's allowlist must mirror this list (enforced by\n// verify-shim-allowlists.test.ts).\nconst ALL_COMPOSITIONS = [\n \"Header\",\n \"Sidebar\",\n \"CardGrid\",\n \"CommentThread\",\n \"DataTable\",\n \"ChatWindow\",\n \"NavigationBar\",\n \"FileUploader\",\n \"NotificationCenter\",\n \"Modal\",\n \"CommandPalette\",\n \"Footer\",\n \"Hero\",\n].join(\", \");\n\nconst ALL_INTERACT = [\"Clickable\", \"Hoverable\", \"Pressable\"].join(\", \");\n\n// D1: the whole design system is imported through one specifier\n// (`@ggui-ai/design`), so the boilerplate emits a single import line.\nconst ALL_DESIGN = [\n ALL_PRIMITIVES,\n ALL_COMPONENTS,\n ALL_COMPOSITIONS,\n ALL_INTERACT,\n].join(\", \");\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/** Infer a TypeScript type string from an example value (when no JSON Schema is available). */\nfunction inferTypeFromExample(example: JsonObject): string {\n const fields: string[] = [];\n for (const [k, v] of Object.entries(example)) {\n let t: string;\n if (v === null || v === undefined) t = \"unknown\";\n else if (typeof v === \"string\") t = \"string\";\n else if (typeof v === \"number\") t = \"number\";\n else if (typeof v === \"boolean\") t = \"boolean\";\n else if (Array.isArray(v)) {\n if (v.length === 0) t = \"unknown[]\";\n else if (typeof v[0] === \"string\") t = \"string[]\";\n else if (typeof v[0] === \"number\") t = \"number[]\";\n else if (typeof v[0] === \"object\" && v[0] !== null)\n t = `Array<${inferTypeFromExample(v[0] as JsonObject)}>`;\n else t = \"unknown[]\";\n } else if (typeof v === \"object\") {\n t = inferTypeFromExample(v as JsonObject);\n } else {\n t = \"unknown\";\n }\n fields.push(`${k}: ${t}`);\n }\n return `{ ${fields.join(\"; \")} }`;\n}\n\n// =============================================================================\n// Boilerplate generator\n// =============================================================================\n\nexport function generateBoilerplate(\n _userPrompt: string,\n contract?: DataContract,\n shellType?: ShellType,\n screen?: ScreenSize,\n /** Axis-composed boilerplate sections — fragments produced by `compose()`. */\n composedSections?: string,\n /**\n * Registered gadget catalog. The boilerplate emits a direct\n * `import { … } from '<package>'` per gadget package from the\n * contract's declarations; this catalog supplies the descriptor\n * metadata (`description` / `usage` / `example`) used to prime each\n * pre-emitted gadget call site so the LLM has a working starting\n * point rather than an empty `useFoo()` it might delete.\n */\n appGadgets?: readonly GadgetDescriptor[],\n): string {\n // ── Props interface from data contract (data only — NO action callbacks) ──\n // Contract shape (PropsSpec is ALWAYS the wrapper — never flat):\n // { properties: { fieldName: { schema, required, description } } }\n const propsFields: string[] = [];\n const propsProperties = contract?.propsSpec?.properties ?? {};\n for (const [key, entry] of Object.entries(propsProperties)) {\n const required = entry.required !== false;\n const nullable = entry.schema.nullable === true;\n const tsType = jsonSchemaTypeToTs(entry.schema);\n const fullType = nullable ? `${tsType} | null` : tsType;\n // Build comment: description + default value hint\n const parts: string[] = [];\n if (entry.description) parts.push(entry.description);\n if (entry.default !== undefined) parts.push(`(default: ${JSON.stringify(entry.default)})`);\n const desc = parts.length > 0 ? ` // ${parts.join(' ')}` : \"\";\n propsFields.push(` ${key}${required ? \"\" : \"?\"}: ${fullType};${desc}`);\n }\n\n // ── Actions (useAction hooks — fire-and-forget to agent) ──\n // Contract shape: { actionSpec: { actionName: { label, description, schema?, example?, nextStep? } } }\n // ActionEntry.nextStep: optional hint naming the MCP tool the AGENT\n // should invoke on its next turn after this action fires. Actions have\n // exactly one routing target — the agent; there is NO synchronous\n // server-side dispatch. The name is informational here (use it for\n // button labels, icons, copy).\n const actionTypeAliases: string[] = [];\n const actionHookCalls: string[] = [];\n const actionReturnFields: string[] = [];\n const actionsMap: ActionSpec = contract?.actionSpec ?? {};\n for (const [key, entry] of Object.entries(actionsMap)) {\n const label = entry.label ?? key;\n const desc = entry.description ?? \"\";\n const tool = entry.nextStep ?? \"\";\n const typeName = `Action${key.charAt(0).toUpperCase()}${key.slice(1)}Payload`;\n\n // Derive TypeScript type: schema > example > void (fire-and-forget)\n let tsType = \"void\";\n if (entry.schema) {\n tsType = jsonSchemaTypeToTs(entry.schema);\n } else if (entry.example && typeof entry.example === \"object\" && !Array.isArray(entry.example)) {\n tsType = inferTypeFromExample(entry.example as JsonObject);\n }\n\n const toolNote = tool ? ` (label \"${label}\", nextStep hint → ${tool})` : \"\";\n actionTypeAliases.push(\n `/** Action payload: ${desc || label}${toolNote} */\\ntype ${typeName} = ${tsType};`\n );\n // Inline signature tells the LLM exactly how to call this action\n const callSig = tsType === \"void\" ? \"() => void — fire and forget\" : `(data: ${tsType}) => void`;\n const toolHint = tool ? ` → nextStep: ${tool}` : \"\";\n actionHookCalls.push(` const ${key} = useAction<${typeName}>('${key}'); // ${callSig}${toolHint}`);\n actionReturnFields.push(key);\n }\n\n // ── Stream channels (useStream hooks — real-time from agent) ──\n // Stream spec: flat map { channelName: { schema, description, example } }\n const streamChannels: StreamSpec = contract?.streamSpec ?? {};\n const streamChannelEntries = Object.entries(streamChannels);\n\n const streamTypeAliases: string[] = [];\n const streamHookCalls: string[] = [];\n const streamReturnFields: string[] = [];\n for (const [channelName, entry] of streamChannelEntries) {\n const desc = entry.description ?? \"\";\n const typeName = `Stream${channelName.charAt(0).toUpperCase()}${channelName.slice(1)}`;\n const tsType = entry.schema\n ? jsonSchemaTypeToTs(entry.schema)\n : \"unknown\";\n streamTypeAliases.push(`/** Stream channel: ${desc} */\\ntype ${typeName} = ${tsType};`);\n // Show .latest/.all types so the LLM knows how to access stream data\n streamHookCalls.push(\n ` const ${channelName} = useStream<${typeName}>('${channelName}'); // .latest: ${typeName} | null, .all: ${typeName}[]`\n );\n streamReturnFields.push(channelName);\n }\n\n // ── agentCapabilities.tools catalog (NO component-side hook emission) ──\n // `agentCapabilities.tools[*]` declares tools the AGENT invokes —\n // referenced from the contract via `actionSpec[*].nextStep` (advisory\n // hint forwarded on action events) and `streamSpec[*].source.tool`\n // (channel data source). The component never calls these tools\n // directly; there is no `useWiredTool(name)` hook. The boilerplate\n // therefore emits no per-tool hook line, no request/response type\n // aliases, and no useWiredTool import.\n\n // ── Client capabilities (browser-capability gadget hooks declared in contract) ──\n // Contract shape: { gadgets: { '<package>': { '<exportName>': { description?, usage? } } } }\n // package-keyed two-level map. `listContractGadgets` flattens it to\n // `GadgetUse[]` — one record per used export with `package`, `name`,\n // and optional `description` / `usage` overrides. The export NAME\n // grammar discriminates kind (`use`-prefixed → hook, PascalCase →\n // component).\n // No type aliases — gadget hooks own their typed return shape.\n // No wire-import side effect — gadgets are imported from `package`\n // (default `@ggui-ai/gadgets`), not from `@ggui-ai/wire`.\n //\n // Group-by-package — emit ONE combined `import { hookA, hookB } from '<pkg>'`\n // per declared package, NOT one import per hook. Hooks ordered\n // alphabetically within each package for stable diffs across same-\n // contract regens.\n const gadgetUses = contract ? listContractGadgets(contract) : [];\n\n // Gadgets are DIRECT-imported from their package, grouped\n // per package below. Build a hook-name → registry export lookup so\n // each contract-declared gadget binding can be enriched with the\n // catalog's description / usage / example fields. Mirrors how wire\n // boilerplate emits typed action signatures + nextStep hints —\n // gadgets get the same priming so the LLM has a working call site to\n // start from rather than an empty `useFoo()` it might delete.\n //\n // Each `GadgetDescriptor` is a PACKAGE with `exports[]`;\n // flatten to the hook exports, keyed by hook name.\n const gadgetCatalog = new Map<\n string,\n {\n readonly description?: string;\n readonly usage?: string;\n readonly example?: JsonValue;\n }\n >();\n for (const descriptor of appGadgets ?? []) {\n for (const exp of descriptor.exports) {\n // `GadgetExport` is a type-exclusive union (`hook?: never` on the\n // component member); discriminate by VALUE presence — `\"hook\" in\n // exp` no longer narrows now that `hook` is an optional key of\n // both members.\n if (exp.hook === undefined) continue;\n gadgetCatalog.set(exp.hook, {\n description: exp.description,\n usage: exp.usage,\n example: exp.example,\n });\n }\n }\n // Gadget imports grouped by package: `package → set of export names`\n // (hook AND component exports). One combined\n // `import { … } from '<pkg>'` is emitted per package.\n const gadgetImportsByPackage = new Map<string, Set<string>>();\n const gadgetHookCalls: string[] = [];\n for (const use of gadgetUses) {\n const exportName = use.name;\n // Both hooks and components are DIRECT-imported from their\n // package — add every contract-declared export to the per-package\n // import group.\n const pkgExports = gadgetImportsByPackage.get(use.package);\n if (pkgExports !== undefined) pkgExports.add(exportName);\n else gadgetImportsByPackage.set(use.package, new Set([exportName]));\n\n // Kind discrimination is by the export-name grammar.\n // A component name (PascalCase) is import-only — the LLM renders\n // `<X … />` in the JSX tree itself, so there is no pre-emitted call\n // site. Hook names (`use`-prefixed) additionally get a pre-emitted\n // call line below so the LLM has a working invocation.\n if (!HOOK_NAME_RE.test(exportName)) continue;\n const hook = exportName;\n // Contract entry's local override wins; registry catalog is the\n // fallback (most plugin descriptors live on the registry side).\n // The wire `GadgetUse` carries only `description` / `usage`\n // overrides — `example` lives solely on the registered export.\n const contractDesc = use.description;\n const contractUsage = use.usage;\n const catalog = gadgetCatalog.get(hook) ?? {};\n const desc = contractDesc ?? catalog.description ?? hook;\n const usage = contractUsage ?? catalog.usage;\n const example = catalog.example;\n\n // Pre-emit the hook call so the LLM sees a working invocation\n // (and doesn't delete it as \"unused\"). Mirrors wire's typed-\n // signature pattern. Two example shapes in the wild:\n // (a) plain literal — `{ center: [0,0], zoom: 12 }` — the\n // descriptor IS the call args; inline as the call arg.\n // (b) shaped object — `{ call: '<full TS expression>',\n // returns: <typed return shape> }` — the canonical\n // sample/leaflet descriptor shape; emit the `call` as a\n // separate EXAMPLE comment so the LLM sees the literal TS\n // it should produce.\n let callArgs = '';\n let exampleComment = '';\n if (example !== undefined && example !== null) {\n const callLine =\n typeof example === 'object' &&\n !Array.isArray(example) &&\n typeof example.call === 'string'\n ? example.call\n : undefined;\n if (callLine !== undefined) {\n exampleComment = `\\n // EXAMPLE: ${callLine.trim()}`;\n } else {\n callArgs = JSON.stringify(example);\n }\n }\n const usageNote = usage ? ` USE: ${usage}` : '';\n // Local binding name: strip the `use` prefix + lowercase the first\n // char so `useGeolocation` → `geolocation`. The wire no longer\n // carries an explicit binding name (the export name IS the inner\n // key), so the boilerplate derives a stable, readable one.\n const bindingName =\n hook.length > 3\n ? hook.charAt(3).toLowerCase() + hook.slice(4)\n : hook;\n gadgetHookCalls.push(\n ` const ${bindingName} = ${hook}(${callArgs}); // ${desc}${usageNote}${exampleComment}`,\n );\n }\n // Gadgets are DIRECT-imported, one combined\n // `import { hookA, hookB } from '<pkg>'` per registered package\n // (packages + hooks sorted for stable diffs across same-contract\n // regens). The `DO NOT EDIT` banner + tier-0 `gadget_preservation`\n // keep the LLM from deleting an import it (correctly) intuits is\n // runtime-resolved — the banner alone makes direct imports survive\n // multi-turn generation. Tier-0 verifies each registered hook is\n // still imported from its package.\n const gadgetImportLine =\n gadgetImportsByPackage.size > 0\n ? \"// DO NOT EDIT — gadget imports. Each export is resolved by the iframe \" +\n \"runtime; keep every import line and export name. self_check fails with \" +\n \"gadget_preservation:<export> if a gadget import is removed.\\n\" +\n Array.from(gadgetImportsByPackage.entries())\n .sort(([a], [b]) => a.localeCompare(b))\n .map(\n ([pkg, hooks]) =>\n `import { ${Array.from(hooks).sort().join(\", \")} } from '${pkg}';`,\n )\n .join(\"\\n\")\n : \"\";\n // ── Props interface (data only — no action callbacks) ──\n const propsInterface =\n propsFields.length > 0\n ? `// DO NOT EDIT — generated from data contract. Changing this will fail validation.\\ninterface Props {\\n${propsFields.join(\"\\n\")}\\n}`\n : `// DO NOT EDIT — generated from data contract.\\ninterface Props {\\n [key: string]: string | number | boolean | null | object;\\n}`;\n\n // ── Context slots — `useGguiContext` hook ──\n // For each declared `contextSpec` slot, emit ONE destructure line\n // at the top of the user component:\n // const [<slotKey>, set<PascalSlotKey>] =\n // useGguiContext<TS>('<slotKey>');\n // The runtime owns useState per slot and wraps the user component\n // in nested SingleSlotProvider components — the user only reads\n // the live tuple via the hook. There must be NO `useState` and NO\n // `<Provider>` wrap anywhere in the LLM-authored JSX.\n const contextSpec: ContextSpec = contract?.contextSpec ?? {};\n const contextSpecEntries = Object.entries(contextSpec);\n let contextHooks = \"\";\n if (contextSpecEntries.length > 0) {\n const hookLines: string[] = [];\n for (const [slotKey, entry] of contextSpecEntries) {\n const valueType = entry.schema\n ? jsonSchemaTypeToTs(entry.schema)\n : \"unknown\";\n const setterName = `set${slotKey.charAt(0).toUpperCase()}${slotKey.slice(1)}`;\n hookLines.push(\n ` const [${slotKey}, ${setterName}] = useGguiContext<${valueType}>('${slotKey}');`,\n );\n }\n contextHooks =\n ` // DO NOT EDIT — auto-generated per contextSpec slot.\\n` +\n ` // Read \\`<slotKey>\\` to render, write via \\`set<SlotKey>\\` to\\n` +\n ` // surface the change to the agent's LLM context (debounced).\\n` +\n ` // The runtime owns the underlying useState + Provider; you\\n` +\n ` // write plain JSX, no wrap.\\n` +\n `${hookLines.join(\"\\n\")}\\n`;\n }\n\n // ── Determine which wire hooks are needed ──\n const hasActions = actionHookCalls.length > 0;\n const hasStream = streamHookCalls.length > 0;\n // Gates the gadget hook-CALL body section. A component gadget\n // contributes an import but no call site, so this is false for a\n // component-only contract — the import line is gated separately on\n // `gadgetImportLine` below.\n const hasGadgetHookCalls = gadgetHookCalls.length > 0;\n const hasContext = contextSpecEntries.length > 0;\n // `hasAnyHook` gates the \"DO NOT EDIT wire hooks\" header + body.\n // Client gadget HOOKS contribute call sites alongside the\n // @ggui-ai/wire hooks — their declaration needs the same emitted\n // header so the LLM sees the binding lines pre-declared and doesn't\n // strip / duplicate them. (Component gadgets add no body line.)\n const hasAnyHook =\n hasActions || hasStream || hasContext || hasGadgetHookCalls;\n const hasAnyWireFromWire = hasActions || hasStream || hasContext;\n\n const wireHooks: string[] = [];\n if (hasActions) wireHooks.push(\"useAction\");\n if (hasStream) wireHooks.push(\"useStream\");\n if (hasContext) wireHooks.push(\"useGguiContext\");\n const wireImport = hasAnyWireFromWire\n ? `import { ${wireHooks.join(\", \")} } from '@ggui-ai/wire';\\n`\n : \"\";\n // The gadget import line is emitted whenever ANY gadget export is\n // declared — hook OR component. (`gadgetImportLine` is non-empty iff\n // `gadgetImportsByPackage` has an entry; component-only contracts\n // have an import but no `hasGadgetHookCalls`.)\n const gadgetImport =\n gadgetImportLine.length > 0 ? `${gadgetImportLine}\\n` : \"\";\n\n // ── React import — only include hooks that are actually needed ──\n const reactHooks = [\"useState\", \"useCallback\", \"useMemo\", \"useEffect\", \"useRef\"];\n const reactImport = `import React, { ${reactHooks.join(\", \")} } from 'react';`;\n\n // ── Hook body ──────────────────────────────────────────\n // Wire hooks are placed inside render(), before the return statement.\n const hookParts: string[] = [];\n if (hasActions) {\n hookParts.push(\" // ── Actions (contract-typed, fire-and-forget to agent) ──\");\n hookParts.push(\" // Call these to send user interactions to the agent. Types are enforced by the compiler.\");\n hookParts.push(...actionHookCalls);\n }\n if (hasStream) {\n hookParts.push(\"\");\n hookParts.push(\" // ── Streams (contract-typed, real-time from agent) ──\");\n hookParts.push(\" // .latest is the most recent event (or null). .all is the full history array.\");\n hookParts.push(...streamHookCalls);\n }\n if (hasGadgetHookCalls) {\n hookParts.push(\"\");\n hookParts.push(\" // ── Gadgets (browser-capability hooks; UI-owned lifecycle) ──\");\n hookParts.push(\" // Read .value / .status; call .start() to invoke. Surface .value through\");\n hookParts.push(\" // an actionSpec payload or contextSpec slot if the agent needs to observe it.\");\n hookParts.push(...gadgetHookCalls);\n }\n\n // Only emit the \"DO NOT EDIT wire hooks\" header when there ARE wire-side\n // OR gadget-side hook bindings to surface. An orphaned header on\n // no-wire fixtures (e.g. weather-card) makes the LLM hallucinate\n // hooks for an empty section and burn turns on missing imports.\n const hookBody = hasAnyHook\n ? ` // DO NOT EDIT wire hooks — auto-generated from the data contract\\n${hookParts.join(\"\\n\")}\\n`\n : \"\";\n\n // ── Type alias blocks ───────────────────────────────────\n // Auto-generated type aliases serve as documentation for the LLM. Some are\n // referenced by the wire-hook calls below (e.g. `useAction<ActionXPayload>`)\n // but request types are typically only mentioned in trailing comments —\n // ESLint flags them as unused. Without `eslint-disable` here, the LLM\n // enters a fix-rename oscillation loop (prefix `_`, break prop access,\n // revert, retry…) that drives up to 27% of cap-hit selfCheckFails on\n // wire-bearing fixtures. Suppress no-unused-vars for the generated\n // type-alias block; \"DO NOT EDIT\" comments + tier-0 wire-preservation\n // already prevent the LLM from removing them.\n const wrapTypes = (label: string, body: string): string =>\n `\\n/* eslint-disable no-unused-vars */\\n// DO NOT EDIT — ${label}\\n${body}\\n/* eslint-enable no-unused-vars */\\n`;\n\n const actionTypesBlock =\n actionTypeAliases.length > 0\n ? wrapTypes(\"action payload types generated from action contract.\", actionTypeAliases.join(\"\\n\\n\"))\n : \"\";\n const streamTypesBlock =\n streamTypeAliases.length > 0\n ? wrapTypes(\"stream event types generated from stream contract.\", streamTypeAliases.join(\"\\n\\n\"))\n : \"\";\n // `clientCapabilities.gadgets` ship NO type-alias block — gadget\n // hooks own their typed return shape internally; the contract surface\n // is pure declaration.\n\n return renderBoilerplate(shellType ?? \"fullscreen\", screen ?? \"universal\", {\n REACT_IMPORT: reactImport,\n ALL_DESIGN,\n WIRE_IMPORT: wireImport + gadgetImport,\n PROPS_INTERFACE: propsInterface,\n ACTION_TYPES: actionTypesBlock,\n STREAM_TYPES: streamTypesBlock,\n CONTEXT_HOOKS: contextHooks,\n WIRE_HOOKS: hookBody,\n AXIS_SECTIONS: composedSections ?? \"\",\n });\n}\n","// Evaluation type vocabulary shared between the harness runtime and its\n// check/evaluator surfaces. This is the narrow contract layer — the\n// type language every harness leg is written against:\n//\n// - `EvalIssue` — the single issue shape everything produces.\n// - `EvalTier` / `EvalOutcome` / `EvalCategory` — the issue's axes.\n// - `Priority` — P0/P1/P2 ranking referenced by the retry formatter.\n// - `EvalResult` — aggregate shape a runner returns.\n// - `QualityMode` / `QualityConfig` / `DEFAULT_QUALITY_CONFIG` —\n// the quality-mode knob the adapter surface consumes.\n// - `priorityForIssue` / `isBlocked` / `getActionableIssues` — the\n// purely-typed helpers over the vocabulary.\n//\n// `EvalIssue` is referenced by `PatchFn`, `TierCheck`, `LLMEvaluator`,\n// and `RuntimeRenderCheck` in the harness types hub.\n\n// ─── Priority ──────────────────────────────────────────────────────────────\n// P0 = must (compile + complete), P1 = should (safety), P2 = nice (quality).\n// Single source of truth for the retry-formatter ranking.\n\nexport type Priority = \"P0\" | \"P1\" | \"P2\";\n\n// ─── Issue shape ───────────────────────────────────────────────────────────\n\nexport type EvalTier = 0 | 1 | 2;\nexport type EvalOutcome = \"fail\" | \"warn\" | \"pass\";\n\nexport type EvalCategory =\n | \"compile\"\n | \"security\"\n | \"contract\"\n | \"types\"\n | \"imports\"\n | \"tokens\" // tier 0\n | \"mode\" // tier 0 — per-mode deterministic\n | \"functionality\"\n | \"crash\" // tier 1\n | \"interactivity\"\n | \"accessibility\"\n | \"layout\"\n | \"loading\"\n | \"visual\"; // tier 2\n\nexport interface EvalIssue {\n tier: EvalTier;\n result: EvalOutcome;\n category: EvalCategory;\n /**\n * Priority tier — threaded through to the retry formatter so the LLM can\n * rank its next patch against the prompt's P0/P1/P2 priority schema.\n * Derived from (category, result) via {@link priorityForIssue} when not\n * explicitly set. Optional on construction; check-runners typically\n * populate it before returning.\n */\n priority?: Priority;\n subcategory?: string;\n severity?: \"critical\" | \"major\";\n description: string;\n fix: string;\n line?: number;\n}\n\n/**\n * Runtime-render probe execution status — three-valued so \"the probe\n * never ran\" is never conflated with \"the probe ran clean\".\n *\n * - `ran` — probe executed; its findings (possibly none) are\n * in the issue stream under `runtime:*` subcategories.\n * - `infra-skipped` — probe could NOT execute (environment failure:\n * happy-dom load, user-event document capture,\n * ESM/CJS interop). Carries ZERO probe evidence;\n * consumers MUST NOT count it as a pass.\n * - `not-applicable`— nothing to probe (no compiled code, no contract\n * surface, or no runtimeRender check configured).\n */\nexport type RuntimeProbeStatus = \"ran\" | \"infra-skipped\" | \"not-applicable\";\n\n/**\n * Probe execution meta stamped onto an `EvalResult` at the exit-decision\n * points that invoke the probe. Absence of this field means the eval\n * path never reached a probe invocation at all — consumers treat that\n * the same as not-run, never as a pass.\n */\nexport interface RuntimeProbeMeta {\n readonly status: RuntimeProbeStatus;\n /** Populated for `infra-skipped` / `not-applicable` — why the probe didn't run. */\n readonly reason?: string;\n}\n\nexport interface EvalResult {\n issues: EvalIssue[];\n pass: string[];\n /**\n * Runtime-render probe execution meta. Stamped by the exit-decision\n * probe runner; absent on eval paths that never invoke the probe.\n */\n runtimeProbe?: RuntimeProbeMeta;\n}\n\n// ─── Quality mode ──────────────────────────────────────────────────────────\n\nexport type QualityMode = \"fast\" | \"auto-improve\" | \"high-quality\";\n\nexport interface QualityConfig {\n quality: QualityMode;\n visualEval: boolean;\n maxCostPerGeneration: number;\n model?: { provider?: string; model?: string };\n}\n\nexport const DEFAULT_QUALITY_CONFIG: QualityConfig = {\n quality: \"fast\",\n visualEval: false,\n maxCostPerGeneration: 3,\n};\n\n// ─── Axis-check types ──────────────────────────────────────────────────────\n// The `AxisCheck` type vocabulary lives here. The check bodies\n// themselves (REGISTRY, per-axis implementations) live under\n// `./axis-checks/`.\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { AxisVector, Classification } from \"../classifier/axes.js\";\nimport type { AxisKey } from \"../fragments/index.js\";\n\nexport interface AxisCheckInput {\n sourceCode: string;\n compiledCode: string | null;\n contract?: DataContract;\n originalPrompt: string;\n /** Full classification — checks may read sibling axes. */\n classification: Classification;\n}\n\n/**\n * A gated check. Runs only when the classification's axis value matches\n * one of the gate's accepted values. Multiple gates (implicit AND) support\n * cross-axis combinations.\n */\nexport interface AxisCheck {\n /** Stable id used in issue subcategories. */\n id: string;\n /** Primary axis this check gates on. */\n axis: AxisKey;\n /** Which values of that axis activate the check. */\n values: readonly string[];\n /** Optional extra gate on a sibling axis (e.g., only when state=merge AND writes=per-item). */\n and?: { axis: AxisKey; values: readonly string[] };\n /** Execute the check and emit zero or more issues. */\n run(input: AxisCheckInput): EvalIssue[];\n}\n\n/**\n * Whether a check's gate(s) match the given axis vector. Pure function,\n * no issue emission.\n */\nexport function matches(vector: AxisVector, check: AxisCheck): boolean {\n const primary = vector[check.axis] as string;\n if (!check.values.includes(primary)) return false;\n if (check.and) {\n const sibling = vector[check.and.axis] as string;\n if (!check.and.values.includes(sibling)) return false;\n }\n return true;\n}\n\n// ─── Purely-typed helpers ──────────────────────────────────────────────────\n\n/**\n * Map a tier-0 issue category to the canonical P0/P1/P2 priority.\n *\n * Sourced from the criteria priority assignments:\n * - P0 (must): compile, security, imports, contract, types, mode\n * - P1 (safety): tokens, crash, functionality\n * - P2 (quality): interactivity, accessibility, layout, loading, visual\n */\nexport function priorityForIssue(category: EvalCategory): Priority {\n if (\n category === \"interactivity\" ||\n category === \"accessibility\" ||\n category === \"layout\" ||\n category === \"loading\" ||\n category === \"visual\"\n ) {\n return \"P2\";\n }\n if (category === \"tokens\" || category === \"crash\" || category === \"functionality\") {\n return \"P1\";\n }\n // compile, security, imports, contract, types, mode → P0.\n return \"P0\";\n}\n\n/** Whether any issue blocks shipping (has result = 'fail'). */\nexport function isBlocked(result: EvalResult): boolean {\n return result.issues.some((i) => i.result === \"fail\");\n}\n\n/**\n * Return the issues the agent should act on, depending on quality mode.\n * - fast: only fails (blocking issues)\n * - auto-improve / high-quality: fails + warns\n */\nexport function getActionableIssues(result: EvalResult, mode: QualityMode): EvalIssue[] {\n if (mode === \"fast\") {\n return result.issues.filter((i) => i.result === \"fail\");\n }\n return result.issues.filter((i) => i.result === \"fail\" || i.result === \"warn\");\n}\n\n// ─── Criteria (single source of truth for coding + eval sides) ─────────────\n//\n// Each criterion is defined ONCE with both sides of the contract:\n// - codingGuidance: what the coding agent should DO\n// - evalInstruction: what the eval agent should CHECK\n// They must be compatible — changing one means reviewing the other.\n//\n// This is *validated* shipping content: it's what the hosted runtime sends\n// to every generation today. External OSS implementers building their own\n// prompts should be able to use the same rubric — hence it's open.\n\nexport interface EvalCriterion {\n /** Unique identifier matching the eval tool name (e.g., 'functionality') */\n id: string;\n /** Human-readable name shown to both agents */\n name: string;\n /** Priority tier — P0 must, P1 should, P2 nice */\n priority: Priority;\n /** What the coding agent should DO to satisfy this criterion */\n codingGuidance: string;\n /** What the eval agent should CHECK — the evaluation prompt */\n evalInstruction: string;\n /** Tier 0 = programmatic, Tier 1 = LLM critical, Tier 2 = LLM quality */\n tier: 0 | 1 | 2;\n /** Eval outcome when this criterion fails */\n failOutcome: \"fail\" | \"warn\";\n}\n\nexport const CRITERIA: readonly EvalCriterion[] = [\n // ── P0: Correctness (must satisfy — failure = broken component) ──\n\n {\n id: \"compile\",\n name: \"Compile & type-check\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance:\n \"Code must compile. The typed Props and wire hook generics are enforced by the compiler.\",\n evalInstruction: \"Checked automatically by esbuild + TypeScript. No LLM evaluation needed.\",\n },\n {\n id: \"render-props\",\n name: \"Render all Props fields\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance: \"Render every Props field in JSX. Access via props.fieldName.\",\n evalInstruction:\n \"Check that every field from interface Props appears as props.fieldName in the function body.\",\n },\n {\n id: \"wire-hooks\",\n name: \"Wire all contract hooks\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Wire every useAction/useStream and every clientCapabilities.gadgets hook (e.g., useGeolocation) to a UI element. `agentCapabilities.tools` is a catalog the AGENT invokes — NOT a component hook surface.\",\n evalInstruction:\n \"Check that every hook variable from the boilerplate appears in the JSX or an effect.\",\n },\n {\n id: \"imports\",\n name: \"Valid imports only\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Only import from react, @ggui-ai/design/*, and @ggui-ai/wire.\",\n evalInstruction: \"Flag any import from a package not in the allowlist.\",\n },\n {\n id: \"security\",\n name: \"No eval/fetch/window\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Never use eval(), fetch(), or window. Data comes from props and hooks.\",\n evalInstruction: \"Flag any call to eval(), fetch(), or window access.\",\n },\n\n // ── P1: Safety (should satisfy — failure = crash or bad UX) ──\n\n {\n id: \"functionality\",\n name: \"All features implemented\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance: \"Implement ALL features from the request AND the data contract.\",\n evalInstruction: `Evaluate FUNCTIONALITY: Does this component implement ALL features from the request AND the data contract?\n\nCheck against BOTH sources:\n1. Original request — each feature must be coded AND rendered in JSX\n2. Data contract (if present) — verify:\n - Props fields are rendered in the UI. EXCEPTION: pure identifier fields (\\`id\\`, \\`*Id\\`, keys) that exist only to be echoed back inside an action payload do NOT need to be visibly rendered.\n - ALL useAction hooks are wired to clickable UI elements\n - ALL useStream hooks are consumed — the streamed data must reach the UI. Merging stream events into rendered state (a list, a counter, the displayed records) COUNTS as consuming the stream; it need not be a literal \\`.latest\\` render.\n - ALL clientCapabilities gadgets are used. \\`clientCapabilities.gadgets\\` is keyed by npm package: built-in browser capabilities (useGeolocation / useCamera / …) import from @ggui-ai/gadgets; registered third-party gadgets (e.g. useChartTheme) import from their OWN package. Any gadget the contract declares IS a contract feature — NEVER flag it as \"not part of the contract\".\n - \\`agentCapabilities.tools\\` is a catalog declaration only; do NOT flag missing component-side calls for it\n\nA contract hook that is declared but never used at all is a MISSING feature.\n\nCRITICAL: The \"issues\" array must ONLY contain features you are CERTAIN are missing or broken — never an implemented feature. (See \"Issue-array discipline\" above: no speculative, self-negating, or \"verify that…\" entries.)`,\n },\n {\n id: \"crash\",\n name: \"No crash scenarios\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance:\n \"Guard optional props (props.field?.x). stream.latest is T|null — always null-guard. .all is always an array.\",\n evalInstruction: `Evaluate CRASH SAFETY: Are there ACTUAL runtime crash scenarios?\n\nWILL crash (include in issues):\n- .map()/.filter()/.length on an uninitialized variable\n- Accessing property of undefined without guard\n- useStream().latest.field WITHOUT null guard — .latest is T | null\n- Optional Props field accessed as props.field.x without guard\n- Array item optional field: items.map(item => item.priority.toUpperCase()) when priority is optional\n\nSAFE (do NOT include):\n- Optional chaining: props.items?.map() — SAFE\n- Fallback: items || [] — SAFE\n- useState initializer: useState([]) — SAFE\n- Null check: items && items.map() — SAFE\n- stream.latest && stream.latest.field — SAFE, guarded\n- stream.all.map(...) — SAFE, .all is always an array\n- stream.all.length — SAFE, always a number\n\nThe \"issues\" array is ONLY for a specific line that WILL throw at runtime. NEVER put a line you have determined is safe into the issues array — not even to note that it is safe (\"…so this is safely guarded\", \"…so there is no crash\"). If you cannot name a concrete line that will throw, the answer is {\"pass\": true} — return that and an empty issues array.`,\n },\n {\n id: \"tokens\",\n name: \"Design system tokens\",\n priority: \"P1\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Use CSS variables for colors (var(--ggui-color-*)); use the spacing scale for gap/padding/margin (gap=\\\"md\\\", padding=\\\"lg\\\").\",\n evalInstruction:\n \"Flag hardcoded hex colors, rgba/hsl functions, and numeric or raw-CSS-length spacing props. A t-shirt-scale spacing name (gap=\\\"md\\\") IS a token — never flag it.\",\n },\n\n // ── P2: Quality (nice to have — failure = lower score, not broken) ──\n\n {\n id: \"interactivity\",\n name: \"Sufficient interactive elements\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Add appropriate interactive elements for the component purpose.\",\n evalInstruction: `Evaluate INTERACTIVITY: Does this component have sufficient interactive elements?\n\nConsider: forms need submit buttons, lists need selection, editable content needs save/cancel.\nContract actions (if present): every useAction hook should be triggered by a visible UI element.\n\nOnly list MISSING interactive elements. Use 'fail' only for issues blocking core purpose.`,\n },\n {\n id: \"accessibility\",\n name: \"Accessible markup\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance:\n \"Add labels on form inputs, alt text on images, semantic HTML, and state ARIA (aria-checked/pressed/selected/expanded) on hand-rolled interactive controls.\",\n evalInstruction: `Evaluate ACCESSIBILITY: missing labels, alt text, semantic HTML, keyboard support, ARIA state.\n\nggui primitives bake in their own ARIA — see \"Primitive Accessibility\" in the Design System context above. NEVER flag a ggui primitive (Input/Select/TextArea, RadioGroup, Checkbox, Toggle, Progress, Slider, Spinner, Skeleton, Tabs, Accordion, Alert, Toast, Tooltip, Clickable, Icon) for a missing role / aria-* / label / keyboard handler — it is already there and not visible in the source you are reading.\n\nFlag ONLY real gaps: a raw div/span used as an interactive control; a hand-rolled control whose checked/selected/expanded/pressed state is conveyed only by styling (strikethrough, color, a check icon) with no \\`aria-checked\\` / \\`aria-pressed\\` / \\`aria-selected\\` / \\`aria-expanded\\`; an image with no alt text; an Input/Select/TextArea with no \\`label\\` prop; an icon-only Button with no aria-label; live/streaming data not wrapped in an aria-live region; inverted heading hierarchy.\n\nOnly list MISSING accessibility features. Use 'fail' only if it blocks delivery.`,\n },\n {\n id: \"layout\",\n name: \"Clean layout\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use proper spacing and visual grouping.\",\n evalInstruction: `Evaluate LAYOUT: Check spacing, alignment, visual grouping, and composition.\n\nOnly list ACTUAL layout problems. Use 'fail' only for fundamentally broken layouts.`,\n },\n {\n id: \"loading\",\n name: \"Loading/empty/error states\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Handle async data, empty collections, and error cases.\",\n evalInstruction: `Evaluate LOADING/EMPTY/ERROR STATES: Does the component handle async data and edge cases?\n\nContract-specific: useStream should handle pre-data state. clientCapabilities hooks may return undefined / permission-denied — defensive guards expected before threading values into JSX.\nProps-only components (no async, no streams, no client capabilities) do NOT need loading states — return pass.\n\nOnly list MISSING states.`,\n },\n {\n id: \"visual\",\n name: \"Design system consistency\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use design system tokens consistently.\",\n evalInstruction: `Evaluate VISUAL CONSISTENCY: Is the component using the design system correctly?\n\nFlag: hardcoded colors instead of CSS variables, numeric or raw-CSS-length spacing instead of the t-shirt scale, style objects bypassing design system.\nA t-shirt-scale spacing name (gap=\"md\", padding=\"lg\") IS correct token usage — never flag it.\nIntentional custom colors (status indicators) are acceptable when no semantic token fits.\n\nOnly list ACTUAL violations. Use 'fail' only for pervasive violations.`,\n },\n] as const;\n\n/** Get all criteria for a specific priority level */\nexport function getCriteriaByPriority(priority: Priority): EvalCriterion[] {\n return CRITERIA.filter((c) => c.priority === priority);\n}\n\n/** Get a specific criterion by ID */\nexport function getCriterionById(id: string): EvalCriterion | undefined {\n return CRITERIA.find((c) => c.id === id);\n}\n\n/** Get all LLM-evaluated criteria (tier 1 + 2) */\nexport function getLLMCriteria(): EvalCriterion[] {\n return CRITERIA.filter((c) => c.tier > 0);\n}\n\n/**\n * Build the coding agent's criteria summary from the single source of truth.\n * Grouped by priority for the P0→P1→P2 hierarchy.\n */\nexport function buildCodingCriteriaSummary(): string {\n const lines: string[] = [\"## Priority (P0 first, then P1, then P2)\", \"\"];\n\n for (const priority of [\"P0\", \"P1\", \"P2\"] as Priority[]) {\n const label =\n priority === \"P0\"\n ? \"Must (compile + complete)\"\n : priority === \"P1\"\n ? \"Should (safety)\"\n : \"Nice (quality)\";\n const criteria = getCriteriaByPriority(priority);\n lines.push(`**${priority} — ${label}:**`);\n for (const c of criteria) {\n lines.push(`- ${c.codingGuidance}`);\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n","// packages/ui-gen/src/internal/extract-call-signatures.ts\n//\n// Internal gadget-signature extractor.\n//\n// Uses the TypeScript Compiler API to parse an in-memory wrapper `.d.ts`\n// STRING and, for each requested export, print a prompt-ready type:\n//\n// - `extractCallSignaturesFromDts` — for HOOK exports, prints the\n// callable signature as a self-contained TS function-type\n// expression (`(options?: { center: [number, number]; zoom: number })\n// => GadgetHookResult<...>`).\n// - `extractComponentPropsFromDts` (GG.8.5) — for COMPONENT exports,\n// prints the props-object shape (the first parameter's type,\n// structurally expanded) so the prompt can teach the LLM the JSX\n// props of `<Chart data={…} height={…} />`.\n//\n// Both take the wrapper's already-built `.d.ts` content AS A STRING —\n// the render handler fetches each non-stdlib gadget's `.d.ts` over HTTPS\n// and threads a `package -> dtsContent` map into the generator\n// (`UiGenerateInput.gadgetTypes`). The code-gen prompt builder calls\n// these helpers to render a `Type:` / `Props:` line per third-party\n// gadget so the LLM sees the real shape it otherwise can't know.\n//\n// Internal only — NOT re-exported from any public package entry. Lives\n// under `src/internal/` deliberately.\n\nimport ts from 'typescript';\n\n/**\n * Map of `hookName → call-signature string` produced by\n * {@link extractCallSignaturesFromDts}. Each value is a printed\n * function-type expression suitable for verbatim interpolation into a\n * prompt `Type:` line.\n *\n * Hooks whose signature could not be resolved are omitted — the caller\n * renders a `Type:` line only for hooks that appear here.\n */\nexport type CallSignatureMap = Record<string, string>;\n\n/**\n * Map of `componentName → props-object type string` produced by\n * {@link extractComponentPropsFromDts}. Each value is a printed object\n * type (`{ data: …; height?: number }`) suitable for a prompt `Props:`\n * line. Components whose props could not be resolved are omitted.\n */\nexport type ComponentPropsMap = Record<string, string>;\n\n// In-memory `.d.ts` is parsed under a synthetic file name. The leading\n// `/` matches the convention `getCurrentDirectory()` (also `/`) so the\n// compiler host's path probes line up.\nconst VIRTUAL_DTS_PATH = '/__gadget__.d.ts';\n\nconst EXTRACTOR_COMPILER_OPTIONS: ts.CompilerOptions = {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n allowJs: false,\n jsx: ts.JsxEmit.ReactJSX,\n noEmit: true,\n esModuleInterop: true,\n // skipLibCheck so an unresolvable wrapper-internal import (the\n // sandbox doesn't carry the wrapper's transitive deps) doesn't abort\n // the program before we can read the symbol's callable signature.\n skipLibCheck: true,\n strict: true,\n};\n\n/**\n * Process-lifetime memos. Building a `ts.Program` — including\n * default-lib reads — on every call is expensive, and each extractor is\n * invoked once per coding-agent turn while the `.d.ts` content + name\n * set stay constant across a generation. Keying on `(dtsContent, names)`\n * collapses the repeated work. The key set is tiny in practice (a\n * handful of gadgets per process).\n */\nconst callSignatureCache = new Map<string, CallSignatureMap>();\nconst componentPropsCache = new Map<string, ComponentPropsMap>();\n\n/**\n * One-shot extractor program for a wrapper `.d.ts`, with the resolved\n * call signatures of every requested export. Shared by both public\n * extractors — they differ only in how they format the result.\n */\ninterface ExtractorContext {\n readonly checker: ts.TypeChecker;\n /** Render a `ts.Type` as a self-contained, prompt-ready expression. */\n readonly renderType: (t: ts.Type, depth: number) => string;\n /**\n * Requested export name → its resolved call signatures, in\n * declaration order. Only exports that are callable (a hook or a\n * function component) appear; non-callable exports are omitted.\n */\n readonly signaturesByName: ReadonlyMap<string, readonly ts.Signature[]>;\n}\n\n/**\n * Build a single-file TS Program over `dtsContent`, resolve the call\n * signatures of every requested export name, and expose the checker +\n * a structural type renderer. Returns `undefined` when the `.d.ts`\n * cannot be parsed.\n */\nfunction buildExtractorContext(\n dtsContent: string,\n names: readonly string[],\n): ExtractorContext | undefined {\n // Build a fresh `.d.ts` source file. `setParentNodes: true` is\n // required so the checker can walk the AST.\n const sourceFile = ts.createSourceFile(\n VIRTUAL_DTS_PATH,\n dtsContent,\n ts.ScriptTarget.ESNext,\n /* setParentNodes */ true,\n ts.ScriptKind.TS,\n );\n\n // Minimal in-memory compiler host. Only the synthetic `.d.ts` plus\n // the TS default lib files are resolvable; everything else is absent\n // (skipLibCheck keeps that from aborting the program). The checker\n // still resolves intra-file named types, which is all structural\n // fallback needs to inline a self-contained signature.\n const defaultLibName = ts.getDefaultLibFileName(EXTRACTOR_COMPILER_OPTIONS);\n const host: ts.CompilerHost = {\n getSourceFile(fileName) {\n if (fileName === VIRTUAL_DTS_PATH) return sourceFile;\n // Default lib(s) — load from the real `typescript` install so the\n // checker has `lib.d.ts` ambient types. The dts may not need\n // them, but the program won't run without a default lib.\n const libContent = ts.sys.readFile(\n ts.getDefaultLibFilePath(EXTRACTOR_COMPILER_OPTIONS).replace(\n /[^/\\\\]+$/,\n fileName,\n ),\n );\n if (libContent !== undefined) {\n return ts.createSourceFile(\n fileName,\n libContent,\n ts.ScriptTarget.ESNext,\n true,\n ts.ScriptKind.TS,\n );\n }\n return undefined;\n },\n getDefaultLibFileName() {\n return defaultLibName;\n },\n writeFile() {\n // no-op — noEmit\n },\n getCurrentDirectory() {\n return '/';\n },\n getCanonicalFileName(f) {\n return f;\n },\n useCaseSensitiveFileNames() {\n return true;\n },\n getNewLine() {\n return '\\n';\n },\n fileExists(f) {\n if (f === VIRTUAL_DTS_PATH) return true;\n return ts.sys.fileExists(f);\n },\n readFile(f) {\n if (f === VIRTUAL_DTS_PATH) return dtsContent;\n return ts.sys.readFile(f);\n },\n };\n\n const program = ts.createProgram(\n [VIRTUAL_DTS_PATH],\n EXTRACTOR_COMPILER_OPTIONS,\n host,\n );\n const checker = program.getTypeChecker();\n const parsed = program.getSourceFile(VIRTUAL_DTS_PATH);\n if (parsed === undefined) {\n return undefined;\n }\n\n const requested = new Set(names);\n\n // True when a symbol's declaration originates from the wrapper's own\n // `.d.ts`. Only THESE named types get structurally expanded — types\n // from the TS DOM lib (`HTMLDivElement`), `@ggui-ai/gadgets`\n // (`GadgetHookResult`), or any external package keep their name,\n // because (a) the LLM already knows DOM / ggui types and (b)\n // expanding `HTMLDivElement` would dump hundreds of DOM members into\n // the prompt.\n function isWrapperLocal(symbol: ts.Symbol | undefined): boolean {\n const decls = symbol?.getDeclarations();\n if (decls === undefined) return false;\n return decls.some((d) => d.getSourceFile().fileName === VIRTUAL_DTS_PATH);\n }\n\n // Render a single `ts.Type` as a self-contained TS type expression.\n //\n // The TS node builder keeps a type's NAME whenever that name is\n // reachable in the program — for a `.d.ts` whose option/value types\n // are `export interface`s, that means the printed signature ends up\n // full of `LeafletMapOptions` references the LLM cannot resolve. To\n // produce a prompt-ready, self-contained signature we structurally\n // expand WRAPPER-LOCAL named object types one level: enumerate the\n // apparent properties and render each property's type (recursively,\n // depth-bounded). Non-local named types, primitives, unions, arrays,\n // tuples, and anonymous objects keep `typeToString`'s rendering.\n const MAX_DEPTH = 4;\n function renderType(t: ts.Type, depth: number): string {\n const plain = (): string =>\n checker.typeToString(t, undefined, ts.TypeFormatFlags.NoTruncation);\n\n // Bail to the plain stringifier once we hit the depth cap so a\n // cyclic / deeply-nested type can't blow the stack.\n if (depth >= MAX_DEPTH) return plain();\n\n // `boolean` is internally `true | false` — `isUnion()` is true for\n // it. Catch it before union-splitting so it prints as `boolean`.\n if ((t.getFlags() & ts.TypeFlags.Boolean) !== 0) return 'boolean';\n\n // Union types (e.g. `LeafletMapOptions | undefined` from an\n // optional param) — recurse into each constituent so a wrapper-\n // local named object member still expands structurally.\n if (t.isUnion()) {\n return t.types.map((member) => renderType(member, depth)).join(' | ');\n }\n // Intersections — same treatment.\n if (t.isIntersection()) {\n return t.types.map((member) => renderType(member, depth)).join(' & ');\n }\n\n const symbol = t.getSymbol() ?? t.aliasSymbol;\n\n // Callable types (e.g. `containerRef: (el) => void`) — render the\n // first call signature inline.\n const callSigs = t.getCallSignatures();\n if (callSigs.length > 0) {\n const cs = callSigs[0]!;\n const params = cs\n .getParameters()\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? checker.getTypeOfSymbolAtLocation(p, decl)\n : checker.getDeclaredTypeOfSymbol(p);\n const optional =\n decl !== undefined &&\n ts.isParameter(decl) &&\n (decl.questionToken !== undefined ||\n decl.initializer !== undefined);\n return `${p.getName()}${optional ? '?' : ''}: ${renderType(pType, depth + 1)}`;\n })\n .join(', ');\n const ret = renderType(cs.getReturnType(), depth + 1);\n return `(${params}) => ${ret}`;\n }\n\n const isObject = (t.getFlags() & ts.TypeFlags.Object) !== 0;\n const isArrayOrTuple =\n checker.isArrayType(t) || checker.isTupleType(t);\n\n // Generic instantiation of a non-local type (e.g.\n // `GadgetHookResult<LeafletMapValue>`) — keep the outer name (the\n // LLM knows the ggui types) but recurse into the type arguments so\n // a nested wrapper-local type still expands.\n const typeArgs = (t as ts.TypeReference).typeArguments;\n if (\n symbol !== undefined &&\n isObject &&\n !isArrayOrTuple &&\n !isWrapperLocal(symbol) &&\n typeArgs !== undefined &&\n typeArgs.length > 0\n ) {\n const args = typeArgs.map((a) => renderType(a, depth + 1)).join(', ');\n return `${symbol.getName()}<${args}>`;\n }\n\n // Wrapper-local named object — expand its property shape inline.\n if (\n symbol !== undefined &&\n isObject &&\n !isArrayOrTuple &&\n isWrapperLocal(symbol)\n ) {\n const props = checker.getPropertiesOfType(t);\n if (props.length > 0) {\n const body = props\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? checker.getTypeOfSymbolAtLocation(p, decl)\n : checker.getDeclaredTypeOfSymbol(p);\n const optional = (p.getFlags() & ts.SymbolFlags.Optional) !== 0;\n return `${p.getName()}${optional ? '?' : ''}: ${renderType(pType, depth + 1)}`;\n })\n .join('; ');\n return `{ ${body} }`;\n }\n }\n\n return plain();\n }\n\n // The exported binding may surface as either:\n // - `export declare const useLeafletMap: GguiGadget<...>` — a\n // variable statement, or\n // - `export declare function useLeafletMap(...): ...` — a function\n // declaration, or\n // - `export { useLeafletMap } from '...'` — a re-export.\n // The module-symbol export table covers all three uniformly, so we\n // walk the module symbol's exports rather than top-level statements.\n const moduleSymbol = checker.getSymbolAtLocation(parsed);\n const exportSymbols: ts.Symbol[] =\n moduleSymbol !== undefined ? checker.getExportsOfModule(moduleSymbol) : [];\n\n const signaturesByName = new Map<string, readonly ts.Signature[]>();\n for (const symbol of exportSymbols) {\n const name = symbol.getName();\n if (!requested.has(name)) continue;\n if (signaturesByName.has(name)) continue;\n\n // Resolve aliases (re-exports) so we read the real declaration.\n const resolved =\n (symbol.flags & ts.SymbolFlags.Alias) !== 0\n ? checker.getAliasedSymbol(symbol)\n : symbol;\n\n const declarations = resolved.getDeclarations();\n if (declarations === undefined || declarations.length === 0) continue;\n const declaration = declarations[0]!;\n\n const type = checker.getTypeOfSymbolAtLocation(resolved, declaration);\n const callSignatures = type.getCallSignatures();\n if (callSignatures.length === 0) continue;\n\n signaturesByName.set(name, callSignatures);\n }\n\n return { checker, renderType, signaturesByName };\n}\n\n/**\n * Print one call signature as a self-contained `(params) => ret`\n * expression.\n */\nfunction printCallSignature(sig: ts.Signature, ctx: ExtractorContext): string {\n const params = sig\n .getParameters()\n .map((p) => {\n const decl = p.valueDeclaration ?? p.declarations?.[0];\n const pType =\n decl !== undefined\n ? ctx.checker.getTypeOfSymbolAtLocation(p, decl)\n : ctx.checker.getDeclaredTypeOfSymbol(p);\n const optional =\n decl !== undefined &&\n ts.isParameter(decl) &&\n (decl.questionToken !== undefined || decl.initializer !== undefined);\n return `${p.getName()}${optional ? '?' : ''}: ${ctx.renderType(pType, 0)}`;\n })\n .join(', ');\n const ret = ctx.renderType(sig.getReturnType(), 0);\n return `(${params}) => ${ret}`.trim();\n}\n\n/**\n * Render a function component's props — the first parameter's type,\n * structurally expanded into a self-contained object type. A\n * zero-parameter component yields `{}`. Returns `undefined` when the\n * expander bottoms out on an unresolvable token.\n */\nfunction printComponentProps(\n sig: ts.Signature,\n ctx: ExtractorContext,\n): string | undefined {\n const params = sig.getParameters();\n // A zero-parameter component takes no props.\n if (params.length === 0) return '{}';\n const propsParam = params[0]!;\n const decl = propsParam.valueDeclaration ?? propsParam.declarations?.[0];\n const propsType =\n decl !== undefined\n ? ctx.checker.getTypeOfSymbolAtLocation(propsParam, decl)\n : ctx.checker.getDeclaredTypeOfSymbol(propsParam);\n const rendered = ctx.renderType(propsType, 0);\n // A surviving virtual-file qualifier means the structural expander\n // bottomed out on something it couldn't inline — drop it rather than\n // feed the LLM an unresolvable `import(\"/__gadget__\")` token.\n if (rendered.length === 0 || rendered.includes('import(\"')) return undefined;\n return rendered;\n}\n\n/**\n * Print the inferred call signature of every requested HOOK found in\n * the supplied wrapper `.d.ts` string.\n *\n * For each exported declaration whose name matches a requested hook,\n * the checker's callable signature is printed with structural-fallback\n * so wrapper-specific named types expand to their structural form — the\n * resulting string is self-contained and safe to drop into a prompt. A\n * hook declared with multiple overloads renders each, joined with ` | `.\n *\n * Hooks that aren't found, or that resolve to a value with no callable\n * signature, are omitted from the result (no throw) — the caller is\n * expected to render a `Type:` line only for hooks that resolved.\n *\n * Memoized on `(dtsContent, hookNames)`.\n */\nexport function extractCallSignaturesFromDts(\n dtsContent: string,\n hookNames: readonly string[],\n): CallSignatureMap {\n if (hookNames.length === 0 || dtsContent.trim().length === 0) {\n return {};\n }\n\n const cacheKey = `${dtsContent}\u0000${[...hookNames].sort().join(',')}`;\n const cached = callSignatureCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const result: CallSignatureMap = {};\n const ctx = buildExtractorContext(dtsContent, hookNames);\n if (ctx === undefined) {\n callSignatureCache.set(cacheKey, result);\n return result;\n }\n\n for (const [name, signatures] of ctx.signaturesByName) {\n // A hook declared with multiple overloads renders ALL of them,\n // joined as a union of function types. A surviving virtual-file\n // qualifier means the structural expander bottomed out on something\n // it couldn't inline — drop that overload rather than feed the LLM\n // an unresolvable `import(\"/__gadget__\")` token.\n const printed = signatures\n .map((sig) => printCallSignature(sig, ctx))\n .filter((s) => s.length > 0 && !s.includes('import(\"'))\n .join(' | ');\n if (printed.length > 0) {\n result[name] = printed;\n }\n }\n\n callSignatureCache.set(cacheKey, result);\n return result;\n}\n\n/**\n * Print the props-object shape of every requested COMPONENT found in\n * the supplied wrapper `.d.ts` string (GG.8.5).\n *\n * A function component's props are its first parameter's type. The\n * type is structurally expanded the same way hook signatures are, so\n * the printed value (`{ data: …; height?: number }`) is self-contained\n * and prompt-ready — the code-gen prompt renders it as a `Props:` line\n * so the LLM knows the JSX attributes of `<Component … />`.\n *\n * Components not found, or that resolve to a non-callable value, are\n * omitted (no throw). Memoized on `(dtsContent, componentNames)`.\n */\nexport function extractComponentPropsFromDts(\n dtsContent: string,\n componentNames: readonly string[],\n): ComponentPropsMap {\n if (componentNames.length === 0 || dtsContent.trim().length === 0) {\n return {};\n }\n\n const cacheKey = `${dtsContent}\u0000${[...componentNames].sort().join(',')}`;\n const cached = componentPropsCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n const result: ComponentPropsMap = {};\n const ctx = buildExtractorContext(dtsContent, componentNames);\n if (ctx === undefined) {\n componentPropsCache.set(cacheKey, result);\n return result;\n }\n\n for (const [name, signatures] of ctx.signaturesByName) {\n // A component is single-signature by convention — use the first.\n const first = signatures[0];\n if (first === undefined) continue;\n const props = printComponentProps(first, ctx);\n if (props !== undefined) {\n result[name] = props;\n }\n }\n\n componentPropsCache.set(cacheKey, result);\n return result;\n}\n","// packages/ui-gen/src/boilerplate/system-prompt.ts\n//\n// System-prompt skeleton for the coding agent. Deterministic assembly;\n// injection points for funnel content (pitfalls) and for large content\n// blocks that are OWNED BY OTHER PACKAGES (design-system docs,\n// primitives doc, wire doc). Those blocks travel as strings so ui-gen\n// doesn't silently pull in megabytes of auto-generated content from\n// `@ggui-ai/design` / `@ggui-ai/wire` that those packages authoritatively\n// own.\n//\n// The only content this skeleton carries by default is the coding-\n// criteria summary (`buildCodingCriteriaSummary()` over the open\n// `CRITERIA` single-source-of-truth). Everything else defaults to empty\n// string — the skeleton still renders cleanly for OSS callers who don't\n// pass doc blocks.\n\nimport { resolveAppGadgets } from \"@ggui-ai/protocol\";\nimport type {\n GadgetDescriptor,\n GadgetExport,\n GadgetHookExport,\n GadgetComponentExport,\n} from \"@ggui-ai/protocol\";\nimport { buildCodingCriteriaSummary } from \"../evaluation/types-public.js\";\nimport {\n extractCallSignaturesFromDts,\n extractComponentPropsFromDts,\n} from \"../internal/extract-call-signatures.js\";\n\n/** Narrow a {@link GadgetExport} to its hook variant by field presence. */\nfunction isHookExport(exp: GadgetExport): exp is GadgetHookExport {\n return \"hook\" in exp;\n}\n\n/** Narrow a {@link GadgetExport} to its component variant by field presence. */\nfunction isComponentExport(exp: GadgetExport): exp is GadgetComponentExport {\n return \"component\" in exp;\n}\n\nexport interface SystemPromptInputs {\n /** The user's original request. */\n userRequest: string;\n /** Shell layout mode. */\n shellType?: string;\n /** Target screen size. */\n screen?: string;\n /** Axis-conditioned prompt fragments (from `compose()`). */\n axisDelta?: string;\n /**\n * Funnel content injection — env-gated pitfalls block rendered by the\n * caller. OSS default: `\"\"`. The hosted runtime's core wrapper passes\n * `renderPitfallsBlock()` which honors `GGUI_PITFALLS` /\n * `GGUI_NEW_PITFALLS` env vars.\n */\n pitfallsBlock?: string;\n /**\n * Pre-rendered criteria block. Defaults to\n * `buildCodingCriteriaSummary()` over the open CRITERIA registry.\n * Callers that want to override (e.g. a trimmed summary for fast mode)\n * pass their own string.\n */\n criteriaBlock?: string;\n /** Hand-written design-token reference. Owned by `@ggui-ai/design`. */\n designSystemDocs?: string;\n /** Auto-generated primitives reference. Owned by `@ggui-ai/design`. */\n primitivesDoc?: string;\n /** Auto-generated wire-hooks reference. Owned by `@ggui-ai/wire`. */\n wireDoc?: string;\n /**\n * Per-app gadget catalog. When provided, replaces the default\n * `STDLIB_GADGETS`-only table in the\n * `clientCapabilities — registered catalog` section so registered\n * third-party gadgets (Leaflet, Mapbox, Stripe, …) instruct the\n * code-gen LLM with the same teaching text the synth + decision LLMs\n * see.\n *\n * When omitted, the section renders the standard-library seed (the\n * first-party browser-capability hooks).\n */\n appGadgets?: readonly GadgetDescriptor[];\n /**\n * A `package -> .d.ts content` map for THIRD-PARTY gadget wrappers\n * (the render handler parallel-fetches each non-stdlib gadget's\n * `.d.ts`). When a gadget's `package` has an entry here,\n * `formatGadgetsSection` renders a `**Type**:` line carrying the\n * hook's extracted call signature — the LLM sees the real call shape\n * of a wrapper it cannot otherwise know.\n *\n * Stdlib gadgets (`@ggui-ai/gadgets`) get NO `Type:` line — they\n * already carry an `example` and are well-known; extracting stdlib\n * signatures is deliberately out of scope. Omit for STDLIB-only\n * callers (the section stays byte-identical).\n */\n gadgetTypes?: Readonly<Record<string, string>>;\n}\n\nconst SHELL_DESCRIPTIONS: Record<string, string> = {\n chat: \"inline component inside ChatShell message bubble (~400px wide, compact)\",\n fullscreen: \"full viewport, responsive layout\",\n spatial: \"floating AR/VR panel (~600px, touch-friendly)\",\n};\n\nconst SCREEN_DESCRIPTIONS: Record<string, string> = {\n mobile: \"single column, large touch targets\",\n tablet: \"flexible columns, medium spacing\",\n desktop: \"multi-column, dense layout\",\n universal: \"responsive across all breakpoints\",\n};\n\n/**\n * Render the `clientCapabilities — registered catalog` table from the\n * per-app gadget catalog. Each registered gadget renders one row\n * with hook + permission + the `description`-or-`usage` field as the\n * \"what it does\" column. Permission falls back to `(none)` when the\n * descriptor doesn't declare one.\n *\n * The table is built dynamically from the catalog so all three triad\n * surfaces (synth contract authoring, decision LLM, code-gen system\n * prompt) instruct the model uniformly about which gadgets are\n * available.\n *\n * Rows are emitted in catalog order. An empty catalog produces a hint\n * to seed it via `app.gadgets` rather than an empty table.\n *\n * When `gadgetTypes` carries a `.d.ts` for a gadget's `package`, a\n * `**Type**:` block is appended after the table with one line per\n * THIRD-PARTY gadget: `\\`<hook>\\`: <extracted call signature>`. The\n * signature is extracted from the wrapper's `.d.ts` via\n * `extractCallSignaturesFromDts`. Stdlib gadgets (`@ggui-ai/gadgets`)\n * get NO `Type:` line — they already carry an `example` and are\n * well-known. A hook whose signature can't be extracted is silently\n * skipped.\n *\n * Pure helper. Exported for unit testing.\n */\nexport function formatGadgetsSection(\n appGadgets: readonly GadgetDescriptor[],\n gadgetTypes?: Readonly<Record<string, string>>,\n): string {\n if (appGadgets.length === 0) {\n return [\n \"When the contract declares a `clientCapabilities.gadgets` entry,\",\n \"the hook MUST be one the operator has registered on\",\n \"`App.gadgets`. The default ggui server seeds the 7\",\n \"first-party STDLIB hooks; this server has none registered (the\",\n \"operator's `ggui.json#app.gadgets` is empty). Don't\",\n \"declare `clientCapabilities.gadgets` until a hook is registered.\",\n ].join(\" \");\n }\n // The LLM DIRECT-IMPORTS gadget hooks. The boilerplate emits\n // one combined `import { hookA, hookB } from '<package>'` line per\n // registered gadget package, above a `DO NOT EDIT` banner. The\n // `Package` column below IS the import specifier — it is load-bearing.\n //\n // Each `GadgetDescriptor` is a PACKAGE with `exports[]`;\n // flatten to the hook exports (one table row per hook), carrying\n // package identity through for the Package column.\n const hookExports = appGadgets.flatMap((descriptor) =>\n descriptor.exports\n .filter(isHookExport)\n .map((exp) => ({ exp, descriptor })),\n );\n // Component exports get their own table + render teaching.\n const componentExports = appGadgets.flatMap((descriptor) =>\n descriptor.exports\n .filter(isComponentExport)\n .map((exp) => ({ exp, descriptor })),\n );\n const header =\n \"When the contract declares a hook gadget on `clientCapabilities.gadgets`, the hook MUST be one of the registered hooks below. The boilerplate has already emitted a direct import per gadget package — `import { <hook>, … } from '<package>'` — above a `// DO NOT EDIT` banner. KEEP those imports exactly; they are the runtime-resolution anchor and self_check rejects the code if one disappears. Import each STDLIB hook from `@ggui-ai/gadgets`; import each third-party hook from the package named in the `Package` column. DO NOT invent your own import paths. Available registered hooks:\";\n const tableHead = [\n \"| Hook | Package (import from here) | Permission | What it does |\",\n \"| --------------------- | ---------------------------------- | ------------------ | ------------------------------------------- |\",\n ];\n const rows = hookExports.map(({ exp, descriptor }) => {\n const hookCol = `\\`${exp.hook}\\``.padEnd(21, \" \");\n const pkgCol = `\\`${descriptor.package}\\``.padEnd(34, \" \");\n const permCol = exp.permission\n ? `\\`${exp.permission}\\``.padEnd(18, \" \")\n : \"(none)\".padEnd(18, \" \");\n const what = (exp.usage ?? exp.description ?? \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 80);\n return `| ${hookCol} | ${pkgCol} | ${permCol} | ${what.padEnd(43, \" \")} |`;\n });\n\n // `**Type**:` lines for THIRD-PARTY gadgets. A gadget is third-party\n // when its `package` has a `.d.ts` entry in `gadgetTypes` (stdlib\n // `@ggui-ai/gadgets` is never in the map). The LLM can't know a\n // third-party wrapper's call shape; the extracted signature gives it\n // the exact param/return type to code against.\n // Stdlib gadgets get nothing here by design — `example` covers them.\n const typeLines: string[] = [];\n if (gadgetTypes !== undefined) {\n for (const { exp, descriptor } of hookExports) {\n const dts = gadgetTypes[descriptor.package];\n if (dts === undefined) continue; // stdlib or no `.d.ts` fetched.\n const signatures = extractCallSignaturesFromDts(dts, [exp.hook]);\n const sig = signatures[exp.hook];\n if (sig === undefined) continue; // graceful — couldn't extract.\n typeLines.push(`- \\`${exp.hook}\\`: \\`${sig}\\``);\n }\n }\n const typeBlock =\n typeLines.length > 0\n ? [\n \"\",\n \"**Type** (third-party gadgets — call signature from the wrapper's published `.d.ts`):\",\n \"\",\n ...typeLines,\n ]\n : [];\n\n const hookSection =\n hookExports.length > 0\n ? [header, \"\", ...tableHead, ...rows, ...typeBlock].join(\"\\n\")\n : \"\";\n\n // Component gadgets: their own table + RENDER (not call)\n // teaching. A component export is mounted as a JSX element; the LLM\n // never invokes it like a hook.\n const componentRows = componentExports.map(({ exp, descriptor }) => {\n const compCol = `\\`${exp.component}\\``.padEnd(21, \" \");\n const pkgCol = `\\`${descriptor.package}\\``.padEnd(34, \" \");\n const what = (exp.usage ?? exp.description ?? \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 80);\n return `| ${compCol} | ${pkgCol} | ${what.padEnd(53, \" \")} |`;\n });\n\n // `**Props**:` lines for THIRD-PARTY component gadgets. The\n // props-object shape is extracted from the wrapper's published\n // `.d.ts` so the LLM knows the exact JSX attributes of `<X … />`. A\n // component whose `package` has no `.d.ts` entry is skipped\n // (graceful — the `example` still covers it).\n const componentPropsLines: string[] = [];\n if (gadgetTypes !== undefined) {\n for (const { exp, descriptor } of componentExports) {\n const dts = gadgetTypes[descriptor.package];\n if (dts === undefined) continue; // stdlib or no `.d.ts` fetched.\n const propsMap = extractComponentPropsFromDts(dts, [exp.component]);\n const props = propsMap[exp.component];\n if (props === undefined) continue; // graceful — couldn't extract.\n componentPropsLines.push(`- \\`${exp.component}\\`: \\`${props}\\``);\n }\n }\n const componentPropsBlock =\n componentPropsLines.length > 0\n ? [\n \"\",\n \"**Props** (third-party component gadgets — prop shape from the wrapper's published `.d.ts`):\",\n \"\",\n ...componentPropsLines,\n ]\n : [];\n\n const componentSection =\n componentExports.length > 0\n ? [\n \"When the contract declares a component gadget on `clientCapabilities.gadgets`, the export is a COMPONENT — RENDER it as a JSX element (`<X … />`) in the tree you return. Do NOT call it like a hook. The boilerplate has already emitted a direct import per gadget package — `import { <Component>, … } from '<package>'` — above a `// DO NOT EDIT` banner. KEEP those imports exactly; they are the runtime-resolution anchor and self_check rejects the code if one disappears. Import each component from the package named in the `Package` column. Available registered components:\",\n \"\",\n \"| Component | Package (import from here) | What it does |\",\n \"| --------------------- | ---------------------------------- | ----------------------------------------------------- |\",\n ...componentRows,\n ...componentPropsBlock,\n ].join(\"\\n\")\n : \"\";\n\n return [hookSection, componentSection]\n .filter((section) => section.length > 0)\n .join(\"\\n\\n\");\n}\n\n/**\n * Assemble the coding-agent system prompt. Deterministic — the only\n * variable content comes from the caller-supplied injection fields.\n */\nexport function buildSystemPrompt(inputs: SystemPromptInputs): string {\n const shell = inputs.shellType ?? \"fullscreen\";\n const scr = inputs.screen ?? \"universal\";\n const shellDesc = SHELL_DESCRIPTIONS[shell] ?? SHELL_DESCRIPTIONS.fullscreen;\n const screenDesc = SCREEN_DESCRIPTIONS[scr] ?? SCREEN_DESCRIPTIONS.universal;\n\n const criteriaBlock = inputs.criteriaBlock ?? buildCodingCriteriaSummary();\n const pitfallsBlock = inputs.pitfallsBlock ?? \"\";\n const designSystemDocs = inputs.designSystemDocs ?? \"\";\n const primitivesDoc = inputs.primitivesDoc ?? \"\";\n const wireDoc = inputs.wireDoc ?? \"\";\n // Default to the standard-library seed when no per-app catalog is\n // supplied. Callers that resolve `App.gadgets` thread it through here.\n //\n // `gadgetTypes` carries third-party wrapper `.d.ts` content;\n // `formatGadgetsSection` renders a `Type:` line per third-party\n // gadget from it. When omitted, no `Type:` lines are rendered.\n const gadgetsSection = formatGadgetsSection(\n resolveAppGadgets(inputs.appGadgets),\n inputs.gadgetTypes,\n );\n\n const axisSection =\n inputs.axisDelta && inputs.axisDelta.trim().length > 0\n ? `\\n## Shape Guidance\\n${inputs.axisDelta}\\n`\n : \"\";\n\n return `You are ggui's UI builder. You receive a typed boilerplate and fill it in using apply_changes.\n\n## Your Task\n${inputs.userRequest}\n\n## Rendering Context\n- **Shell**: \\`${shell}\\` — ${shellDesc}\n- **Screen**: \\`${scr}\\` — ${screenDesc}\n\n## How It Works\n1. Read the boilerplate — typed Props, wire hooks, and layout container are pre-configured\n2. Respond with one apply_changes call — add state, helpers, and JSX\n3. If compilation or evaluation fails, you'll get errors to fix in the next turn\n\n${criteriaBlock}\n${axisSection}\n## Protocol Notes\nThe boilerplate pre-declares every wire hook the contract requires (\\`useAction\\`, \\`useStream\\`, \\`useGguiContext\\`, plus capability hooks from \\`@ggui-ai/gadgets\\` when the contract declares \\`clientCapabilities\\`). Three rules:\n1. **Do NOT delete any pre-declared hook.** \\`self_check\\` fails with \\`wire_preservation:<kind>:<name>\\` if you remove one.\n2. **Consume every hook binding** somewhere in the component — in JSX, a callback, or an effect. Unused bindings fail lint with \\`no-unused-vars\\`.\n3. **Do NOT invent new wire calls.** Every \\`useAction('X')\\`, \\`useStream('X')\\`, \\`useGguiContext('X')\\` etc. MUST correspond to a declared entry on the contract. Calling one that isn't declared fails \\`self_check\\` with \\`wire_undeclared:<kind>:<name>\\` because the runtime has no Context/registration for it and would throw at first paint. If you need a new wire surface, that's a contract authoring step the agent owns — your job is to honor what's declared.\n\nRenaming a binding is fine — the wiring is the string-literal argument, not the identifier.\n\n## Contract surface — four specs + two catalogs\n\nA \\`DataContract\\` declares everything a GguiSession exchanges with the outside world. **Four typed specs** for the four data-flow directions, **two reference catalogs** for tool / hook lookups:\n\n| Surface | Direction | Role |\n| -------------------- | -------------------------- | -------------------------------------------------------------------- |\n| \\`propsSpec\\` | server → UI (one-shot) | Initial render values delivered once at \\`ggui_render\\` |\n| \\`streamSpec\\` | agent → UI (many) | Typed channels for live updates via \\`ggui_emit\\` |\n| \\`actionSpec\\` | UI → agent (events) | Discrete events driving the agent's next turn (consumed via \\`ggui_consume\\`) |\n| \\`contextSpec\\` | UI → server (state mirror) | UI state the agent observes between turns |\n| \\`agentCapabilities.tools\\` | catalog | Tools the contract references via \\`actionSpec[*].nextStep\\` and \\`streamSpec[*].source.tool\\` |\n| \\`clientCapabilities.gadgets\\` | catalog | Browser-capability gadget hooks the component code mounts (e.g., \\`useGeolocation\\`) |\n\n**Placement rule for inbound specs**: actions drive turns; context observes state. There is no third category.\n\n**Data vs behavior**: the contract describes data flow; the component code describes behavior. Scroll, focus, toast, animation, clipboard write — all component code, never contract fields.\n\n## Defensive coding for absent / late-arriving data\n\nProps arrive at mount and may be partial on first render; later prop changes reach the SAME mounted component via \\`ggui_amend\\` (in-place repaint) on the live channel. Stream channels start empty and fill over time. Context slots start at their declared default (often \\`null\\`). **Never assume a field exists before you read it.**\n\n- **Array iteration**: always default to \\`[]\\` before \\`.map\\`/\\`.filter\\`/\\`.length\\`. Use \\`(props.items ?? []).map(...)\\` not \\`props.items.map(...)\\`. Same for stream.all, stream.latest, etc.\n- **Object access**: optional-chain through nested fields. \\`props.user?.name ?? 'Anonymous'\\` not \\`props.user.name\\`.\n- **Number ops**: default before arithmetic. \\`(props.count ?? 0) + 1\\` not \\`props.count + 1\\`.\n- **Stream latest**: \\`useStream\\` returns \\`{latest: T | null, all: T[], isComplete: boolean}\\`. The default \\`all\\` is \\`[]\\` so it's safe to map; \\`latest\\` is null until the first frame arrives — guard before reading \\`.foo\\`.\n- **Stream reconciliation**: when a stream event carries an \\`action\\` discriminant (e.g. \\`create | move | edit | delete\\`), the channel is a CRUD feed — your handler MUST branch on EVERY value: append on \\`create\\`, drop on \\`delete\\`, replace-by-id on \\`move\\` / \\`edit\\`. Merging only the \"edit\" case silently loses created and deleted items. Reconcile into the SAME state that seeds from \\`props\\` (e.g. \\`useState(() => props.tasks ?? [])\\`) so the seed data and the live feed render as one list — and handle an event whose id is not yet present (a \\`create\\` for an unknown item) by inserting it, not ignoring it.\n- **Props re-sync on repaint**: props the agent owns are the source of truth for display — prefer rendering DIRECTLY from \\`props\\` (controlled, no local copy). When local optimistic state genuinely needs a prop seed (a click bumps a count before the agent confirms), it MUST re-sync on prop change — \\`useEffect(() => setCount(props.count ?? 0), [props.count])\\` — or a \\`ggui_amend\\` repaint applies the new props while the display keeps the stale local value. BAD: \\`const [count, setCount] = useState(props.count ?? 0)\\` alone. GOOD: the same seed + the one-line re-sync effect.\n- **Loading state**: while data is still absent, render \\`<Skeleton>\\` placeholders — never a blank screen. \\`<Skeleton variant=\"text\" />\\` for a text line, \\`variant=\"circle\"\\` for an avatar slot, default \\`rect\\` for a block.\n- **Empty state**: when a list or results array is empty, render \\`<EmptyState title=\"…\" description=\"…\" />\\` — a region that renders nothing when empty looks broken to the user.\n\nUnhandled \\`Cannot read properties of undefined\\` errors trip the iframe error boundary and the user sees \"Something went wrong\" — a regression class the runtime can't recover from.\n\n## Picking the right primitive for user gestures\n\nChoose by what the user is DOING, not where the result goes — the runtime handles the routing.\n\n| Gesture intent | LLM writes | Notes |\n| -------------- | ---------- | ----- |\n| Fire a server-side action | \\`useAction(name)\\` + call \\`dispatch(name, payload)\\` | Every action is agent-routed. The runtime emits an event on \\`ggui_consume\\`; the agent reacts on its next turn. If the contract entry declares \\`nextStep: 'X'\\`, that names the tool the agent SHOULD call next — advisory hint forwarded as event metadata. |\n| Surface state to the agent's context | the auto-generated \\`setSlotName\\` setter (from the boilerplate's \\`useGguiContext\\` line) | The runtime owns useState + Provider; the boilerplate emits one \\`const [slot, setSlot] = useGguiContext<T>('slot')\\` line per declared \\`contextSpec\\` slot. Write plain JSX, no \\`useState\\`, no Provider wrap. Every value change auto-flows to the host LLM (debounced). One-way client → agent — see \"Observable state via \\`contextSpec\\`\" below. |\n| Use a browser capability (camera, mic, geolocation, clipboard, file picker, notifications) | call the hook the contract declared, e.g., \\`const loc = useGeolocation();\\` and \\`await loc.start()\\` | The contract's \\`clientCapabilities.gadgets\\` declares which gadget exports the UI uses. The hook implementations live in \\`@ggui-ai/gadgets\\` (or a third-party package named in the \\`Package\\` column). Read \\`status\\` (\"idle\" / \"prompting\" / \"active\" / \"completed\" / \"denied\" / \"error\") to gate UI, and thread the resolved \\`value\\` into a contextSpec slot or actionSpec payload if the agent needs to see it. |\n| Open external link | Plain \\`<a href=\"https://...\">\\` (or \\`target=\"_blank\"\\`) | External cross-origin clicks are intercepted and routed through the host (security warnings, app-internal navigation, audit). Same-origin links and \\`#fragment\\` jumps stay native. |\n| Toggle fullscreen / chrome | Plain \\`el.requestFullscreen()\\` / \\`document.exitFullscreen()\\` | The native browser API is intercepted; the host adjusts iframe chrome accordingly. Returns a resolved promise so \\`.then()\\` / \\`await\\` chains don't break. |\n\nEvery gesture fires a uniform server-side audit envelope (\\`ggui_runtime_submit_action\\`) so operators see all three patterns in RenderInspector with the same shape.\n\n**Don't import wire hooks for link / display-mode.** \\`useAction\\` is the only wire hook for user gestures; links and fullscreen use plain HTML / browser APIs.\n\n**All actions are agent-routed.** Every action emits an event the agent reacts to on its next turn via \\`ggui_consume\\`. The optional \\`nextStep: '<tool>'\\` field on an \\`actionSpec\\` entry is a HINT naming the tool the agent SHOULD call next — the contract author's recommendation, NOT a binding directive. The agent decides whether to honor it. If you want to declare a tool catalog entry the contract references, add it to \\`agentCapabilities.tools[<name>]\\` with input/output schemas; the cross-ref linter rejects dangling \\`nextStep\\` values that don't resolve to a declared catalog entry.\n\n## Making a primitive interactive — \\`as={Trait}\\`\n\nStructural primitives (\\`Box\\`, \\`Stack\\`, \\`Row\\`, \\`Card\\`) have NO \\`onClick\\` by default. Add interactivity with the \\`as\\` prop — a trait, not a wrapper:\n\n\\`\\`\\`tsx\n<Card as={Clickable} onClick={() => dispatch('select', { id })}\n hoverStyle={{ boxShadow: 'var(--ggui-shape-shadow-lg)' }}>…</Card>\n\\`\\`\\`\n\n- \\`as={Clickable}\\` → \\`onClick\\` + keyboard activation (Enter/Space) + \\`role=\"button\"\\` + \\`hoverStyle\\`/\\`activeStyle\\`/\\`cursor\\`.\n- \\`as={Hoverable}\\` → \\`hoverStyle\\` only (no click). \\`as={Pressable}\\` → \\`onPress\\` + \\`pressStyle\\`.\n\n\\`as={Trait}\\` is a PROP — it does NOT re-nest the JSX. Never write \\`<Clickable>…</Clickable>\\` around a primitive; put \\`as={Clickable}\\` on the primitive itself. The trait carries the keyboard + ARIA wiring, so don't hand-write \\`onKeyDown\\` / \\`role\\`. Trait components (\\`Clickable\\`, \\`Hoverable\\`, \\`Pressable\\`) import from \\`@ggui-ai/design\\` like everything else — the boilerplate already imports them.\n\n**Semantic components are already interactive** — \\`Button\\` (\\`onClick\\`), \\`Link\\` (\\`href\\`), \\`Input\\` / \\`Select\\` (\\`onChange\\`). Use their own props; never put \\`as\\` on them. \\`Text\\` picks its element with \\`is\\` (\\`<Text is=\"label\">\\`), not \\`as\\`.\n\n**Never nest two interactive elements.** Interactive content MUST NOT contain other interactive content — a gesture on the inner control bubbles to the outer one and fires BOTH handlers (one user click → the action dispatched twice). Do NOT put a \\`Button\\`, \\`Checkbox\\`, \\`Input\\`, \\`Select\\`, \\`Link\\`, or another \\`as={Clickable}\\` primitive inside a \\`Card\\` / \\`Box\\` / \\`Row\\` / \\`Stack\\` that is itself \\`as={Clickable}\\`. Wire each \\`useAction\\` callback to exactly ONE surface: EITHER the whole card is the trigger (interactive container, no interactive children) OR an inner control is the trigger (plain container, no \\`as={Clickable}\\`) — never both. A row with a checkbox: put the action on the \\`Checkbox onChange\\` and leave the row plain.\n\n**\\`Text\\` / \\`Heading\\` accept NO event handlers and NO \\`as\\` — only \\`style\\` / \\`className\\` plus their own typed props.** \\`onClick\\`, \\`onDoubleClick\\`, \\`as={Clickable}\\`, \\`color\\` are all type errors on \\`Text\\`. When the request says a label is \"clickable\", \"editable\", \"edit on click / double-click\", or \"tap to …\", do ONE of these — never put the handler on \\`Text\\`:\n\n\\`\\`\\`tsx\n// Click-to-edit a label: wrap the Text in a Clickable structural primitive.\n<Box as={Clickable} onClick={() => setEditingId(task.id)}\n style={{ cursor: 'pointer' }}>\n <Text weight=\"semibold\">{task.title}</Text>\n</Box>\n\n// Or pair the label with an explicit edit Button (clearer affordance).\n<Row gap=\"xs\" align=\"center\">\n <Text weight=\"semibold\">{task.title}</Text>\n <Button variant=\"ghost\" size=\"xs\" aria-label=\"Edit title\"\n onClick={() => setEditingId(task.id)}>Edit</Button>\n</Row>\n\n// In edit mode, swap the Text for an Input.\n{editingId === task.id\n ? <Input value={draftTitle} onChange={setDraftTitle} label=\"Task title\" />\n : <Text weight=\"semibold\">{task.title}</Text>}\n\\`\\`\\`\n\n## Anti-patterns — DO NOT WRITE\n\nThe following identifiers / shapes are RETIRED from the contract surface as of 2026-05-11. Pre-2026-05-11 examples in your training data may include them; do not reproduce. The linter / CI grep gate rejects:\n\n- \\`useWiredTool\\`, \\`useClientTool\\` — retired hooks. Replace with \\`useAction\\` (events) and the named hook from \\`@ggui-ai/gadgets\\` (browser capabilities).\n- \\`dispatch: { kind: 'tool', tool: '...' }\\` / \\`dispatch: { kind: 'agent', intendedTool: '...' }\\` — retired discriminated-union. Use the flat optional \\`nextStep?: '<tool>'\\` instead.\n- \\`mode: 'host-routed'\\` / \\`mode: 'tool'\\` — retired \\`mode\\` field. Same fix: flat \\`nextStep?\\`.\n- \\`broadcast: {...}\\` on the contract — retired top-level field. Use \\`streamSpec[channel].source: {tool, args?}\\` to declare a tool-fed channel.\n- \\`wiredTools\\` / \\`agentTools\\` (top-level) — retired catalog names. Use \\`agentCapabilities.tools\\`.\n- \\`clientTools\\` / \\`clientCapabilities.capabilities\\` — retired catalog shapes. Use \\`clientCapabilities.gadgets\\` (entries declare hooks, not RPC).\n- \\`@ggui-ai/client-tools\\` — retired package name. Import gadget hooks from \\`@ggui-ai/gadgets\\`.\n- \\`intendedTool\\` — retired. Use \\`nextStep\\` (flat).\n- \\`props: { properties: {...} }\\` as a CONTRACT field — retired. The contract field is \\`propsSpec\\` (the wire \\`props\\` field on render / update still carries VALUES).\n\n## Cross-reference rules\n\nWhen you declare a reference, also declare the catalog entry it points at:\n\n- \\`actionSpec[X].nextStep = 'fetch_inbox'\\` → \\`agentCapabilities.tools.fetch_inbox = { toolInfo: { inputSchema, description?, outputSchema? }, usage?, example? }\\` MUST exist. Cross-ref code: \\`CTR_REF_NEXT_STEP\\`.\n- \\`streamSpec[X].source.tool = 'list_messages'\\` → \\`agentCapabilities.tools.list_messages\\` MUST exist. Cross-ref code: \\`CTR_REF_STREAM_SOURCE\\`.\n- The catalog entry's schemas MUST be a superset of the referencing spec's schema. Cross-ref code: \\`CTR_SCHEMA_INCOMPAT\\`.\n\n## clientCapabilities — registered catalog\n\n${gadgetsSection}\n\nEach hook conforms to \\`GadgetHook<TOutput, TOptions>\\`: call \\`start(opts?)\\` to fire, read \\`{value, status, error, stop?}\\`. \\`status\\` walks through \\`idle → prompting → active|completed\\` or routes to \\`denied\\` / \\`error\\` on failure.\n\n3rd-party plugins (Leaflet maps, Mapbox, Stripe, Chart.js, …) are registered via \\`createGguiGadget\\` from \\`@ggui-ai/gadgets\\` and surface in this same table when the operator has added them to \\`App.gadgets\\`. Reference any registered hook by name — render validation rejects hooks not in this catalog with \\`gadget_not_registered\\`.\n\n## Observable state via \\`contextSpec\\`\n\nWhen the contract declares \\`contextSpec\\`, the boilerplate auto-generates one \\`useGguiContext\\` call per slot at the top of your component. The runtime owns the underlying \\`useState\\` and the Provider tree — **you do NOT write \\`useState\\` or any \\`<Provider>\\` wrap yourself**:\n\n\\`\\`\\`tsx\nimport { useGguiContext } from '@ggui-ai/wire';\n\nexport default function Component(props: Props) {\n // AUTO-GENERATED — do not remove or rename:\n const [currentStep, setCurrentStep] = useGguiContext<number>('currentStep');\n const [draftText, setDraftText] = useGguiContext<string>('draftText');\n\n // Plain JSX. No Provider wrap. The runtime already wrapped your\n // component in nested SingleSlotProviders before this code ran.\n return (\n <Container>\n <Text>Step {currentStep}</Text>\n <Input value={draftText} onChange={(e) => setDraftText(e.target.value)} />\n <Button onClick={() => setCurrentStep((s) => s + 1)}>Next</Button>\n </Container>\n );\n}\n\\`\\`\\`\n\nFor every declared slot you have **\\`slotName\\` + \\`setSlotName\\`** in scope:\n- **Read** the value to render: \\`<Text>Step {currentStep}</Text>\\`\n- **Write** via the setter: \\`setCurrentStep(s => s + 1)\\` (in callbacks, effects, anywhere)\n\nEvery value change is mirrored to the host LLM's context automatically (debounced, default 300ms — adjustable per-slot via \\`entry.debounceMs\\` in the contract). The agent sees the user's interaction state — drafts, current step, hover, selection — without you calling any API.\n\n**When to use the auto-generated state.** Any slot the contract declared. If \\`contextSpec.draftText\\` exists, bind \\`<Input value={draftText} onChange={e => setDraftText(e.target.value)}>\\` so the agent sees the typing live. If \\`contextSpec.currentStep\\` exists, render the step indicator from \\`currentStep\\` and bump it via \\`setCurrentStep\\` in your \"next\" callback.\n\n**When NOT to use it.** Local UI state the contract did NOT declare — \\`isDropdownOpen\\`, hover flags, animation phase, ephemeral toggles. For those, use a plain \\`useState\\` directly. The runtime ignores undeclared state.\n\n**\\`contextSpec\\` direction is one-way: client → agent.** The agent uses \\`propsSpec\\` (via \\`ggui_amend\\` for in-place repaints of this mount, or \\`ggui_update\\` when it mints a new history card) and \\`streamSpec\\` (via the live channel) to push state TO the client. Don't try to write to the agent via \\`contextSpec\\` — there is no return path.\n\n**Schema mismatches drop silently.** If you set a value that doesn't match the slot's schema (e.g. a string into a \\`{type: 'number'}\\` slot), the runtime logs a dev \\`console.warn\\` and skips the post. Make sure your setter calls produce values that match the declared shape.\n\n${pitfallsBlock}\n\n## Reference: Wire Hooks\n${wireDoc}\n\n${DESIGN_SYSTEM_GUIDANCE}\n\n### CSS Token Documentation\n${designSystemDocs}\n\n### Component Reference\n${primitivesDoc}\n`;\n}\n\n/**\n * Hand-written design-system guidance embedded in every coding-agent\n * system prompt. Lists prop-value enums, branded color strategy, and\n * responsive/parameterization rules that make a generated component\n * feel polished — the system prompt without it would only list\n * primitive *names*. Exported so `prompt-type-drift.test.ts` can\n * verify its enum claims against the auto-generated primitive catalog.\n */\nexport const DESIGN_SYSTEM_GUIDANCE = `## Imports & Component Surface\n\nImport ONLY from: \\`react\\`, \\`@ggui-ai/design\\`, \\`@ggui-ai/wire\\`. The ENTIRE design system — every primitive, component, composition and trait — is exported from the single \\`@ggui-ai/design\\` entry: \\`import { Card, Grid, Stack, Modal, Clickable } from '@ggui-ai/design'\\`. There are NO subpaths (\\`/primitives\\`, \\`/components\\`, …) — never import from them. Use the design components — DO NOT use raw HTML elements (\\`<button>\\`, \\`<input>\\`, \\`<div>\\` for layout) or Tailwind classes; those render unstyled in the iframe runtime.\n\nAvailable primitives (all from \\`@ggui-ai/design\\`):\n- Layout: Box, Container, Stack, Row, Grid, Spacer, Divider\n- Typography: Heading, Text, Link\n- Form: Button, Input, TextArea, Checkbox, Toggle, RadioGroup, Select, Slider\n- Display: Card, Alert, Badge, Avatar, Image, Icon, Progress, Spinner, Skeleton, Tooltip\n- Composite: Accordion, Tabs, Table, Toast\n\nAvailable compound components (all from \\`@ggui-ai/design\\`):\n- Autocomplete, Breadcrumb, Dropdown, EmptyState, FormField, Markdown, MarkdownInline, MenuItem, Pagination, SearchField, Stat, Stepper, Tag\n\n**Choosing between similar components** — pick by intent, don't guess:\n- **Pick from options**: one value from a short fixed list (a form field) → \\`Select\\`. Type-to-filter a long list, then pick → \\`Autocomplete\\`. A menu of actions off a button (edit / delete / …) → \\`Dropdown\\`. A search box that filters displayed content → \\`SearchField\\`.\n- **Tabular data** → \\`Table\\`. Reach for \\`DataTable\\` ONLY when you need built-in sorting / pagination / row-selection.\n- **Messaging**: an inline message in the layout flow → \\`Alert\\`. A transient popup → \\`Toast\\`. A panel listing many notifications → \\`NotificationCenter\\`.\n- **Step progress**: a wizard's step indicator → \\`Stepper\\`. NOT \\`Tabs\\` (implies free navigation), NOT \\`Progress\\` (continuous bar), NOT \\`Breadcrumb\\` (hierarchy).\n- **Containers**: width-constrain a page region → \\`Container\\`. A visually-contained surface (background + shadow + border) → \\`Card\\`. Plain grouping / spacing with no chrome → \\`Box\\`.\n\nEXACT primitive prop values (other values are silently ignored — the design system maps them to defaults):\n- \\`<Text size=\"...\">\\` — ONLY \\`xs | sm | base | lg | xl | 2xl | 3xl | 4xl\\`. For a HUGE number/temperature, use \\`<Text size=\"4xl\" weight=\"bold\">\\`. \\`caps\\` uppercases with letter-spacing — the eyebrow/overline label look is \\`<Text size=\"xs\" weight=\"semibold\" caps tone=\"muted\">\\`.\n- \\`<Text weight=\"...\">\\` — \\`normal | medium | semibold | bold\\`.\n- \\`<Text tone=\"...\">\\` — typed semantic slot. \\`default | muted | subtle | emphasized | loud | success | warning | error | info | inverse | inherit\\`. The theme decides what each tone LOOKS like — \\`muted\\` is a quiet warm grey on Claudic, a cool slate on Indigo. \\`tone\\` is the ONLY way to set Text color; the legacy \\`color=\"...\"\\` prop has been removed.\n- \\`<Heading level={1|2|3|4|5|6}>\\` — sizes are preset by level (h1 = 4xl bold, h2 = 3xl bold, h3 = 2xl semibold). Pass a number, not \\`level=\"h1\"\\`. Heading uses the same \\`tone\\` slot vocabulary as Text.\n- \\`<Icon name=\"...\" tone=\"...\">\\` / \\`<Spinner tone=\"...\">\\` / \\`<Link href=\"...\" tone=\"...\">\\` / \\`<Divider tone=\"...\">\\` — same \\`tone\\` vocabulary as Text. Default = \\`currentColor\\` (Icon), primary-tinted (Spinner / Link), outlineVariant (Divider). Use \\`tone=\"inherit\"\\` when you want the element to track the parent's foreground color (e.g. an Icon next to muted text).\n- \\`<Button variant=\"...\">\\` — \\`primary | secondary | outline | ghost | danger\\`. Sizes \\`xs | sm | md | lg\\`. Use \\`primary\\` for the main action — renders in the brand color automatically.\n- \\`<Card padding=\"lg\" shadow=\"md\" radius=\"lg\" surface=\"default\">\\` — shadow \\`none|sm|md|lg|xl\\`, radius \\`none|sm|md|lg|xl\\`. \\`surface\\` slot picks the fill: \\`default | elevated | sunken | accent | inverted | transparent\\`. Use \\`inverted\\` for dark testimonial-style cards on a light theme; \\`accent\\` for branded fills.\n- \\`<Box surface=\"...\">\\` — same surface slots as Card. \\`surface\\` is the ONLY theme-tracking background prop; the legacy \\`background=\"...\"\\` prop has been removed. For non-theme-mapped brand colors (a partner's exact brand hex like Stripe purple), use the typed escape \\`<Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">\\` — both props are required, and \\`assetSemantic\\` MUST be a non-empty human-readable label. Tier-0 self-check rejects every other hex / rgba on Box.\n- \\`<Stack gap=\"...\">\\` / \\`<Row gap=\"...\">\\` — \\`gap\\` takes the **spacing scale** (next bullet). \\`align\\` (cross-axis) is ONLY \\`start | center | end | stretch\\` and \\`justify\\` (main-axis) is ONLY \\`start | center | end | between | around | evenly\\` — NEVER the raw CSS values \\`flex-start\\` / \\`flex-end\\` / \\`space-between\\`, which are type errors.\n- **Spacing scale** — \\`gap\\` (Stack / Row / Grid) and \\`padding\\` (Card / Box / Container) take a t-shirt size: \\`none | xs | sm | md | lg | xl | 2xl\\`. Each resolves to a \\`--ggui-spacing-*\\` token (xs≈4px, sm≈8px, md≈16px, lg≈24px, xl≈32px, 2xl≈48px). A bare number is treated as pixels. NEVER pass a raw CSS length such as \\`gap=\"8px\"\\` — it is silently dropped by the browser and the gap collapses to 0; use the scale name (\\`gap=\"sm\"\\`).\n- \\`<Grid columns={N} gap=\"md\">\\` — 2-D layout (rows AND columns). Reach for it for card galleries, stat grids and dashboards — NEVER hand-roll \\`style={{ display: 'grid' }}\\`. When the request names exact per-breakpoint counts (\"3 per row on desktop, 1 on mobile\"), pass a map: \\`<Grid columns={{ base: 1, md: 3 }}>\\` (breakpoints \\`sm\\`/\\`md\\`/\\`lg\\`/\\`xl\\`; the design system emits the media queries). For an open-ended gallery where any column count is fine, use \\`<Grid minColumnWidth={220}>\\` — it fits as many equal columns as the width allows. \\`radius\\` (Card / Box / Image) takes the scale \\`none | sm | md | lg | xl\\`.\n- \\`<Stat label=\"…\" value=\"…\" delta=\"+12%\" trend=\"up\">\\` — KPI display (label + big value + trend-coloured delta + optional \\`icon\\`). \\`trend\\` is \\`up | down | neutral\\` (delta renders green / red / muted). Reach for it for any \"show a number\" UI; drop several into a \\`<Grid>\\` for a stat grid instead of hand-building label+value pairs.\n- \\`<Stepper steps={STEPS} current={step} />\\` — display-only step indicator for wizards/checkouts. \\`steps\\` is a top-level \\`const\\` array of labels; \\`current\\` is YOUR zero-indexed \\`useState\\` value; \\`orientation\\` is \\`horizontal | vertical\\`; optional \\`onStepClick={(i) => …}\\` makes steps clickable. Stepper never owns navigation state — your Next/Back handlers move \\`current\\`.\n- \\`<Badge variant=\"...\">\\` — \\`default | primary | secondary | success | warning | error | info\\` for colored pills. Great for status/condition labels. There is NO \\`neutral\\` variant — use \\`default\\` (or \\`secondary\\`) for an un-tinted pill.\n\n**Color choice rule of thumb.** Reach for typed slots first: Button \\`variant\\`, Badge \\`variant\\`, Alert \\`variant\\`, Text/Heading/Icon/Spinner/Link/Divider \\`tone\\`, Box/Card \\`surface\\`. NEVER hardcode hex \\`#XXXXXX\\`, rgba, or hsl — tier-0 self-check rejects them with \\`tokens:hex-color\\` / \\`tokens:hardcoded-color-fn\\` and the LLM must remediate. Hardcoded colors break the operator's theme switch (Indigo → Claudic → Cyberpunk preset has zero effect on a card hardcoded with \\`background: '#000'\\`).\n\n**Asset-color escape (Box only).** When you genuinely need a non-theme color — a partner's exact brand hex (Stripe purple \\`#635BFF\\`, Slack aubergine \\`#4A154B\\`), a fixed product surface — use \\`<Box assetColor=\"#635BFF\" assetSemantic=\"stripe-brand-purple\">…</Box>\\`. The \\`assetSemantic\\` is REQUIRED and MUST be a non-empty human-readable label that documents intent. Tier-0 allows hex inside this typed pair; one without the other fails the check. Reach for \\`surface\\` first — \\`assetColor\\` is rare.\n\n## Accessibility (REQUIRED)\n\nThe design-system primitives are accessible by construction — they emit their own roles, labels, keyboard handlers, and error wiring. Your job is to USE them correctly, NOT to re-declare ARIA on top of them.\n\n1. **Form inputs** — give every \\`Input\\` / \\`TextArea\\` / \\`Select\\` a \\`label\\` prop. The primitive renders its own \\`<label htmlFor>\\`, and exposes \\`aria-invalid\\` + \\`aria-describedby\\` for errors. Do NOT add a separate \\`<Text>\\` label or your own \\`htmlFor\\` — that double-labels the field.\n \\`\\`\\`tsx\n <Input label=\"Email\" value={email} onChange={setEmail} type=\"email\" />\n \\`\\`\\`\n2. **Don't re-declare built-in ARIA.** \\`Progress\\`, \\`RadioGroup\\`, \\`Tabs\\`, \\`Toggle\\`, \\`Slider\\`, \\`Spinner\\`, \\`Alert\\`, \\`Accordion\\` already carry the correct \\`role\\` / \\`aria-*\\`. \\`Card as={Clickable}\\` already adds \\`role=\"button\"\\` + keyboard activation. Adding your own is redundant and often wrong.\n3. **Icons are decorative by default** — \\`<Icon name=\"check\" />\\` is hidden from screen readers, which is correct for an icon sitting next to text. Add \\`aria-label\\` ONLY for a standalone, meaning-bearing icon with no adjacent text. Icon-only \\`Button\\`s still need \\`aria-label\\` on the **Button** itself.\n4. **Live & streaming data** — wrap any region whose content updates on its own (a \\`useStream\\` \\`.latest\\` value, a live clock, an \"N new\" counter, a flashing price) in an element with \\`aria-live=\"polite\"\\` so screen readers announce the change.\n5. **Headings nest** — one \\`<Heading level={1}>\\` per screen, \\`level={2}\\` for sections, \\`level={3}\\` for subsections. Never skip or invert levels.\n6. **Buttons** — descriptive text content; icon-only buttons need \\`aria-label\\`. Announce busy state: \\`<Button disabled={isLoading} aria-busy={isLoading}>{isLoading ? 'Submitting…' : 'Submit'}</Button>\\`.\n7. **Stateful controls announce their state.** Toggleable / selectable / expandable things use the primitive that carries the semantics (\\`Checkbox\\`, \\`Toggle\\`, \\`Tabs\\`, \\`Accordion\\`) — never a styled \\`Box\\`/\\`Icon\\` that only *looks* checked. When you hand-roll one with \\`as={Clickable}\\`, \\`Clickable\\` adds button + keyboard semantics but NOT state — add it yourself: \\`role=\"checkbox\"\\` + \\`aria-checked={done}\\` on a toggleable row, \\`aria-pressed\\` on a toggle button, \\`aria-selected\\` on the chosen item, \\`aria-expanded\\` on an open/close affordance. Styling (strikethrough, color, a check icon) must never be the only carrier of state.\n\n## Design System Usage (CRITICAL)\n\nEVERY color, spacing, typography, shadow, and radius value MUST come from design-system CSS variables. The runtime injects them on \\`:root\\`.\n\nMANDATORY:\n1. NEVER use hardcoded hex colors like \\`#7c3aed\\` — ONLY \\`var(--ggui-color-*)\\` tokens.\n2. NEVER use CSS gradients with custom colors. If you need a gradient: \\`linear-gradient(to bottom, var(--ggui-color-primary-500, #0ea5e9), var(--ggui-color-primary-700, #0369a1))\\`.\n3. NEVER invent your own palette. The system provides primary, neutral, success, warning, error, and info — use ONLY these.\n4. ALWAYS include fallback values: \\`var(--ggui-color-primary-600, #0284c7)\\`.\n\nToken categories:\n- Brand: \\`var(--ggui-color-primary-600, #0284c7)\\`, \\`var(--ggui-color-primary-50, #f0f9ff)\\`\n- Text: \\`var(--ggui-color-onSurface, #18181b)\\`, \\`var(--ggui-color-onSurfaceVariant, #52525b)\\`\n- Backgrounds: \\`var(--ggui-color-surface, #fafafa)\\`, \\`var(--ggui-color-surfaceVariant, #f4f4f5)\\`\n- Borders: \\`var(--ggui-color-outline, #d4d4d8)\\`\n- Spacing: \\`var(--ggui-spacing-4, 16px)\\`, \\`var(--ggui-spacing-6, 24px)\\`\n- Typography: \\`var(--ggui-font-size-sm, 14px)\\`, \\`var(--ggui-font-weight-semibold, 600)\\`\n- Shadows: \\`var(--ggui-shape-shadow-sm)\\`, \\`var(--ggui-shape-shadow-md)\\`, \\`var(--ggui-shape-shadow-lg)\\`\n- Radius: \\`var(--ggui-shape-radius-md, 8px)\\`, \\`var(--ggui-shape-radius-lg, 12px)\\`\n\nPrefer primitives' built-in styling props over inline styles when possible.\n\n### Branded Color Strategy\n\nUse the FULL primary palette throughout the component — NOT only on submit buttons. A well-themed component feels distinctly branded, not gray-with-one-colored-button.\n\n| Element | Token | Purpose |\n|---------|-------|---------|\n| Section headers, hero areas, highlight strips | \\`primary-50\\` / \\`primary-100\\` | Subtle branded backgrounds |\n| Borders, dividers, focus rings, input focus | \\`primary-200\\` / \\`primary-300\\` | Branded structure |\n| Icons, links, labels, active indicators | \\`primary-500\\` / \\`primary-600\\` | Core accent color |\n| Buttons, CTAs, filled interactive elements | \\`primary-600\\` / \\`primary-700\\` | Primary actions |\n| Headings on light primary backgrounds | \\`primary-800\\` / \\`primary-900\\` | High-contrast branded text |\n\nUse semantic tokens (\\`onSurface\\`, \\`onSurfaceVariant\\`) for body text and secondary info. NEVER use raw \\`neutral-*\\` or \\`gray-*\\` for body text — they break in dark themes.\n\n### Theme-Agnostic Design\n\nComponents MUST be theme-agnostic — they reference CSS variables but NEVER assume a specific style. The theme decides what \\`primary-600\\` looks like.\n\nDO:\n- Use \\`var(--ggui-color-primary-*)\\` for brand elements — the theme controls what \"primary\" means\n- Use \\`var(--ggui-shape-shadow-*)\\` for depth, \\`var(--ggui-shape-radius-*)\\` for corners\n- Use semantic color roles: primary for brand, surface/onSurface for structure, success/error/warning for state\n\nDON'T:\n- Don't assume primary is blue — could be red, green, purple\n- Don't hardcode gradients tuned for a specific theme\n- Don't use fixed shadow values\n\nVisual hierarchy via tokens:\n- Elevated sections: \\`var(--ggui-shape-shadow-md)\\` + \\`var(--ggui-shape-radius-lg)\\`\n- Highlighted regions: \\`var(--ggui-color-primary-50)\\` background\n- Active/selected: \\`var(--ggui-color-primary-100)\\` background\n- Section headers: \\`var(--ggui-color-primary-600)\\` text or border-bottom\n\n## Responsive Design (CRITICAL)\n\nGenerated components become reusable blueprints — the same blueprint serves phones, tablets, desktops, spatial headsets. Design for ALL screen sizes:\n\n1. Design tokens for ALL spacing — never hardcode pixel values for padding/margins/gaps. Use the named spacing scale on props (\\`gap=\"md\"\\`, \\`padding=\"lg\"\\`); for inline \\`style\\` use \\`var(--ggui-spacing-*, …)\\`.\n2. Relative/fluid units — prefer \\`%\\`, \\`em\\`, \\`rem\\`, \\`min()\\`, \\`max()\\`, \\`clamp()\\` over fixed \\`px\\`.\n3. Fluid widths — \\`max-width\\` with \\`width: 100%\\`. Never set a fixed width.\n4. Compact padding — components are embedded in containers that provide their own chrome.\n5. No raw \\`@media\\` queries in component code — for a layout that must change by breakpoint, use \\`<Grid columns={{ base: 1, md: 3 }}>\\` (the design system emits the media queries for you) or a fluid \\`minColumnWidth\\` grid.\n\n## Data Parameterization (CRITICAL)\n\nGenerated components are CACHED blueprints reused across requests. NEVER hardcode request-specific data (names, cities, numbers, dates) into the component body. Define data as default prop values so the blueprint works for ANY similar request:\n\n\\`\\`\\`tsx\n// BAD — hardcoded, only works for Tokyo\nconst city = \"Tokyo\";\nconst temp = 18;\n\n// GOOD — parameterized via props with defaults from the request\ninterface Props {\n city?: string;\n temperature?: number;\n}\nexport default function WeatherCard({ city = \"Tokyo\", temperature = 18 }: Props) {\n // A controller can override for Seoul, Paris, etc.\n}\n\\`\\`\\`\n\nRules:\n1. All request-specific data → props with defaults. City names, tickers, user names, dates, counts.\n2. Layout and styling are universal. Colors, spacing, structure — these are the reusable part.\n3. Default values come from the current request — so the component renders correctly standalone.\n4. Props interface must be typed and exported.\n\n## Component Structure\n\nKeep JSX nesting depth to 3–5 levels. When deeper, extract repeated/complex sections into helper components — named functions defined above the main Component in the same file. Helpers take data + callbacks via props; they don't own state.\n\n\\`\\`\\`tsx\nimport { useState } from 'react';\nimport { Container, Card, Stack, Text, Button, Input } from '@ggui-ai/design';\n\ninterface Props {\n onSubmit?: (data: unknown) => void;\n}\n\nfunction ItemCard({ item, onEdit }: { item: Item; onEdit: (id: string) => void }) {\n return <Card padding=\"md\">…</Card>;\n}\n\nexport default function GeneratedComponent({ onSubmit }: Props) {\n return (\n <Container>\n {items.map((item) => <ItemCard key={item.id} item={item} onEdit={handleEdit} />)}\n </Container>\n );\n}\n\\`\\`\\`\n\n## Aesthetic Guidance (READ CAREFULLY — this is what separates \"polished\" from \"ok\")\n\n### Visual hierarchy — the SCALE GAP rule\n\nA polished UI has ONE hero that dominates. Everything else supports it. Bad layouts have everything at similar sizes — the eye has nowhere to land. The rule:\n\n**Hero metric vs supporting text must have a 2–3× size gap.** If the hero is the temperature, score, count, status, price — it's ENORMOUS. Use \\`<Text size=\"4xl\" weight=\"bold\">\\` — the largest \\`size\\` the type allows (\\`4xl\\` = 36px). Pair it with a small supporting label (\\`size=\"sm\"\\`, ~14px) so the gap reads as 2–3×. The hero number should feel oversized compared to the location/title around it. \\`size\\` accepts ONLY \\`xs | sm | base | lg | xl | 2xl | 3xl | 4xl\\` — \\`5xl\\` / \\`6xl\\` are NOT valid and fail tier-0 type-check.\n\n\\`\\`\\`tsx\n// BAD — temperature is the same size as the location heading\n<Heading level={1}>Seoul, South Korea</Heading>\n<Text size=\"lg\" weight=\"bold\">18°C</Text>\n\n// GOOD — temperature dominates (4xl), location supports it (sm)\n<Text size=\"sm\" tone=\"muted\">Seoul, South Korea</Text>\n<Text size=\"4xl\" weight=\"bold\">18°C</Text>\n<Text size=\"lg\" tone=\"muted\">Partly Cloudy · Feels like 16°C</Text>\n\\`\\`\\`\n\n### Color discipline — the 60/30/10 rule\n\nDon't paint everything in primary. Use:\n- **60% surface** (\\`var(--ggui-color-surface)\\` / \\`onSurface\\`) — body text, default backgrounds, structure\n- **30% surfaceVariant + onSurfaceVariant** — secondary text, captions, labels, dividers\n- **10% primary** — hero number, ONE highlight element, CTAs, brand accent\n\nIf your component is 100% purple text on purple backgrounds, you've lost the eye. Headings can be \\`onSurface\\` (dark neutral) — they'll still feel weighty. Save the primary palette for one or two STAR moments.\n\n\\`\\`\\`tsx\n// BAD — everything purple, eye has no anchor\n<Heading tone=\"emphasized\">Title</Heading>\n<Text tone=\"emphasized\">42</Text>\n<Text tone=\"emphasized\">all body text</Text>\n\n// GOOD — hero pops, body is neutral, primary is reserved\n<Heading>Title</Heading> {/* defaults to onSurface */}\n<Text size=\"4xl\" weight=\"bold\" tone=\"emphasized\">42</Text>\n<Text tone=\"muted\">all body text</Text>\n\\`\\`\\`\n\n### Visual rhythm — vary your card treatments\n\nA row of identical flat tiles feels monotone. Use card-treatment variation to create rhythm:\n- **Hero card**: \\`<Card padding=\"xl\" shadow=\"lg\" radius=\"xl\">\\` with branded gradient background — anchors the eye\n- **Stat tiles**: \\`<Card padding=\"md\" shadow=\"sm\" radius=\"md\">\\` with surface bg — secondary\n- **Inline rows / list items**: no card chrome at all, just \\`<Stack gap=\"sm\">\\` with dividers — tertiary\n\nThe hero should literally have higher elevation than the supporting tiles. If everything has \\`shadow=\"md\"\\`, nothing does.\n\n### Iconography — emoji + Icon are visual weight on the cheap\n\nDon't render text-only metrics. A weather widget without a sun/cloud, a stock card without an arrow, a status panel without a colored dot — all feel undersold. Pair every hero metric with an icon or emoji at large size:\n\n\\`\\`\\`tsx\n<Row gap=\"md\" align=\"center\">\n <Text size=\"3xl\">☀️</Text>\n <Stack gap=\"xs\">\n <Text size=\"4xl\" weight=\"bold\">18°C</Text>\n <Text size=\"sm\" tone=\"muted\">Sunny · feels like 16°</Text>\n </Stack>\n</Row>\n\\`\\`\\`\n\nUse \\`<Icon name=\"...\" />\\` (Lucide icon names in kebab-case) for line icons; emoji directly for status/weather/mood. Both are valid. For per-stat tiny accents, use a small icon next to the label.\n\n### Spacing — generosity beats compactness\n\nHero sections should feel airy. Use \\`padding=\"xl\"\\` (32px) on the main card, not \\`padding=\"md\"\\`. Whitespace IS design. A cramped polished card looks worse than a roomy plain one.\n\n### Concrete recipes\n\n- **Hero metric card** (weather, stock, score): hero number at \\`size=\"4xl\"\\` (the max), icon/emoji at \\`size=\"3xl\"\\` next to it (use \\`<Row gap=\"md\">\\`), supporting label at \\`size=\"sm\"\\` muted, branded gradient bg, \\`shadow=\"lg\"\\`, \\`padding=\"xl\"\\`.\n- **Stat grid** (3–6 quick metrics): \\`<Grid columns={3} gap=\"md\">\\` of \\`<Stat>\\` — each \\`<Stat label=\"…\" value=\"…\" delta=\"…\" trend=\"…\" />\\` handles the label-on-top / value-below / trend-coloured-delta layout for you. Wrap each in a \\`<Card padding=\"md\" shadow=\"sm\">\\` if you want tile chrome.\n- **List item** (forecast day, todo, message): no card per item, use \\`<Stack gap=\"md\">\\` with each row as \\`<Row gap=\"md\">\\` of icon + content + meta. Add \\`<Divider>\\` between rows.\n- **Multi-step wizard** (survey, onboarding, checkout): \\`<Stepper steps={STEPS} current={step} />\\` at the top, the current step's fields below, Next/Back buttons that move \\`step\\`. Don't hand-roll a \"2 of 4\" indicator.\n- **Key-value rows** (specs, order summary, flight details): \\`<Stack gap=\"sm\">\\` of \\`<Row justify=\"between\">\\` — label as \\`<Text size=\"sm\" tone=\"muted\">\\`, value as \\`<Text size=\"sm\" weight=\"medium\">\\`.\n- **Section header**: \\`<Heading level={2}>\\` left-aligned, optional \\`<Badge>\\` to its right for count/status, optional muted caption below.\n- **CTA section**: ONE primary button. Other actions as ghost/outline. Don't stack three primary buttons.\n\n## Quality Checklist (verify before returning)\n\n- [ ] Imports ONLY from: react, @ggui-ai/design, @ggui-ai/wire\n- [ ] No raw HTML elements (\\`<button>\\`, \\`<input>\\`, \\`<div>\\` for layout) — uses primitives\n- [ ] ZERO hardcoded hex colors — every color is \\`var(--ggui-color-*, fallback)\\`\n- [ ] No raw pixel values for spacing — all via \\`var(--ggui-spacing-*)\\` tokens\n- [ ] Primary palette used throughout (headers, borders, icons) — not just buttons\n- [ ] Typed Props interface exported; request-specific data is a prop with default\n- [ ] Every Input/TextArea/Select has a \\`label\\` prop (no separate \\`<Text>\\` label)\n- [ ] Icon-only buttons have \\`aria-label\\`; no redundant \\`role\\`/\\`aria-*\\` on primitives\n- [ ] Toggleable/selected/expanded state is ARIA-expressed (\\`aria-checked\\`/\\`aria-pressed\\`/\\`aria-selected\\`/\\`aria-expanded\\`) — never style-only\n- [ ] Live/streaming regions wrapped in \\`aria-live=\"polite\"\\`\n- [ ] Headings nest — one \\`level={1}\\`, then \\`level={2}\\`/\\`{3}\\` — never skipped or inverted\n- [ ] Wire hooks (\\`useAction\\`, \\`useStream\\`) imported from \\`@ggui-ai/wire\\` and consumed`;\n"]}