@ggui-ai/ui-gen 0.15.0 → 0.16.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 (101) hide show
  1. package/dist/adapters/generation-dispatch.d.ts +21 -4
  2. package/dist/adapters/generation-dispatch.js +913 -350
  3. package/dist/adapters/generation-dispatch.js.map +1 -1
  4. package/dist/adapters/index.js +26 -22
  5. package/dist/adapters/index.js.map +1 -1
  6. package/dist/advanced/index.d.ts +17 -12
  7. package/dist/advanced/index.js +966 -374
  8. package/dist/advanced/index.js.map +1 -1
  9. package/dist/boilerplate.d.ts +16 -1
  10. package/dist/boilerplate.js +579 -245
  11. package/dist/boilerplate.js.map +1 -1
  12. package/dist/check/index.d.ts +17 -3
  13. package/dist/check/index.js +32 -25
  14. package/dist/check/index.js.map +1 -1
  15. package/dist/{create-ui-generator-D6TKuv9V.d.ts → create-ui-generator-CCIeQaEe.d.ts} +77 -10
  16. package/dist/design-mode-BHEE7flj.d.ts +67 -0
  17. package/dist/{dispatch-BuZfTh9r.d.ts → dispatch-BA5dJcg-.d.ts} +4 -1
  18. package/dist/evaluation/axis-checks/index.d.ts +4 -3
  19. package/dist/evaluation/axis-checks/index.js +3 -1
  20. package/dist/evaluation/axis-checks/index.js.map +1 -1
  21. package/dist/evaluation/axis-checks/registry.d.ts +2 -1
  22. package/dist/evaluation/axis-checks/registry.js +1 -0
  23. package/dist/evaluation/axis-checks/registry.js.map +1 -1
  24. package/dist/evaluation/index.d.ts +143 -3
  25. package/dist/evaluation/index.js +3866 -92
  26. package/dist/evaluation/index.js.map +1 -1
  27. package/dist/{generate-BTfvELgl.d.ts → generate-8L_bc2iP.d.ts} +10 -1
  28. package/dist/harness/check/runtime-render/index.d.ts +2 -1
  29. package/dist/harness/index.d.ts +2 -1
  30. package/dist/harness/index.js +589 -248
  31. package/dist/harness/index.js.map +1 -1
  32. package/dist/harness/llm-trace-sink.d.ts +3 -3
  33. package/dist/harness/llm-trace-sink.js.map +1 -1
  34. package/dist/harness/prompts.d.ts +2 -1
  35. package/dist/harness/prompts.js +3 -0
  36. package/dist/harness/prompts.js.map +1 -1
  37. package/dist/harness/result-types.d.ts +17 -5
  38. package/dist/harness/result-types.js.map +1 -1
  39. package/dist/harness/runtime.d.ts +19 -3
  40. package/dist/harness/runtime.js +602 -261
  41. package/dist/harness/runtime.js.map +1 -1
  42. package/dist/harness/types-public.d.ts +28 -1
  43. package/dist/harness/types-public.js +589 -248
  44. package/dist/harness/types-public.js.map +1 -1
  45. package/dist/harness/validator-trace-sink.d.ts +2 -1
  46. package/dist/index.d.ts +8 -4
  47. package/dist/index.js +973 -372
  48. package/dist/index.js.map +1 -1
  49. package/dist/patch.d.ts +2 -1
  50. package/dist/{prompts-BVhtH3M1.d.ts → prompts-k6m6reqe.d.ts} +11 -1
  51. package/dist/providers/index.d.ts +2 -2
  52. package/dist/providers/index.js.map +1 -1
  53. package/dist/tools/get-primitives-ts.d.ts +1 -1
  54. package/dist/tools/get-primitives-ts.js +1 -1
  55. package/dist/tools/get-primitives-ts.js.map +1 -1
  56. package/dist/{types-public-CkNWEov9.d.ts → types-public-D24JLJgl.d.ts} +49 -5
  57. package/dist/validation/index.d.ts +1 -1
  58. package/dist/validation/index.js +4 -4
  59. package/dist/validation/index.js.map +1 -1
  60. package/dist/workflows.d.ts +2 -1
  61. package/package.json +12 -12
  62. package/src/adapters/generation-dispatch.ts +57 -4
  63. package/src/adapters/provider-router.ts +7 -6
  64. package/src/adapters/tools.ts +5 -5
  65. package/src/advanced/generator.ts +11 -10
  66. package/src/advanced/index.ts +5 -4
  67. package/src/boilerplate/free-design-prompt.ts +329 -0
  68. package/src/boilerplate/generate.ts +10 -1
  69. package/src/boilerplate/hard-sections.ts +242 -0
  70. package/src/boilerplate/render.ts +32 -8
  71. package/src/boilerplate/system-prompt.ts +81 -229
  72. package/src/boilerplate/templates/base-free.tsx.tmpl +24 -0
  73. package/src/check/run-tier0.ts +80 -20
  74. package/src/coding-agent/tools.ts +8 -2
  75. package/src/contract-context.ts +28 -0
  76. package/src/create-harness.ts +11 -0
  77. package/src/create-ui-generator.ts +71 -25
  78. package/src/design-mode.ts +182 -0
  79. package/src/design-system-docs.ts +17 -13
  80. package/src/evaluation/axis-checks/dispatch.ts +4 -0
  81. package/src/evaluation/axis-checks/extras.ts +5 -0
  82. package/src/evaluation/cost-tracker.ts +2 -3
  83. package/src/evaluation/index.ts +46 -2
  84. package/src/evaluation/llm-evaluator.ts +77 -21
  85. package/src/evaluation/types-public.ts +103 -8
  86. package/src/evaluation/visual-evaluator.ts +301 -29
  87. package/src/harness/coding/dupe-break.ts +0 -0
  88. package/src/harness/coding/init-session.ts +1 -0
  89. package/src/harness/coding/run-coding-turn.ts +3 -0
  90. package/src/harness/coding/run-eval-round.ts +15 -2
  91. package/src/harness/llm-trace-sink.ts +3 -3
  92. package/src/harness/result-types.ts +15 -3
  93. package/src/harness/runtime.ts +18 -0
  94. package/src/harness/types-public.ts +27 -0
  95. package/src/index.ts +26 -0
  96. package/src/internal/extract-call-signatures.ts +2 -2
  97. package/src/providers/bedrock.ts +4 -4
  98. package/src/run-check.ts +1 -0
  99. package/src/tools/get-primitives-ts.ts +1 -1
  100. package/src/validation/allowed-imports.ts +8 -2
  101. package/src/validation/primitives.ts +1 -1
@@ -2,9 +2,67 @@ import { listContractGadgets, HOOK_NAME_RE, resolveAppGadgets } from '@ggui-ai/p
2
2
  import { readFileSync } from 'fs';
3
3
  import { dirname, resolve } from 'path';
4
4
  import { fileURLToPath } from 'url';
5
+ import { consumedTokenManifest } from '@ggui-ai/design/themes';
5
6
  import ts from 'typescript';
6
7
 
7
8
  // src/boilerplate/generate.ts
9
+
10
+ // src/design-mode.ts
11
+ var DEFAULT_DESIGN_MODE = "constrained";
12
+ function canvasDisplayModeForShell(shell) {
13
+ return shell === "chat" || shell === "inline" ? "inline" : "fullscreen";
14
+ }
15
+ function canvasForRendering(shellType, screen) {
16
+ const shell = shellType ?? "fullscreen";
17
+ if (canvasDisplayModeForShell(shell) === "inline") return "xs-chat-card";
18
+ if (shell === "spatial") return "md";
19
+ switch (screen ?? "universal") {
20
+ case "mobile":
21
+ return "mobile-fullscreen-small";
22
+ case "tablet":
23
+ return "md";
24
+ default:
25
+ return "lg";
26
+ }
27
+ }
28
+ var CANVAS_DESCRIPTORS = {
29
+ "xs-chat-card": {
30
+ label: "extra-small chat card",
31
+ minWidthPx: 320,
32
+ maxWidthPx: 480,
33
+ host: "an inline card inside a chat message bubble \u2014 the host draws the card border, shadow and rounded corners; the component fills the bubble width and takes its natural height"
34
+ },
35
+ "mobile-fullscreen-small": {
36
+ label: "small mobile fullscreen",
37
+ minWidthPx: 320,
38
+ maxWidthPx: 599,
39
+ host: "a phone-sized viewport the component owns edge to edge \u2014 single column, touch targets at least 44px, the component manages its own scroll"
40
+ },
41
+ md: {
42
+ label: "medium panel",
43
+ minWidthPx: 600,
44
+ maxWidthPx: 1023,
45
+ host: "a tablet viewport or a floating panel (spatial / picture-in-picture) \u2014 one or two columns, medium density"
46
+ },
47
+ lg: {
48
+ label: "large fullscreen",
49
+ minWidthPx: 1024,
50
+ maxWidthPx: 1439,
51
+ host: "a desktop viewport the component owns edge to edge \u2014 multi-column layouts, hover states and pointer interactions are available"
52
+ },
53
+ xl: {
54
+ label: "extra-large fullscreen",
55
+ minWidthPx: 1440,
56
+ maxWidthPx: 1920,
57
+ host: "a wide desktop viewport the component owns edge to edge \u2014 cap content width or use the extra room deliberately; never stretch a single column across the whole width"
58
+ }
59
+ };
60
+ function describeCanvas(canvas) {
61
+ const d = CANVAS_DESCRIPTORS[canvas];
62
+ return `This component renders on the \`${canvas}\` canvas (${d.label}): ${d.minWidthPx}\u2013${d.maxWidthPx}px wide, ${d.host}. Design for the whole range \u2014 the host may size the iframe anywhere inside it.`;
63
+ }
64
+
65
+ // src/boilerplate/render.ts
8
66
  var __dirname$1 = dirname(fileURLToPath(import.meta.url));
9
67
  var TEMPLATE_DIRS = [
10
68
  resolve(__dirname$1, "templates"),
@@ -13,19 +71,31 @@ var TEMPLATE_DIRS = [
13
71
  resolve(__dirname$1, "..", "..", "..", "src", "boilerplate", "templates"),
14
72
  resolve(__dirname$1, "..", "..", "..", "..", "src", "boilerplate", "templates")
15
73
  ];
16
- var baseCache = null;
74
+ var BASE_TEMPLATE_FILE = {
75
+ constrained: "base.tsx.tmpl",
76
+ free: "base-free.tsx.tmpl"
77
+ };
78
+ var FREE_LAYOUT = [
79
+ " <div style={{ width: '100%' }}>",
80
+ " {/* implement your UI here */}",
81
+ " </div>"
82
+ ].join("\n");
83
+ var baseCache = /* @__PURE__ */ new Map();
17
84
  var layoutCache = /* @__PURE__ */ new Map();
18
- function loadBase() {
19
- if (baseCache) return baseCache;
85
+ function loadBase(designMode) {
86
+ const cached = baseCache.get(designMode);
87
+ if (cached !== void 0) return cached;
88
+ const file = BASE_TEMPLATE_FILE[designMode];
20
89
  for (const dir of TEMPLATE_DIRS) {
21
90
  try {
22
- baseCache = readFileSync(resolve(dir, "base.tsx.tmpl"), "utf-8");
23
- return baseCache;
91
+ const content = readFileSync(resolve(dir, file), "utf-8");
92
+ baseCache.set(designMode, content);
93
+ return content;
24
94
  } catch {
25
95
  continue;
26
96
  }
27
97
  }
28
- throw new Error("No base.tsx.tmpl found");
98
+ throw new Error(`No ${file} found`);
29
99
  }
30
100
  function loadLayout(shellType, screen) {
31
101
  const key = `${shellType}-${screen}`;
@@ -49,9 +119,9 @@ function loadLayout(shellType, screen) {
49
119
  }
50
120
  throw new Error(`No layout found for ${key}`);
51
121
  }
52
- function renderBoilerplate(shellType, screen, markers) {
53
- let template = loadBase();
54
- const layout = loadLayout(shellType, screen);
122
+ function renderBoilerplate(shellType, screen, markers, designMode = DEFAULT_DESIGN_MODE) {
123
+ let template = loadBase(designMode);
124
+ const layout = designMode === "free" ? FREE_LAYOUT : loadLayout(shellType, screen);
55
125
  template = template.replace("{{LAYOUT}}", layout);
56
126
  for (const [key, value] of Object.entries(markers)) {
57
127
  template = template.replaceAll(`{{${key}}}`, value);
@@ -228,7 +298,7 @@ function inferTypeFromExample(example) {
228
298
  }
229
299
  return `{ ${fields.join("; ")} }`;
230
300
  }
231
- function generateBoilerplate(_userPrompt, contract, shellType, screen, composedSections, appGadgets) {
301
+ function generateBoilerplate(_userPrompt, contract, shellType, screen, composedSections, appGadgets, designMode = DEFAULT_DESIGN_MODE) {
232
302
  const propsFields = [];
233
303
  const propsProperties = contract?.propsSpec?.properties ?? {};
234
304
  for (const [key, entry] of Object.entries(propsProperties)) {
@@ -410,7 +480,7 @@ ${body}
410
480
  CONTEXT_HOOKS: contextHooks,
411
481
  WIRE_HOOKS: hookBody,
412
482
  AXIS_SECTIONS: composedSections ?? ""
413
- });
483
+ }, designMode);
414
484
  }
415
485
 
416
486
  // src/evaluation/types-public.ts
@@ -591,14 +661,45 @@ Intentional custom colors (status indicators) are acceptable when no semantic to
591
661
  Only list ACTUAL violations. Use 'fail' only for pervasive violations.`
592
662
  }
593
663
  ];
594
- function getCriteriaByPriority(priority) {
595
- return CRITERIA.filter((c) => c.priority === priority);
664
+ var FREE_DESIGN_CRITERIA_OVERRIDES = [
665
+ {
666
+ id: "tokens",
667
+ name: "Color tokens",
668
+ priority: "P1",
669
+ tier: 0,
670
+ failOutcome: "warn",
671
+ codingGuidance: "Every color is a bare var(--ggui-color-*) from the token manifest \u2014 no hex, rgb()/hsl(), CSS named colors or literal fallbacks, in style props and <style> blocks alike. Spacing, typography, radius and shadow geometry may be literals.",
672
+ evalInstruction: "Flag hardcoded hex colors, rgba/hsl functions, CSS named colors, and literal fallbacks inside var(--ggui-*) references. Do NOT flag literal spacing, font sizes, radii or pixel values \u2014 they are allowed in this mode."
673
+ },
674
+ {
675
+ id: "visual",
676
+ name: "Visual composition",
677
+ priority: "P2",
678
+ tier: 2,
679
+ failOutcome: "warn",
680
+ codingGuidance: "Compose deliberately: one clear focal point, consistent spacing rhythm, a coherent theme-token palette, a fit to the rendering canvas.",
681
+ evalInstruction: `Evaluate VISUAL COMPOSITION: Is the component composed deliberately for its canvas?
682
+
683
+ Judge: visual hierarchy (one clear focal point, headings distinct from body text), consistent spacing rhythm and alignment, a coherent palette drawn from the theme tokens, fit to the canvas (fluid width, no fixed widths, nothing cramped or stretched).
684
+ Do NOT reward or penalise the use of design-system primitives \u2014 raw HTML with inline CSS is a first-class choice here. Literal spacing / typography / radius values are fine.
685
+
686
+ Only list ACTUAL composition problems. Use 'fail' only for a fundamentally incoherent composition.`
687
+ }
688
+ ];
689
+ function criteriaFor(designMode = "constrained") {
690
+ if (designMode === "constrained") return CRITERIA;
691
+ return CRITERIA.map(
692
+ (c) => FREE_DESIGN_CRITERIA_OVERRIDES.find((o) => o.id === c.id) ?? c
693
+ );
596
694
  }
597
- function buildCodingCriteriaSummary() {
695
+ function getCriteriaByPriority(priority, designMode = "constrained") {
696
+ return criteriaFor(designMode).filter((c) => c.priority === priority);
697
+ }
698
+ function buildCodingCriteriaSummary(designMode = "constrained") {
598
699
  const lines = ["## Priority (P0 first, then P1, then P2)", ""];
599
700
  for (const priority of ["P0", "P1", "P2"]) {
600
701
  const label = priority === "P0" ? "Must (compile + complete)" : priority === "P1" ? "Should (safety)" : "Nice (quality)";
601
- const criteria = getCriteriaByPriority(priority);
702
+ const criteria = getCriteriaByPriority(priority, designMode);
602
703
  lines.push(`**${priority} \u2014 ${label}:**`);
603
704
  for (const c of criteria) {
604
705
  lines.push(`- ${c.codingGuidance}`);
@@ -607,6 +708,427 @@ function buildCodingCriteriaSummary() {
607
708
  }
608
709
  return lines.join("\n");
609
710
  }
711
+
712
+ // src/boilerplate/hard-sections.ts
713
+ var PROTOCOL_NOTES = `## Protocol Notes
714
+ The 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:
715
+ 1. **Do NOT delete any pre-declared hook.** \`self_check\` fails with \`wire_preservation:<kind>:<name>\` if you remove one.
716
+ 2. **Consume every hook binding** somewhere in the component \u2014 in JSX, a callback, or an effect. Unused bindings fail lint with \`no-unused-vars\`.
717
+ 3. **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 \u2014 your job is to honor what's declared.
718
+
719
+ Renaming a binding is fine \u2014 the wiring is the string-literal argument, not the identifier.`;
720
+ var CONTRACT_SURFACE = `## Contract surface \u2014 four specs + two catalogs
721
+
722
+ A \`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:
723
+
724
+ | Surface | Direction | Role |
725
+ | -------------------- | -------------------------- | -------------------------------------------------------------------- |
726
+ | \`propsSpec\` | server \u2192 UI (one-shot) | Initial render values delivered once at \`ggui_render\` |
727
+ | \`streamSpec\` | agent \u2192 UI (many) | Typed channels for live updates via \`ggui_emit\` |
728
+ | \`actionSpec\` | UI \u2192 agent (events) | Discrete events driving the agent's next turn (consumed via \`ggui_consume\`) |
729
+ | \`contextSpec\` | UI \u2192 server (state mirror) | UI state the agent observes between turns |
730
+ | \`agentCapabilities.tools\` | catalog | Tools the contract references via \`actionSpec[*].nextStep\` and \`streamSpec[*].source.tool\` |
731
+ | \`clientCapabilities.gadgets\` | catalog | Browser-capability gadget hooks the component code mounts (e.g., \`useGeolocation\`) |
732
+
733
+ **Placement rule for inbound specs**: actions drive turns; context observes state. There is no third category.
734
+
735
+ **Data vs behavior**: the contract describes data flow; the component code describes behavior. Scroll, focus, toast, animation, clipboard write \u2014 all component code, never contract fields.`;
736
+ var DEFENSIVE_CODING = `## Defensive coding for absent / late-arriving data
737
+
738
+ Props 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.**
739
+
740
+ - **Optional contract props**: a \`Props\` field marked \`?\` in the boilerplate may be omitted by the agent ENTIRELY \u2014 the wire gate only enforces \`required: true\` entries, and the harness verifies your component with those props stripped. Guard them (\`?? default\`, \`?.\`, or an empty-state branch) from the FIRST render.
741
+ - **Array iteration**: always default to \`[]\` before \`.map\`/\`.filter\`/\`.length\`. Use \`(props.items ?? []).map(...)\` not \`props.items.map(...)\`. Same for stream.all, stream.latest, etc.
742
+ - **Object access**: optional-chain through nested fields. \`props.user?.name ?? 'Anonymous'\` not \`props.user.name\`.
743
+ - **Number ops**: default before arithmetic. \`(props.count ?? 0) + 1\` not \`props.count + 1\`.
744
+ - **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 \u2014 guard before reading \`.foo\`.
745
+ - **Stream reconciliation**: when a stream event carries an \`action\` discriminant (e.g. \`create | move | edit | delete\`), the channel is a CRUD feed \u2014 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 \u2014 and handle an event whose id is not yet present (a \`create\` for an unknown item) by inserting it, not ignoring it.
746
+ - **Props re-sync on repaint**: props the agent owns are the source of truth for display \u2014 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 \u2014 \`useEffect(() => setCount(props.count ?? 0), [props.count])\` \u2014 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.
747
+ - **Loading state**: while data is still absent, render \`<Skeleton>\` placeholders \u2014 never a blank screen. \`<Skeleton variant="text" />\` for a text line, \`variant="circle"\` for an avatar slot, default \`rect\` for a block.
748
+ - **Empty state**: when a list or results array is empty, render \`<EmptyState title="\u2026" description="\u2026" />\` \u2014 a region that renders nothing when empty looks broken to the user.
749
+
750
+ Unhandled \`Cannot read properties of undefined\` errors trip the iframe error boundary and the user sees "Something went wrong" \u2014 a regression class the runtime can't recover from.`;
751
+ var GESTURE_ROUTING = `## Picking the right primitive for user gestures
752
+
753
+ Choose by what the user is DOING, not where the result goes \u2014 the runtime handles the routing.
754
+
755
+ | Gesture intent | LLM writes | Notes |
756
+ | -------------- | ---------- | ----- |
757
+ | 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 \u2014 advisory hint forwarded as event metadata. |
758
+ | 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 \u2192 agent \u2014 see "Observable state via \`contextSpec\`" below. |
759
+ | 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. |
760
+ | 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. |
761
+ | 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. |
762
+
763
+ Every gesture fires a uniform server-side audit envelope (\`ggui_runtime_submit_action\`) so operators see all three patterns in RenderInspector with the same shape.
764
+
765
+ **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.
766
+
767
+ **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 \u2014 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.`;
768
+ var INTERACTIVE_TRAITS = `## Making a primitive interactive \u2014 \`as={Trait}\`
769
+
770
+ Structural primitives (\`Box\`, \`Stack\`, \`Row\`, \`Card\`) have NO \`onClick\` by default. Add interactivity with the \`as\` prop \u2014 a trait, not a wrapper:
771
+
772
+ \`\`\`tsx
773
+ <Card as={Clickable} onClick={() => dispatch('select', { id })}
774
+ hoverStyle={{ boxShadow: 'var(--ggui-shape-shadow-lg)' }}>\u2026</Card>
775
+ \`\`\`
776
+
777
+ - \`as={Clickable}\` \u2192 \`onClick\` + keyboard activation (Enter/Space) + \`role="button"\` + \`hoverStyle\`/\`activeStyle\`/\`cursor\`.
778
+ - \`as={Hoverable}\` \u2192 \`hoverStyle\` only (no click). \`as={Pressable}\` \u2192 \`onPress\` + \`pressStyle\`.
779
+
780
+ \`as={Trait}\` is a PROP \u2014 it does NOT re-nest the JSX. Never write \`<Clickable>\u2026</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 \u2014 the boilerplate already imports them.
781
+
782
+ **Semantic components are already interactive** \u2014 \`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\`.
783
+
784
+ **Never nest two interactive elements.** Interactive content MUST NOT contain other interactive content \u2014 a gesture on the inner control bubbles to the outer one and fires BOTH handlers (one user click \u2192 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}\`) \u2014 never both. A row with a checkbox: put the action on the \`Checkbox onChange\` and leave the row plain.
785
+
786
+ **\`Text\` / \`Heading\` accept NO event handlers and NO \`as\` \u2014 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 \u2026", do ONE of these \u2014 never put the handler on \`Text\`:
787
+
788
+ \`\`\`tsx
789
+ // Click-to-edit a label: wrap the Text in a Clickable structural primitive.
790
+ <Box as={Clickable} onClick={() => setEditingId(task.id)}
791
+ style={{ cursor: 'pointer' }}>
792
+ <Text weight="semibold">{task.title}</Text>
793
+ </Box>
794
+
795
+ // Or pair the label with an explicit edit Button (clearer affordance).
796
+ <Row gap="xs" align="center">
797
+ <Text weight="semibold">{task.title}</Text>
798
+ <Button variant="ghost" size="xs" aria-label="Edit title"
799
+ onClick={() => setEditingId(task.id)}>Edit</Button>
800
+ </Row>
801
+
802
+ // In edit mode, swap the Text for an Input.
803
+ {editingId === task.id
804
+ ? <Input value={draftTitle} onChange={setDraftTitle} label="Task title" />
805
+ : <Text weight="semibold">{task.title}</Text>}
806
+ \`\`\``;
807
+ var ANTI_PATTERNS = `## Anti-patterns \u2014 DO NOT WRITE
808
+
809
+ The 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:
810
+
811
+ - \`useWiredTool\`, \`useClientTool\` \u2014 retired hooks. Replace with \`useAction\` (events) and the named hook from \`@ggui-ai/gadgets\` (browser capabilities).
812
+ - \`dispatch: { kind: 'tool', tool: '...' }\` / \`dispatch: { kind: 'agent', intendedTool: '...' }\` \u2014 retired discriminated-union. Use the flat optional \`nextStep?: '<tool>'\` instead.
813
+ - \`mode: 'host-routed'\` / \`mode: 'tool'\` \u2014 retired \`mode\` field. Same fix: flat \`nextStep?\`.
814
+ - \`broadcast: {...}\` on the contract \u2014 retired top-level field. Use \`streamSpec[channel].source: {tool, args?}\` to declare a tool-fed channel.
815
+ - \`wiredTools\` / \`agentTools\` (top-level) \u2014 retired catalog names. Use \`agentCapabilities.tools\`.
816
+ - \`clientTools\` / \`clientCapabilities.capabilities\` \u2014 retired catalog shapes. Use \`clientCapabilities.gadgets\` (entries declare hooks, not RPC).
817
+ - \`@ggui-ai/client-tools\` \u2014 retired package name. Import gadget hooks from \`@ggui-ai/gadgets\`.
818
+ - \`intendedTool\` \u2014 retired. Use \`nextStep\` (flat).
819
+ - \`props: { properties: {...} }\` as a CONTRACT field \u2014 retired. The contract field is \`propsSpec\` (the wire \`props\` field on render / update still carries VALUES).`;
820
+ var CROSS_REFERENCE_RULES = `## Cross-reference rules
821
+
822
+ When you declare a reference, also declare the catalog entry it points at:
823
+
824
+ - \`actionSpec[X].nextStep = 'fetch_inbox'\` \u2192 \`agentCapabilities.tools.fetch_inbox = { toolInfo: { inputSchema, description?, outputSchema? }, usage?, example? }\` MUST exist. Cross-ref code: \`CTR_REF_NEXT_STEP\`.
825
+ - \`streamSpec[X].source.tool = 'list_messages'\` \u2192 \`agentCapabilities.tools.list_messages\` MUST exist. Cross-ref code: \`CTR_REF_STREAM_SOURCE\`.
826
+ - The catalog entry's schemas MUST be a superset of the referencing spec's schema. Cross-ref code: \`CTR_SCHEMA_INCOMPAT\`.`;
827
+ function renderGadgetCatalogSection(gadgetsSection) {
828
+ return `## clientCapabilities \u2014 registered catalog
829
+
830
+ ${gadgetsSection}
831
+
832
+ Each hook conforms to \`GadgetHook<TOutput, TOptions>\`: call \`start(opts?)\` to fire, read \`{value, status, error, stop?}\`. \`status\` walks through \`idle \u2192 prompting \u2192 active|completed\` or routes to \`denied\` / \`error\` on failure.
833
+
834
+ 3rd-party plugins (Leaflet maps, Mapbox, Stripe, Chart.js, \u2026) 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 \u2014 render validation rejects hooks not in this catalog with \`gadget_not_registered\`.`;
835
+ }
836
+ var CONTEXT_SPEC_SECTION = `## Observable state via \`contextSpec\`
837
+
838
+ When 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 \u2014 **you do NOT write \`useState\` or any \`<Provider>\` wrap yourself**:
839
+
840
+ \`\`\`tsx
841
+ import { useGguiContext } from '@ggui-ai/wire';
842
+
843
+ export default function Component(props: Props) {
844
+ // AUTO-GENERATED \u2014 do not remove or rename:
845
+ const [currentStep, setCurrentStep] = useGguiContext<number>('currentStep');
846
+ const [draftText, setDraftText] = useGguiContext<string>('draftText');
847
+
848
+ // Plain JSX. No Provider wrap. The runtime already wrapped your
849
+ // component in nested SingleSlotProviders before this code ran.
850
+ return (
851
+ <Container>
852
+ <Text>Step {currentStep}</Text>
853
+ <Input value={draftText} onChange={(e) => setDraftText(e.target.value)} />
854
+ <Button onClick={() => setCurrentStep((s) => s + 1)}>Next</Button>
855
+ </Container>
856
+ );
857
+ }
858
+ \`\`\`
859
+
860
+ For every declared slot you have **\`slotName\` + \`setSlotName\`** in scope:
861
+ - **Read** the value to render: \`<Text>Step {currentStep}</Text>\`
862
+ - **Write** via the setter: \`setCurrentStep(s => s + 1)\` (in callbacks, effects, anywhere)
863
+
864
+ Every value change is mirrored to the host LLM's context automatically (debounced, default 300ms \u2014 adjustable per-slot via \`entry.debounceMs\` in the contract). The agent sees the user's interaction state \u2014 drafts, current step, hover, selection \u2014 without you calling any API.
865
+
866
+ **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.
867
+
868
+ **When NOT to use it.** Local UI state the contract did NOT declare \u2014 \`isDropdownOpen\`, hover flags, animation phase, ephemeral toggles. For those, use a plain \`useState\` directly. The runtime ignores undeclared state.
869
+
870
+ **\`contextSpec\` direction is one-way: client \u2192 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\` \u2014 there is no return path.
871
+
872
+ **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.`;
873
+ var DATA_PARAMETERIZATION = `## Data Parameterization (CRITICAL)
874
+
875
+ Generated 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:
876
+
877
+ \`\`\`tsx
878
+ // BAD \u2014 hardcoded, only works for Tokyo
879
+ const city = "Tokyo";
880
+ const temp = 18;
881
+
882
+ // GOOD \u2014 parameterized via props with defaults from the request
883
+ interface Props {
884
+ city?: string;
885
+ temperature?: number;
886
+ }
887
+ export default function WeatherCard({ city = "Tokyo", temperature = 18 }: Props) {
888
+ // A controller can override for Seoul, Paris, etc.
889
+ }
890
+ \`\`\`
891
+
892
+ Rules:
893
+ 1. All request-specific data \u2192 props with defaults. City names, tickers, user names, dates, counts.
894
+ 2. Layout and styling are universal. Colors, spacing, structure \u2014 these are the reusable part.
895
+ 3. Default values come from the current request \u2014 so the component renders correctly standalone.
896
+ 4. Props interface must be typed and exported.`;
897
+ var COMPONENT_STRUCTURE = `## Component Structure
898
+
899
+ Keep JSX nesting depth to 3\u20135 levels. When deeper, extract repeated/complex sections into helper components \u2014 named functions defined above the main Component in the same file. Helpers take data + callbacks via props; they don't own state.
900
+
901
+ \`\`\`tsx
902
+ import { useState } from 'react';
903
+ import { Container, Card, Stack, Text, Button, Input } from '@ggui-ai/design';
904
+
905
+ interface Props {
906
+ onSubmit?: (data: unknown) => void;
907
+ }
908
+
909
+ function ItemCard({ item, onEdit }: { item: Item; onEdit: (id: string) => void }) {
910
+ return <Card padding="md">\u2026</Card>;
911
+ }
912
+
913
+ export default function GeneratedComponent({ onSubmit }: Props) {
914
+ return (
915
+ <Container>
916
+ {items.map((item) => <ItemCard key={item.id} item={item} onEdit={handleEdit} />)}
917
+ </Container>
918
+ );
919
+ }
920
+ \`\`\``;
921
+
922
+ // src/boilerplate/free-design-prompt.ts
923
+ var FREE_GESTURE_SURFACE = `## One gesture surface per action binding
924
+
925
+ Every \`useAction\` binding is wired to exactly ONE interactive surface. Interactive content MUST NOT contain other interactive content that dispatches the same binding \u2014 a click on the inner control bubbles to the outer handler and the action fires TWICE, so a toggle-style action silently reverts the user's change. Concretely: never put a \`<button>\`, \`<a>\`, \`<input>\`, \`<select>\`, an element with \`role="button"\`, or any element with its own \`onClick\`, inside a \`<div>\` / \`<li>\` / \`<tr>\` / \`<Card>\` whose own \`onClick\` calls the same binding. EITHER the whole row is the trigger (interactive container, no interactive children) OR an inner control is the trigger (plain container) \u2014 never both. Tier-0 fails the nested shape with \`double-wired-action:certain\`. A row with a checkbox: put the action on the checkbox's \`onChange\` and leave the row plain. \`stopPropagation\` is not a fix \u2014 pick one surface.`;
926
+ var FREE_DESIGN_FREEDOM = `## Design freedom
927
+
928
+ You are not required to compose from the \`@ggui-ai/design\` primitives. Compose with raw HTML elements (\`<div>\`, \`<section>\`, \`<button>\`, \`<input>\`, \`<ul>\`, \`<table>\`, \u2026), inline \`style\` props and \`<style>\` blocks \u2014 regular CSS, \`@media\` and \`@container\` queries, \`@keyframes\`, \`:hover\` / \`:focus-visible\` (the host CSP permits \`'unsafe-inline'\` styles). Any layout: CSS grid, flexbox, absolute positioning, sticky headers. The runtime injects NO Tailwind and NO reset stylesheet \u2014 a raw element renders unstyled until your CSS styles it, so bring the CSS you need. Use class selectors in \`<style>\` blocks (an \`#id\` selector that reads as hex digits trips the color check).
929
+
930
+ \`@ggui-ai/design\` stays importable \u2014 \`import { Skeleton, EmptyState, Icon } from '@ggui-ai/design'\` \u2014 use a primitive when it saves work, skip it when it constrains you. Its props are documented in the optional catalog at the end of this prompt.
931
+
932
+ Spacing, typography, radius, shadow geometry and layout values MAY be literals: \`padding: '20px'\`, \`fontSize: 'clamp(1rem, 2vw, 1.5rem)'\`, \`borderRadius: 12\`, \`gap: '0.75rem'\`, \`boxShadow: '0 8px 24px var(--ggui-color-outlineVariant)'\`. Color is the one exception \u2014 next section.`;
933
+ var COLOR_PREFIX = "--ggui-color-";
934
+ var RAMP_FAMILIES = ["primary", "neutral", "success", "warning", "error", "info"];
935
+ var SEMANTIC_ROLES = [
936
+ { names: ["ground", "onGround"], role: "the page / chat canvas behind everything + its text" },
937
+ { names: ["container", "onContainer"], role: "a card, a bubble, a panel + body text on it" },
938
+ { names: ["elevated", "onElevated"], role: "popover, menu, modal, toast \u2014 floats above a container" },
939
+ { names: ["sunken", "onSunken"], role: "wells, inputs at rest, code blocks + secondary text" },
940
+ { names: ["ground-subtle", "ground-gradient"], role: "quiet canvas fills" },
941
+ { names: ["onPrimary"], role: "text on the brand color" },
942
+ { names: ["outline", "outlineVariant"], role: "borders + dividers" },
943
+ { names: ["onError"], role: "text on an error fill" }
944
+ ];
945
+ function colorVocabularyFromManifest(manifest) {
946
+ const colors = manifest.filter((t) => t.startsWith(COLOR_PREFIX)).map((t) => t.slice(COLOR_PREFIX.length));
947
+ const ramps = [];
948
+ const claimed = /* @__PURE__ */ new Set();
949
+ for (const family of RAMP_FAMILIES) {
950
+ const steps = [];
951
+ for (const name of colors) {
952
+ const m = new RegExp(`^${family}-(\\d+)$`).exec(name);
953
+ if (m) {
954
+ steps.push(Number(m[1]));
955
+ claimed.add(name);
956
+ }
957
+ }
958
+ if (steps.length === 0) continue;
959
+ steps.sort((a, b) => a - b);
960
+ const bare = colors.includes(family);
961
+ if (bare) claimed.add(family);
962
+ ramps.push({ family, steps, bare });
963
+ }
964
+ const roles = colors.filter((n) => !claimed.has(n)).sort();
965
+ return { ramps, roles };
966
+ }
967
+ function renderRamp(r) {
968
+ return `\`${r.family}-${r.steps.join("/")}\`${r.bare ? ` (plus bare \`${r.family}\`)` : ""}`;
969
+ }
970
+ function renderFreeColorRule(manifest = consumedTokenManifest) {
971
+ const { ramps, roles } = colorVocabularyFromManifest(manifest);
972
+ const brand = ramps.filter((r) => r.family === "primary" || r.family === "neutral");
973
+ const state = ramps.filter((r) => r.family !== "primary" && r.family !== "neutral");
974
+ const roleLines = [];
975
+ const named = /* @__PURE__ */ new Set();
976
+ for (const g of SEMANTIC_ROLES) {
977
+ const present = g.names.filter((n) => roles.includes(n));
978
+ if (present.length === 0) continue;
979
+ for (const n of present) named.add(n);
980
+ roleLines.push(`${present.map((n) => `\`${n}\``).join(" / ")} (${g.role})`);
981
+ }
982
+ const other = roles.filter((n) => !named.has(n));
983
+ if (other.length > 0) roleLines.push(`other roles: ${other.map((n) => `\`${n}\``).join(", ")}`);
984
+ const vocabulary = [
985
+ roleLines.length > 0 ? `- Semantic roles cover most needs: ${roleLines.join("; ")}.` : "",
986
+ brand.length > 0 ? `- Brand + neutral ramps (every step that exists, nothing else): ${brand.map(renderRamp).join(", ")}.` : "",
987
+ state.length > 0 ? `- State ramps (every step that exists, nothing else): ${state.map(renderRamp).join(", ")}.` : "",
988
+ "- A step not listed does not exist and renders unset; pick the nearest listed step."
989
+ ].filter((l) => l.length > 0).join("\n");
990
+ return `## Color stays tokenized (the one hard styling rule)
991
+
992
+ Brand-bearing color \u2014 text, backgrounds, borders, fills, gradient stops, focus rings, shadow tints \u2014 comes ONLY from the closed \`--ggui-color-*\` token manifest, referenced BARE: \`color: 'var(--ggui-color-onContainer)'\`, \`background: 'var(--ggui-color-primary-50)'\`, \`border: '1px solid var(--ggui-color-outline)'\`, \`linear-gradient(135deg, var(--ggui-color-primary-500), var(--ggui-color-primary-700))\`.
993
+
994
+ - No hex (\`#7c3aed\`), no \`rgb()\` / \`rgba()\` / \`hsl()\` / \`hsla()\`, no CSS named colors (\`red\`, \`slategray\`) \u2014 anywhere in the file, including \`<style>\` blocks and shadows. Tier-0 fails them (\`tokens:hex-color\`, \`tokens:hardcoded-color-fn\`, \`tokens:named-color\`). \`transparent\`, \`currentColor\` and \`inherit\` are fine.
995
+ - No literal fallback inside ANY token reference: \`var(--ggui-color-primary-600)\` bare, never \`var(--ggui-color-primary-600, #0284c7)\` \u2014 the runtime injects every token on \`:root\`, and a fallback paints the wrong brand exactly when the operator's theme matters (\`tokens:token-fallback\`). This holds for every \`--ggui-*\` token you reference, not only colors.
996
+ - Only names from the manifest (listed at the end of this prompt) exist \u2014 an invented \`--ggui-color-*\` name renders unset (\`tokens:off-manifest-token\`).
997
+ - Shadows: \`var(--ggui-shape-shadow-sm|md|lg|xl)\`, or a literal offset/blur whose color is a token \u2014 never an \`rgba()\` tint.
998
+ - Why: the operator switches the whole app's theme (light, dark, branded) by redefining these variables. A component that reads them is on-brand everywhere; one that hardcodes color is off-brand everywhere but the default.
999
+
1000
+ The color vocabulary (rendered from the manifest \u2014 these names and steps, exactly):
1001
+ ${vocabulary}`;
1002
+ }
1003
+ var FREE_COLOR_RULE = renderFreeColorRule();
1004
+ var FREE_HOST_ENVELOPE = `## Where this renders
1005
+
1006
+ The compiled component is loaded into a sandboxed iframe by an MCP Apps host (chat clients, the ggui console, embedded panels):
1007
+
1008
+ - **Sandbox**: \`allow-scripts allow-forms\`, no same-origin. The only channel to the outside is \`postMessage\` through the wire hooks \u2014 the component never talks to a server itself.
1009
+ - **No network from the component**: \`fetch\`, \`XMLHttpRequest\`, \`WebSocket\`, dynamic \`import()\` fail tier-0 and the CSP (\`connect-src 'none'\` on spec hosts). No \`<link rel="stylesheet">\`, no \`@import url()\`, no CDN scripts, no web fonts from a CDN \u2014 use \`var(--ggui-font-family-sans)\` / \`var(--ggui-font-family-mono)\` (system stacks) or a generic family.
1010
+ - **No host document access**: \`window.*\`, \`document.*\` (other than the intercepted \`requestFullscreen\` / \`exitFullscreen\`), \`localStorage\`, \`sessionStorage\`, \`navigator\`, \`location\`, \`history\`, \`innerHTML\` / \`dangerouslySetInnerHTML\`, \`<script>\` \u2014 all rejected.
1011
+ - **Props arrive through \`_meta["ai.ggui/render"]\`** on the host side and reach you as \`props\`; later repaints (\`ggui_amend\`) update the SAME mounted component \u2014 see "Defensive coding".
1012
+ - **Display modes**: the host advertises \`availableDisplayModes\` (\`inline\` | \`fullscreen\` | \`pip\`); \`el.requestFullscreen()\` asks the host to switch \u2014 never assume it will.
1013
+ - **Size**: the host sets the iframe's \`containerDimensions\` once per render; there is no live resize notification \u2014 a resize is a re-render, so layout must be fluid (\`width: 100%\`, \`max-width\`, no fixed width) and hold at any width inside the canvas range above.`;
1014
+ var FREE_BUDGETS = `## Budgets (deterministic caps)
1015
+
1016
+ - Source \u2264 50 KB and \u2264 500 lines.
1017
+ - Compiled bundle \u2264 2 MB.
1018
+ - One file, one \`export default function Component(props: Props)\`.`;
1019
+ var FREE_IMPORTS_AND_SECURITY = `## Imports & security (what you may import, what you may not call)
1020
+
1021
+ Import ONLY from: \`react\`, \`react-dom\`, \`@ggui-ai/design\` (single barrel \u2014 no \`/primitives\` / \`/components\` subpaths), \`@ggui-ai/wire\`, \`@ggui-ai/gadgets\`, or a gadget package the contract declares \u2014 never \`@ggui-ai/wire/internal\`. The iframe runtime rewrites exactly these specifiers to in-bundle shims; ANY other import fails at module evaluation and blanks the iframe (tier-0 \`imports\` fail). No \`require()\`.
1022
+
1023
+ Never call \`eval()\`, \`Function()\`, \`fetch()\` or the host-document APIs listed under "Where this renders" \u2014 tier-0 \`security\` fails them and the sandbox blocks them anyway.`;
1024
+ var FREE_RESPONSIVE_INVARIANT = `## Responsive invariant
1025
+
1026
+ The component must fit the host-supplied iframe width at every point of the canvas range: \`width: 100%\` (plus \`max-width\` where you want to cap), never a fixed width, no horizontal scroll. Use \`@media\` / \`@container\` queries, \`clamp()\`, \`minmax()\`, \`auto-fit\` grids and \`flex-wrap\` freely. Compact chrome on \`xs-chat-card\` (the host draws the card border and shadow); own the chrome on the fullscreen canvases (\`mobile-fullscreen-small\`, \`md\`, \`lg\`, \`xl\`).`;
1027
+ var FREE_ACCESSIBILITY = `## Accessibility (REQUIRED)
1028
+
1029
+ With raw elements YOU own the semantics \u2014 nothing is accessible by construction unless you import a \`@ggui-ai/design\` primitive (those carry their own roles / labels / keyboard handling; don't re-declare ARIA on them).
1030
+
1031
+ 1. **Interactive = a real control.** A click target is a \`<button type="button">\` or an \`<a href>\` \u2014 never a bare \`<div onClick>\`. If a non-button element must be clickable, add \`role="button"\`, \`tabIndex={0}\` and an \`onKeyDown\` handling Enter/Space.
1032
+ 2. **Form inputs have labels.** \`<label htmlFor={id}>\` paired with the input's \`id\`, or \`aria-label\`; errors via \`aria-invalid\` + \`aria-describedby\`.
1033
+ 3. **Images have \`alt\`** (\`alt=""\` for decorative). Icon-only buttons need \`aria-label\`; decorative icons and emoji are \`aria-hidden="true"\`.
1034
+ 4. **Live & streaming data** (a \`useStream\` \`.latest\` value, counters, clocks, flashing prices) sits in an \`aria-live="polite"\` (or \`role="status"\`) region so screen readers announce the change.
1035
+ 5. **Headings nest**: one \`<h1>\` per screen, \`<h2>\` for sections, \`<h3>\` below \u2014 never skipped or inverted.
1036
+ 6. **Busy state is announced**: \`<button disabled={isLoading} aria-busy={isLoading}>{isLoading ? 'Submitting\u2026' : 'Submit'}</button>\`.
1037
+ 7. **Stateful controls announce state**: \`role="checkbox"\` + \`aria-checked\` 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 mark) is never the only carrier of state.
1038
+ 8. **Focus is visible** \u2014 style \`:focus-visible\` with a token color; never \`outline: none\` without a replacement.`;
1039
+ var FREE_QUALITY_CHECKLIST = `## Quality Checklist (verify before returning)
1040
+
1041
+ - [ ] Imports ONLY from: react, react-dom, @ggui-ai/design, @ggui-ai/wire, @ggui-ai/gadgets (+ contract gadget packages)
1042
+ - [ ] ZERO literal colors \u2014 every color is a bare \`var(--ggui-color-*)\` from the manifest; no hex / rgb() / hsl() / named colors, no fallbacks \u2014 in \`style\` props AND \`<style>\` blocks
1043
+ - [ ] Fluid width (\`width: 100%\`, \`max-width\`), holds across the whole canvas range, no horizontal scroll
1044
+ - [ ] Typed Props interface exported; request-specific data is a prop with default
1045
+ - [ ] Every \`useAction\` binding is wired to exactly ONE gesture surface \u2014 no handler on both a parent and a child
1046
+ - [ ] Real controls (\`<button>\`, \`<a>\`, \`<input>\` + \`<label>\`), \`alt\` on images, \`aria-label\` on icon-only buttons
1047
+ - [ ] State is ARIA-expressed (\`aria-checked\` / \`aria-pressed\` / \`aria-selected\` / \`aria-expanded\`) \u2014 never style-only
1048
+ - [ ] Live/streaming regions wrapped in \`aria-live="polite"\`
1049
+ - [ ] Headings nest \u2014 one \`<h1>\`, then \`<h2>\` / \`<h3>\` \u2014 never skipped or inverted
1050
+ - [ ] No \`fetch\` / \`eval\` / \`window\` / \`document\` / \`localStorage\` / external stylesheets or fonts
1051
+ - [ ] Source \u2264 50 KB / \u2264 500 lines; wire hooks (\`useAction\`, \`useStream\`, \`useGguiContext\`) kept and consumed`;
1052
+ var FREE_SHAPE_GUIDANCE_NOTE = "In this mode the design-package components named above (`<Stepper>`, `<Modal>`, `<Card>`, `<Row>`, `<CardGrid>`) are defaults, not requirements \u2014 any composition that satisfies the behavioural rule (track the step index in state, a close affordance + focus trap, `key={item.id}`, no horizontal scroll) is acceptable. The crash anti-patterns are mandatory.";
1053
+ var TOKEN_GROUPS = [
1054
+ { label: "Color (mandatory for every color)", prefixes: ["--ggui-color-"], note: "" },
1055
+ { label: "Spacing (optional \u2014 literals are fine)", prefixes: ["--ggui-spacing-"], note: "" },
1056
+ { label: "Typography (optional)", prefixes: ["--ggui-font-"], note: "" },
1057
+ { label: "Radius (optional)", prefixes: ["--ggui-shape-radius-"], note: "" },
1058
+ { label: "Shadow (optional)", prefixes: ["--ggui-shape-shadow-"], note: "" }
1059
+ ];
1060
+ function renderTokenVocabulary(manifest = consumedTokenManifest) {
1061
+ const sorted = [...manifest].sort();
1062
+ const claimed = /* @__PURE__ */ new Set();
1063
+ const lines = [
1064
+ "### Reference (optional): theme token vocabulary",
1065
+ "",
1066
+ "The closed manifest \u2014 the ONLY `--ggui-*` names the runtime defines on `:root`. Color names are mandatory for color; the rest are optional conveniences.",
1067
+ ""
1068
+ ];
1069
+ for (const group of TOKEN_GROUPS) {
1070
+ const names = sorted.filter((t) => group.prefixes.some((p) => t.startsWith(p)));
1071
+ if (names.length === 0) continue;
1072
+ for (const n of names) claimed.add(n);
1073
+ lines.push(`- **${group.label}**: ${names.map((n) => `\`${n}\``).join(", ")}`);
1074
+ }
1075
+ const other = sorted.filter((t) => !claimed.has(t));
1076
+ if (other.length > 0) {
1077
+ lines.push(`- **Other**: ${other.map((n) => `\`${n}\``).join(", ")}`);
1078
+ }
1079
+ return lines.join("\n");
1080
+ }
1081
+ function buildFreeDesignPrompt(inputs) {
1082
+ const axisSection = inputs.axisSection.length > 0 ? `${inputs.axisSection}
1083
+ ${FREE_SHAPE_GUIDANCE_NOTE}
1084
+ ` : "";
1085
+ const head = `You are ggui's UI builder. You receive a typed boilerplate and fill it in using apply_changes.
1086
+
1087
+ ## Your Task
1088
+ ${inputs.userRequest}
1089
+
1090
+ ## Rendering canvas
1091
+ ${describeCanvas(inputs.canvas)}
1092
+
1093
+ ## How It Works
1094
+ 1. Read the boilerplate \u2014 typed Props and wire hooks are pre-configured; the JSX body and its styling are yours to compose
1095
+ 2. Respond with one apply_changes call \u2014 add state, helpers, styles and JSX
1096
+ 3. If compilation or evaluation fails, you'll get errors to fix in the next turn
1097
+
1098
+ ${inputs.criteriaBlock}
1099
+ ${axisSection}
1100
+ `;
1101
+ const sections = [
1102
+ PROTOCOL_NOTES,
1103
+ CONTRACT_SURFACE,
1104
+ DEFENSIVE_CODING,
1105
+ GESTURE_ROUTING,
1106
+ FREE_GESTURE_SURFACE,
1107
+ ANTI_PATTERNS,
1108
+ CROSS_REFERENCE_RULES,
1109
+ renderGadgetCatalogSection(inputs.gadgetsSection),
1110
+ CONTEXT_SPEC_SECTION,
1111
+ `## Reference: Wire Hooks
1112
+ ${inputs.wireDoc}`,
1113
+ FREE_DESIGN_FREEDOM,
1114
+ FREE_COLOR_RULE,
1115
+ FREE_HOST_ENVELOPE,
1116
+ FREE_BUDGETS,
1117
+ FREE_IMPORTS_AND_SECURITY,
1118
+ DATA_PARAMETERIZATION,
1119
+ COMPONENT_STRUCTURE,
1120
+ FREE_RESPONSIVE_INVARIANT,
1121
+ FREE_ACCESSIBILITY,
1122
+ FREE_QUALITY_CHECKLIST,
1123
+ renderTokenVocabulary(),
1124
+ `### Reference (optional): \`@ggui-ai/design\` component catalog
1125
+
1126
+ Optional \u2014 import a primitive only when it helps. Raw HTML + your own CSS is a first-class choice.
1127
+
1128
+ ${inputs.primitivesDoc}`
1129
+ ];
1130
+ return head + sections.join("\n\n") + "\n";
1131
+ }
610
1132
  var VIRTUAL_DTS_PATH = "/__gadget__.d.ts";
611
1133
  var EXTRACTOR_COMPILER_OPTIONS = {
612
1134
  target: ts.ScriptTarget.ESNext,
@@ -929,7 +1451,8 @@ function buildSystemPrompt(inputs) {
929
1451
  const scr = inputs.screen ?? "universal";
930
1452
  const shellDesc = SHELL_DESCRIPTIONS[shell] ?? SHELL_DESCRIPTIONS.fullscreen;
931
1453
  const screenDesc = SCREEN_DESCRIPTIONS[scr] ?? SCREEN_DESCRIPTIONS.universal;
932
- const criteriaBlock = inputs.criteriaBlock ?? buildCodingCriteriaSummary();
1454
+ const designMode = inputs.designMode ?? DEFAULT_DESIGN_MODE;
1455
+ const criteriaBlock = inputs.criteriaBlock ?? buildCodingCriteriaSummary(designMode);
933
1456
  const pitfallsBlock = inputs.pitfallsBlock ?? "";
934
1457
  const designSystemDocs = inputs.designSystemDocs ?? "";
935
1458
  const primitivesDoc = inputs.primitivesDoc ?? "";
@@ -942,6 +1465,17 @@ function buildSystemPrompt(inputs) {
942
1465
  ## Shape Guidance
943
1466
  ${inputs.axisDelta}
944
1467
  ` : "";
1468
+ if (designMode === "free") {
1469
+ return buildFreeDesignPrompt({
1470
+ userRequest: inputs.userRequest,
1471
+ canvas: inputs.canvas ?? canvasForRendering(inputs.shellType, inputs.screen),
1472
+ axisSection,
1473
+ criteriaBlock,
1474
+ wireDoc,
1475
+ primitivesDoc,
1476
+ gadgetsSection
1477
+ });
1478
+ }
945
1479
  return `You are ggui's UI builder. You receive a typed boilerplate and fill it in using apply_changes.
946
1480
 
947
1481
  ## Your Task
@@ -958,172 +1492,17 @@ ${inputs.userRequest}
958
1492
 
959
1493
  ${criteriaBlock}
960
1494
  ${axisSection}
961
- ## Protocol Notes
962
- The 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:
963
- 1. **Do NOT delete any pre-declared hook.** \`self_check\` fails with \`wire_preservation:<kind>:<name>\` if you remove one.
964
- 2. **Consume every hook binding** somewhere in the component \u2014 in JSX, a callback, or an effect. Unused bindings fail lint with \`no-unused-vars\`.
965
- 3. **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 \u2014 your job is to honor what's declared.
966
-
967
- Renaming a binding is fine \u2014 the wiring is the string-literal argument, not the identifier.
968
-
969
- ## Contract surface \u2014 four specs + two catalogs
970
-
971
- A \`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:
972
-
973
- | Surface | Direction | Role |
974
- | -------------------- | -------------------------- | -------------------------------------------------------------------- |
975
- | \`propsSpec\` | server \u2192 UI (one-shot) | Initial render values delivered once at \`ggui_render\` |
976
- | \`streamSpec\` | agent \u2192 UI (many) | Typed channels for live updates via \`ggui_emit\` |
977
- | \`actionSpec\` | UI \u2192 agent (events) | Discrete events driving the agent's next turn (consumed via \`ggui_consume\`) |
978
- | \`contextSpec\` | UI \u2192 server (state mirror) | UI state the agent observes between turns |
979
- | \`agentCapabilities.tools\` | catalog | Tools the contract references via \`actionSpec[*].nextStep\` and \`streamSpec[*].source.tool\` |
980
- | \`clientCapabilities.gadgets\` | catalog | Browser-capability gadget hooks the component code mounts (e.g., \`useGeolocation\`) |
981
-
982
- **Placement rule for inbound specs**: actions drive turns; context observes state. There is no third category.
983
-
984
- **Data vs behavior**: the contract describes data flow; the component code describes behavior. Scroll, focus, toast, animation, clipboard write \u2014 all component code, never contract fields.
985
-
986
- ## Defensive coding for absent / late-arriving data
987
-
988
- Props 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.**
989
-
990
- - **Optional contract props**: a \`Props\` field marked \`?\` in the boilerplate may be omitted by the agent ENTIRELY \u2014 the wire gate only enforces \`required: true\` entries, and the harness verifies your component with those props stripped. Guard them (\`?? default\`, \`?.\`, or an empty-state branch) from the FIRST render.
991
- - **Array iteration**: always default to \`[]\` before \`.map\`/\`.filter\`/\`.length\`. Use \`(props.items ?? []).map(...)\` not \`props.items.map(...)\`. Same for stream.all, stream.latest, etc.
992
- - **Object access**: optional-chain through nested fields. \`props.user?.name ?? 'Anonymous'\` not \`props.user.name\`.
993
- - **Number ops**: default before arithmetic. \`(props.count ?? 0) + 1\` not \`props.count + 1\`.
994
- - **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 \u2014 guard before reading \`.foo\`.
995
- - **Stream reconciliation**: when a stream event carries an \`action\` discriminant (e.g. \`create | move | edit | delete\`), the channel is a CRUD feed \u2014 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 \u2014 and handle an event whose id is not yet present (a \`create\` for an unknown item) by inserting it, not ignoring it.
996
- - **Props re-sync on repaint**: props the agent owns are the source of truth for display \u2014 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 \u2014 \`useEffect(() => setCount(props.count ?? 0), [props.count])\` \u2014 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.
997
- - **Loading state**: while data is still absent, render \`<Skeleton>\` placeholders \u2014 never a blank screen. \`<Skeleton variant="text" />\` for a text line, \`variant="circle"\` for an avatar slot, default \`rect\` for a block.
998
- - **Empty state**: when a list or results array is empty, render \`<EmptyState title="\u2026" description="\u2026" />\` \u2014 a region that renders nothing when empty looks broken to the user.
999
-
1000
- Unhandled \`Cannot read properties of undefined\` errors trip the iframe error boundary and the user sees "Something went wrong" \u2014 a regression class the runtime can't recover from.
1001
-
1002
- ## Picking the right primitive for user gestures
1003
-
1004
- Choose by what the user is DOING, not where the result goes \u2014 the runtime handles the routing.
1005
-
1006
- | Gesture intent | LLM writes | Notes |
1007
- | -------------- | ---------- | ----- |
1008
- | 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 \u2014 advisory hint forwarded as event metadata. |
1009
- | 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 \u2192 agent \u2014 see "Observable state via \`contextSpec\`" below. |
1010
- | 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. |
1011
- | 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. |
1012
- | 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. |
1013
-
1014
- Every gesture fires a uniform server-side audit envelope (\`ggui_runtime_submit_action\`) so operators see all three patterns in RenderInspector with the same shape.
1015
-
1016
- **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.
1017
-
1018
- **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 \u2014 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.
1019
-
1020
- ## Making a primitive interactive \u2014 \`as={Trait}\`
1021
-
1022
- Structural primitives (\`Box\`, \`Stack\`, \`Row\`, \`Card\`) have NO \`onClick\` by default. Add interactivity with the \`as\` prop \u2014 a trait, not a wrapper:
1023
-
1024
- \`\`\`tsx
1025
- <Card as={Clickable} onClick={() => dispatch('select', { id })}
1026
- hoverStyle={{ boxShadow: 'var(--ggui-shape-shadow-lg)' }}>\u2026</Card>
1027
- \`\`\`
1028
-
1029
- - \`as={Clickable}\` \u2192 \`onClick\` + keyboard activation (Enter/Space) + \`role="button"\` + \`hoverStyle\`/\`activeStyle\`/\`cursor\`.
1030
- - \`as={Hoverable}\` \u2192 \`hoverStyle\` only (no click). \`as={Pressable}\` \u2192 \`onPress\` + \`pressStyle\`.
1031
-
1032
- \`as={Trait}\` is a PROP \u2014 it does NOT re-nest the JSX. Never write \`<Clickable>\u2026</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 \u2014 the boilerplate already imports them.
1033
-
1034
- **Semantic components are already interactive** \u2014 \`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\`.
1035
-
1036
- **Never nest two interactive elements.** Interactive content MUST NOT contain other interactive content \u2014 a gesture on the inner control bubbles to the outer one and fires BOTH handlers (one user click \u2192 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}\`) \u2014 never both. A row with a checkbox: put the action on the \`Checkbox onChange\` and leave the row plain.
1037
-
1038
- **\`Text\` / \`Heading\` accept NO event handlers and NO \`as\` \u2014 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 \u2026", do ONE of these \u2014 never put the handler on \`Text\`:
1039
-
1040
- \`\`\`tsx
1041
- // Click-to-edit a label: wrap the Text in a Clickable structural primitive.
1042
- <Box as={Clickable} onClick={() => setEditingId(task.id)}
1043
- style={{ cursor: 'pointer' }}>
1044
- <Text weight="semibold">{task.title}</Text>
1045
- </Box>
1046
-
1047
- // Or pair the label with an explicit edit Button (clearer affordance).
1048
- <Row gap="xs" align="center">
1049
- <Text weight="semibold">{task.title}</Text>
1050
- <Button variant="ghost" size="xs" aria-label="Edit title"
1051
- onClick={() => setEditingId(task.id)}>Edit</Button>
1052
- </Row>
1053
-
1054
- // In edit mode, swap the Text for an Input.
1055
- {editingId === task.id
1056
- ? <Input value={draftTitle} onChange={setDraftTitle} label="Task title" />
1057
- : <Text weight="semibold">{task.title}</Text>}
1058
- \`\`\`
1059
-
1060
- ## Anti-patterns \u2014 DO NOT WRITE
1061
-
1062
- The 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:
1063
-
1064
- - \`useWiredTool\`, \`useClientTool\` \u2014 retired hooks. Replace with \`useAction\` (events) and the named hook from \`@ggui-ai/gadgets\` (browser capabilities).
1065
- - \`dispatch: { kind: 'tool', tool: '...' }\` / \`dispatch: { kind: 'agent', intendedTool: '...' }\` \u2014 retired discriminated-union. Use the flat optional \`nextStep?: '<tool>'\` instead.
1066
- - \`mode: 'host-routed'\` / \`mode: 'tool'\` \u2014 retired \`mode\` field. Same fix: flat \`nextStep?\`.
1067
- - \`broadcast: {...}\` on the contract \u2014 retired top-level field. Use \`streamSpec[channel].source: {tool, args?}\` to declare a tool-fed channel.
1068
- - \`wiredTools\` / \`agentTools\` (top-level) \u2014 retired catalog names. Use \`agentCapabilities.tools\`.
1069
- - \`clientTools\` / \`clientCapabilities.capabilities\` \u2014 retired catalog shapes. Use \`clientCapabilities.gadgets\` (entries declare hooks, not RPC).
1070
- - \`@ggui-ai/client-tools\` \u2014 retired package name. Import gadget hooks from \`@ggui-ai/gadgets\`.
1071
- - \`intendedTool\` \u2014 retired. Use \`nextStep\` (flat).
1072
- - \`props: { properties: {...} }\` as a CONTRACT field \u2014 retired. The contract field is \`propsSpec\` (the wire \`props\` field on render / update still carries VALUES).
1073
-
1074
- ## Cross-reference rules
1075
-
1076
- When you declare a reference, also declare the catalog entry it points at:
1077
-
1078
- - \`actionSpec[X].nextStep = 'fetch_inbox'\` \u2192 \`agentCapabilities.tools.fetch_inbox = { toolInfo: { inputSchema, description?, outputSchema? }, usage?, example? }\` MUST exist. Cross-ref code: \`CTR_REF_NEXT_STEP\`.
1079
- - \`streamSpec[X].source.tool = 'list_messages'\` \u2192 \`agentCapabilities.tools.list_messages\` MUST exist. Cross-ref code: \`CTR_REF_STREAM_SOURCE\`.
1080
- - The catalog entry's schemas MUST be a superset of the referencing spec's schema. Cross-ref code: \`CTR_SCHEMA_INCOMPAT\`.
1081
-
1082
- ## clientCapabilities \u2014 registered catalog
1083
-
1084
- ${gadgetsSection}
1085
-
1086
- Each hook conforms to \`GadgetHook<TOutput, TOptions>\`: call \`start(opts?)\` to fire, read \`{value, status, error, stop?}\`. \`status\` walks through \`idle \u2192 prompting \u2192 active|completed\` or routes to \`denied\` / \`error\` on failure.
1087
-
1088
- 3rd-party plugins (Leaflet maps, Mapbox, Stripe, Chart.js, \u2026) 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 \u2014 render validation rejects hooks not in this catalog with \`gadget_not_registered\`.
1089
-
1090
- ## Observable state via \`contextSpec\`
1091
-
1092
- When 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 \u2014 **you do NOT write \`useState\` or any \`<Provider>\` wrap yourself**:
1093
-
1094
- \`\`\`tsx
1095
- import { useGguiContext } from '@ggui-ai/wire';
1096
-
1097
- export default function Component(props: Props) {
1098
- // AUTO-GENERATED \u2014 do not remove or rename:
1099
- const [currentStep, setCurrentStep] = useGguiContext<number>('currentStep');
1100
- const [draftText, setDraftText] = useGguiContext<string>('draftText');
1101
-
1102
- // Plain JSX. No Provider wrap. The runtime already wrapped your
1103
- // component in nested SingleSlotProviders before this code ran.
1104
- return (
1105
- <Container>
1106
- <Text>Step {currentStep}</Text>
1107
- <Input value={draftText} onChange={(e) => setDraftText(e.target.value)} />
1108
- <Button onClick={() => setCurrentStep((s) => s + 1)}>Next</Button>
1109
- </Container>
1110
- );
1111
- }
1112
- \`\`\`
1113
-
1114
- For every declared slot you have **\`slotName\` + \`setSlotName\`** in scope:
1115
- - **Read** the value to render: \`<Text>Step {currentStep}</Text>\`
1116
- - **Write** via the setter: \`setCurrentStep(s => s + 1)\` (in callbacks, effects, anywhere)
1117
-
1118
- Every value change is mirrored to the host LLM's context automatically (debounced, default 300ms \u2014 adjustable per-slot via \`entry.debounceMs\` in the contract). The agent sees the user's interaction state \u2014 drafts, current step, hover, selection \u2014 without you calling any API.
1119
-
1120
- **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.
1121
-
1122
- **When NOT to use it.** Local UI state the contract did NOT declare \u2014 \`isDropdownOpen\`, hover flags, animation phase, ephemeral toggles. For those, use a plain \`useState\` directly. The runtime ignores undeclared state.
1123
-
1124
- **\`contextSpec\` direction is one-way: client \u2192 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\` \u2014 there is no return path.
1125
-
1126
- **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.
1495
+ ` + [
1496
+ PROTOCOL_NOTES,
1497
+ CONTRACT_SURFACE,
1498
+ DEFENSIVE_CODING,
1499
+ GESTURE_ROUTING,
1500
+ INTERACTIVE_TRAITS,
1501
+ ANTI_PATTERNS,
1502
+ CROSS_REFERENCE_RULES,
1503
+ renderGadgetCatalogSection(gadgetsSection),
1504
+ CONTEXT_SPEC_SECTION
1505
+ ].join("\n\n") + `
1127
1506
 
1128
1507
  ${pitfallsBlock}
1129
1508
 
@@ -1139,7 +1518,7 @@ ${designSystemDocs}
1139
1518
  ${primitivesDoc}
1140
1519
  `;
1141
1520
  }
1142
- var DESIGN_SYSTEM_GUIDANCE = `## Imports & Component Surface
1521
+ var DESIGN_SYSTEM_GUIDANCE_SURFACE_AND_TOKENS = `## Imports & Component Surface
1143
1522
 
1144
1523
  Import ONLY from: \`react\`, \`@ggui-ai/design\`, \`@ggui-ai/wire\`. The ENTIRE design system \u2014 every primitive, component, composition and trait \u2014 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\`, \u2026) \u2014 never import from them. Use the design components \u2014 DO NOT use raw HTML elements (\`<button>\`, \`<input>\`, \`<div>\` for layout) or Tailwind classes; those render unstyled in the iframe runtime.
1145
1524
 
@@ -1174,7 +1553,7 @@ EXACT primitive prop values (other values are silently ignored \u2014 the design
1174
1553
  - \`<Grid columns={N} gap="md">\` \u2014 2-D layout (rows AND columns). Reach for it for card galleries, stat grids and dashboards \u2014 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}>\` \u2014 it fits as many equal columns as the width allows. \`radius\` (Card / Box / Image) takes the scale \`none | sm | md | lg | xl\`.
1175
1554
  - \`<Stat label="\u2026" value="\u2026" delta="+12%" trend="up">\` \u2014 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.
1176
1555
  - \`<Stepper steps={STEPS} current={step} />\` \u2014 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) => \u2026}\` makes steps clickable. Stepper never owns navigation state \u2014 your Next/Back handlers move \`current\`.
1177
- - \`<Badge variant="...">\` \u2014 \`default | primary | secondary | success | warning | error | info\` for colored pills. Great for status/condition labels. There is NO \`neutral\` variant \u2014 use \`default\` (or \`secondary\`) for an un-tinted pill.
1556
+ - \`<Badge variant="...">\` \u2014 \`default | primary | secondary | tertiary | success | warning | error | info\` for colored pills. Great for status/condition labels. There is NO \`neutral\` variant \u2014 use \`default\` (or \`secondary\`) for an un-tinted pill.
1178
1557
 
1179
1558
  **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 \u2014 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 \u2192 Claudic \u2192 Cyberpunk preset has zero effect on a card hardcoded with \`background: '#000'\`).
1180
1559
 
@@ -1207,8 +1586,8 @@ MANDATORY:
1207
1586
 
1208
1587
  Token categories:
1209
1588
  - Brand: \`var(--ggui-color-primary-600)\`, \`var(--ggui-color-primary-50)\`
1210
- - Text: \`var(--ggui-color-onSurface)\`, \`var(--ggui-color-onSurfaceVariant)\`
1211
- - Backgrounds: \`var(--ggui-color-surface)\`, \`var(--ggui-color-surfaceVariant)\`
1589
+ - Text: \`var(--ggui-color-onContainer)\`, \`var(--ggui-color-onSunken)\`
1590
+ - Backgrounds: \`var(--ggui-color-container)\`, \`var(--ggui-color-sunken)\`
1212
1591
  - Borders: \`var(--ggui-color-outline)\`
1213
1592
  - Spacing: \`var(--ggui-spacing-4)\`, \`var(--ggui-spacing-6)\`
1214
1593
  - Typography: \`var(--ggui-font-size-sm)\`, \`var(--ggui-font-weight-semibold)\`
@@ -1229,7 +1608,7 @@ Use the FULL primary palette throughout the component \u2014 NOT only on submit
1229
1608
  | Buttons, CTAs, filled interactive elements | \`primary-600\` / \`primary-700\` | Primary actions |
1230
1609
  | Headings on light primary backgrounds | \`primary-800\` / \`primary-900\` | High-contrast branded text |
1231
1610
 
1232
- Use semantic tokens (\`onSurface\`, \`onSurfaceVariant\`) for body text and secondary info. NEVER use raw \`neutral-*\` or \`gray-*\` for body text \u2014 they break in dark themes.
1611
+ Use the layering roles' inks (\`onContainer\` for body text on a card, \`onSunken\` for secondary text, captions, labels) \u2014 never raw neutrals. NEVER use raw \`neutral-*\` or \`gray-*\` for body text \u2014 they break in dark themes.
1233
1612
 
1234
1613
  ### Theme-Agnostic Design
1235
1614
 
@@ -1238,7 +1617,7 @@ Components MUST be theme-agnostic \u2014 they reference CSS variables but NEVER
1238
1617
  DO:
1239
1618
  - Use \`var(--ggui-color-primary-*)\` for brand elements \u2014 the theme controls what "primary" means
1240
1619
  - Use \`var(--ggui-shape-shadow-*)\` for depth, \`var(--ggui-shape-radius-*)\` for corners
1241
- - Use semantic color roles: primary for brand, surface/onSurface for structure, success/error/warning for state
1620
+ - Use semantic color roles: primary for brand; the layering roles (ground / container / elevated / sunken + their on* inks) for structure; success/error/warning for state
1242
1621
 
1243
1622
  DON'T:
1244
1623
  - Don't assume primary is blue \u2014 could be red, green, purple
@@ -1259,59 +1638,8 @@ Generated components become reusable blueprints \u2014 the same blueprint serves
1259
1638
  2. Relative/fluid units \u2014 prefer \`%\`, \`em\`, \`rem\`, \`min()\`, \`max()\`, \`clamp()\` over fixed \`px\`.
1260
1639
  3. Fluid widths \u2014 \`max-width\` with \`width: 100%\`. Never set a fixed width.
1261
1640
  4. Compact padding \u2014 components are embedded in containers that provide their own chrome.
1262
- 5. No raw \`@media\` queries in component code \u2014 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.
1263
-
1264
- ## Data Parameterization (CRITICAL)
1265
-
1266
- Generated 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:
1267
-
1268
- \`\`\`tsx
1269
- // BAD \u2014 hardcoded, only works for Tokyo
1270
- const city = "Tokyo";
1271
- const temp = 18;
1272
-
1273
- // GOOD \u2014 parameterized via props with defaults from the request
1274
- interface Props {
1275
- city?: string;
1276
- temperature?: number;
1277
- }
1278
- export default function WeatherCard({ city = "Tokyo", temperature = 18 }: Props) {
1279
- // A controller can override for Seoul, Paris, etc.
1280
- }
1281
- \`\`\`
1282
-
1283
- Rules:
1284
- 1. All request-specific data \u2192 props with defaults. City names, tickers, user names, dates, counts.
1285
- 2. Layout and styling are universal. Colors, spacing, structure \u2014 these are the reusable part.
1286
- 3. Default values come from the current request \u2014 so the component renders correctly standalone.
1287
- 4. Props interface must be typed and exported.
1288
-
1289
- ## Component Structure
1290
-
1291
- Keep JSX nesting depth to 3\u20135 levels. When deeper, extract repeated/complex sections into helper components \u2014 named functions defined above the main Component in the same file. Helpers take data + callbacks via props; they don't own state.
1292
-
1293
- \`\`\`tsx
1294
- import { useState } from 'react';
1295
- import { Container, Card, Stack, Text, Button, Input } from '@ggui-ai/design';
1296
-
1297
- interface Props {
1298
- onSubmit?: (data: unknown) => void;
1299
- }
1300
-
1301
- function ItemCard({ item, onEdit }: { item: Item; onEdit: (id: string) => void }) {
1302
- return <Card padding="md">\u2026</Card>;
1303
- }
1304
-
1305
- export default function GeneratedComponent({ onSubmit }: Props) {
1306
- return (
1307
- <Container>
1308
- {items.map((item) => <ItemCard key={item.id} item={item} onEdit={handleEdit} />)}
1309
- </Container>
1310
- );
1311
- }
1312
- \`\`\`
1313
-
1314
- ## Aesthetic Guidance (READ CAREFULLY \u2014 this is what separates "polished" from "ok")
1641
+ 5. No raw \`@media\` queries in component code \u2014 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.`;
1642
+ var DESIGN_SYSTEM_GUIDANCE_AESTHETICS_AND_CHECKLIST = `## Aesthetic Guidance (READ CAREFULLY \u2014 this is what separates "polished" from "ok")
1315
1643
 
1316
1644
  ### Visual hierarchy \u2014 the SCALE GAP rule
1317
1645
 
@@ -1333,11 +1661,11 @@ A polished UI has ONE hero that dominates. Everything else supports it. Bad layo
1333
1661
  ### Color discipline \u2014 the 60/30/10 rule
1334
1662
 
1335
1663
  Don't paint everything in primary. Use:
1336
- - **60% surface** (\`var(--ggui-color-surface)\` / \`onSurface\`) \u2014 body text, default backgrounds, structure
1337
- - **30% surfaceVariant + onSurfaceVariant** \u2014 secondary text, captions, labels, dividers
1664
+ - **60% container** (\`var(--ggui-color-container)\` / \`onContainer\`) \u2014 body text, default backgrounds, structure
1665
+ - **30% sunken + onSunken** \u2014 wells, secondary text, captions, labels, dividers
1338
1666
  - **10% primary** \u2014 hero number, ONE highlight element, CTAs, brand accent
1339
1667
 
1340
- If your component is 100% purple text on purple backgrounds, you've lost the eye. Headings can be \`onSurface\` (dark neutral) \u2014 they'll still feel weighty. Save the primary palette for one or two STAR moments.
1668
+ If your component is 100% purple text on purple backgrounds, you've lost the eye. Headings can be \`onContainer\` (the card's ink) \u2014 they'll still feel weighty. Save the primary palette for one or two STAR moments.
1341
1669
 
1342
1670
  \`\`\`tsx
1343
1671
  // BAD \u2014 everything purple, eye has no anchor
@@ -1346,7 +1674,7 @@ If your component is 100% purple text on purple backgrounds, you've lost the eye
1346
1674
  <Text tone="emphasized">all body text</Text>
1347
1675
 
1348
1676
  // GOOD \u2014 hero pops, body is neutral, primary is reserved
1349
- <Heading>Title</Heading> {/* defaults to onSurface */}
1677
+ <Heading>Title</Heading> {/* defaults to onContainer */}
1350
1678
  <Text size="4xl" weight="bold" tone="emphasized">42</Text>
1351
1679
  <Text tone="muted">all body text</Text>
1352
1680
  \`\`\`
@@ -1404,6 +1732,12 @@ Hero sections should feel airy. Use \`padding="xl"\` (32px) on the main card, no
1404
1732
  - [ ] Live/streaming regions wrapped in \`aria-live="polite"\`
1405
1733
  - [ ] Headings nest \u2014 one \`level={1}\`, then \`level={2}\`/\`{3}\` \u2014 never skipped or inverted
1406
1734
  - [ ] Wire hooks (\`useAction\`, \`useStream\`) imported from \`@ggui-ai/wire\` and consumed`;
1735
+ var DESIGN_SYSTEM_GUIDANCE = [
1736
+ DESIGN_SYSTEM_GUIDANCE_SURFACE_AND_TOKENS,
1737
+ DATA_PARAMETERIZATION,
1738
+ COMPONENT_STRUCTURE,
1739
+ DESIGN_SYSTEM_GUIDANCE_AESTHETICS_AND_CHECKLIST
1740
+ ].join("\n\n");
1407
1741
 
1408
1742
  export { buildSystemPrompt, generateBoilerplate, jsonSchemaTypeToTs };
1409
1743
  //# sourceMappingURL=boilerplate.js.map