@ggui-ai/ui-gen 0.14.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 (102) hide show
  1. package/dist/adapters/generation-dispatch.d.ts +21 -4
  2. package/dist/adapters/generation-dispatch.js +915 -351
  3. package/dist/adapters/generation-dispatch.js.map +1 -1
  4. package/dist/adapters/index.js +28 -23
  5. package/dist/adapters/index.js.map +1 -1
  6. package/dist/advanced/index.d.ts +17 -12
  7. package/dist/advanced/index.js +968 -375
  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 +34 -26
  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 +975 -373
  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/check/type-checker.ts +12 -2
  75. package/src/coding-agent/tools.ts +8 -2
  76. package/src/contract-context.ts +28 -0
  77. package/src/create-harness.ts +11 -0
  78. package/src/create-ui-generator.ts +71 -25
  79. package/src/design-mode.ts +182 -0
  80. package/src/design-system-docs.ts +17 -13
  81. package/src/evaluation/axis-checks/dispatch.ts +4 -0
  82. package/src/evaluation/axis-checks/extras.ts +5 -0
  83. package/src/evaluation/cost-tracker.ts +2 -3
  84. package/src/evaluation/index.ts +46 -2
  85. package/src/evaluation/llm-evaluator.ts +77 -21
  86. package/src/evaluation/types-public.ts +103 -8
  87. package/src/evaluation/visual-evaluator.ts +301 -29
  88. package/src/harness/coding/dupe-break.ts +0 -0
  89. package/src/harness/coding/init-session.ts +1 -0
  90. package/src/harness/coding/run-coding-turn.ts +3 -0
  91. package/src/harness/coding/run-eval-round.ts +15 -2
  92. package/src/harness/llm-trace-sink.ts +3 -3
  93. package/src/harness/result-types.ts +15 -3
  94. package/src/harness/runtime.ts +18 -0
  95. package/src/harness/types-public.ts +27 -0
  96. package/src/index.ts +26 -0
  97. package/src/internal/extract-call-signatures.ts +2 -2
  98. package/src/providers/bedrock.ts +4 -4
  99. package/src/run-check.ts +1 -0
  100. package/src/tools/get-primitives-ts.ts +1 -1
  101. package/src/validation/allowed-imports.ts +8 -2
  102. package/src/validation/primitives.ts +1 -1
@@ -2,6 +2,7 @@ import { resolveAppGadgets, listContractGadgets, HOOK_NAME_RE } 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
  import { createHash } from 'crypto';
7
8
 
@@ -93,7 +94,8 @@ async function runCheck(input) {
93
94
  compiledCode,
94
95
  contract,
95
96
  originalPrompt: prompt,
96
- classification: harness.classification
97
+ classification: harness.classification,
98
+ designMode: harness.designMode
97
99
  };
98
100
  let axisIssueCount = 0;
99
101
  const seenAxisIds = /* @__PURE__ */ new Set();
@@ -644,6 +646,63 @@ function compose(classification) {
644
646
  fragments: matched
645
647
  };
646
648
  }
649
+
650
+ // src/design-mode.ts
651
+ var DEFAULT_DESIGN_MODE = "constrained";
652
+ function canvasDisplayModeForShell(shell) {
653
+ return shell === "chat" || shell === "inline" ? "inline" : "fullscreen";
654
+ }
655
+ function canvasForRendering(shellType, screen) {
656
+ const shell = shellType ?? "fullscreen";
657
+ if (canvasDisplayModeForShell(shell) === "inline") return "xs-chat-card";
658
+ if (shell === "spatial") return "md";
659
+ switch (screen ?? "universal") {
660
+ case "mobile":
661
+ return "mobile-fullscreen-small";
662
+ case "tablet":
663
+ return "md";
664
+ default:
665
+ return "lg";
666
+ }
667
+ }
668
+ var CANVAS_DESCRIPTORS = {
669
+ "xs-chat-card": {
670
+ label: "extra-small chat card",
671
+ minWidthPx: 320,
672
+ maxWidthPx: 480,
673
+ 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"
674
+ },
675
+ "mobile-fullscreen-small": {
676
+ label: "small mobile fullscreen",
677
+ minWidthPx: 320,
678
+ maxWidthPx: 599,
679
+ 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"
680
+ },
681
+ md: {
682
+ label: "medium panel",
683
+ minWidthPx: 600,
684
+ maxWidthPx: 1023,
685
+ host: "a tablet viewport or a floating panel (spatial / picture-in-picture) \u2014 one or two columns, medium density"
686
+ },
687
+ lg: {
688
+ label: "large fullscreen",
689
+ minWidthPx: 1024,
690
+ maxWidthPx: 1439,
691
+ host: "a desktop viewport the component owns edge to edge \u2014 multi-column layouts, hover states and pointer interactions are available"
692
+ },
693
+ xl: {
694
+ label: "extra-large fullscreen",
695
+ minWidthPx: 1440,
696
+ maxWidthPx: 1920,
697
+ 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"
698
+ }
699
+ };
700
+ function describeCanvas(canvas) {
701
+ const d = CANVAS_DESCRIPTORS[canvas];
702
+ 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.`;
703
+ }
704
+
705
+ // src/boilerplate/render.ts
647
706
  var __dirname$1 = dirname(fileURLToPath(import.meta.url));
648
707
  var TEMPLATE_DIRS = [
649
708
  resolve(__dirname$1, "templates"),
@@ -652,19 +711,31 @@ var TEMPLATE_DIRS = [
652
711
  resolve(__dirname$1, "..", "..", "..", "src", "boilerplate", "templates"),
653
712
  resolve(__dirname$1, "..", "..", "..", "..", "src", "boilerplate", "templates")
654
713
  ];
655
- var baseCache = null;
714
+ var BASE_TEMPLATE_FILE = {
715
+ constrained: "base.tsx.tmpl",
716
+ free: "base-free.tsx.tmpl"
717
+ };
718
+ var FREE_LAYOUT = [
719
+ " <div style={{ width: '100%' }}>",
720
+ " {/* implement your UI here */}",
721
+ " </div>"
722
+ ].join("\n");
723
+ var baseCache = /* @__PURE__ */ new Map();
656
724
  var layoutCache = /* @__PURE__ */ new Map();
657
- function loadBase() {
658
- if (baseCache) return baseCache;
725
+ function loadBase(designMode) {
726
+ const cached = baseCache.get(designMode);
727
+ if (cached !== void 0) return cached;
728
+ const file = BASE_TEMPLATE_FILE[designMode];
659
729
  for (const dir of TEMPLATE_DIRS) {
660
730
  try {
661
- baseCache = readFileSync(resolve(dir, "base.tsx.tmpl"), "utf-8");
662
- return baseCache;
731
+ const content = readFileSync(resolve(dir, file), "utf-8");
732
+ baseCache.set(designMode, content);
733
+ return content;
663
734
  } catch {
664
735
  continue;
665
736
  }
666
737
  }
667
- throw new Error("No base.tsx.tmpl found");
738
+ throw new Error(`No ${file} found`);
668
739
  }
669
740
  function loadLayout(shellType, screen) {
670
741
  const key = `${shellType}-${screen}`;
@@ -688,9 +759,9 @@ function loadLayout(shellType, screen) {
688
759
  }
689
760
  throw new Error(`No layout found for ${key}`);
690
761
  }
691
- function renderBoilerplate(shellType, screen, markers) {
692
- let template = loadBase();
693
- const layout = loadLayout(shellType, screen);
762
+ function renderBoilerplate(shellType, screen, markers, designMode = DEFAULT_DESIGN_MODE) {
763
+ let template = loadBase(designMode);
764
+ const layout = designMode === "free" ? FREE_LAYOUT : loadLayout(shellType, screen);
694
765
  template = template.replace("{{LAYOUT}}", layout);
695
766
  for (const [key, value] of Object.entries(markers)) {
696
767
  template = template.replaceAll(`{{${key}}}`, value);
@@ -867,7 +938,7 @@ function inferTypeFromExample(example) {
867
938
  }
868
939
  return `{ ${fields.join("; ")} }`;
869
940
  }
870
- function generateBoilerplate(_userPrompt, contract, shellType, screen, composedSections, appGadgets) {
941
+ function generateBoilerplate(_userPrompt, contract, shellType, screen, composedSections, appGadgets, designMode = DEFAULT_DESIGN_MODE) {
871
942
  const propsFields = [];
872
943
  const propsProperties = contract?.propsSpec?.properties ?? {};
873
944
  for (const [key, entry] of Object.entries(propsProperties)) {
@@ -1049,7 +1120,7 @@ ${body}
1049
1120
  CONTEXT_HOOKS: contextHooks,
1050
1121
  WIRE_HOOKS: hookBody,
1051
1122
  AXIS_SECTIONS: composedSections ?? ""
1052
- });
1123
+ }, designMode);
1053
1124
  }
1054
1125
 
1055
1126
  // src/evaluation/types-public.ts
@@ -1230,14 +1301,45 @@ Intentional custom colors (status indicators) are acceptable when no semantic to
1230
1301
  Only list ACTUAL violations. Use 'fail' only for pervasive violations.`
1231
1302
  }
1232
1303
  ];
1233
- function getCriteriaByPriority(priority) {
1234
- return CRITERIA.filter((c) => c.priority === priority);
1304
+ var FREE_DESIGN_CRITERIA_OVERRIDES = [
1305
+ {
1306
+ id: "tokens",
1307
+ name: "Color tokens",
1308
+ priority: "P1",
1309
+ tier: 0,
1310
+ failOutcome: "warn",
1311
+ 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.",
1312
+ 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."
1313
+ },
1314
+ {
1315
+ id: "visual",
1316
+ name: "Visual composition",
1317
+ priority: "P2",
1318
+ tier: 2,
1319
+ failOutcome: "warn",
1320
+ codingGuidance: "Compose deliberately: one clear focal point, consistent spacing rhythm, a coherent theme-token palette, a fit to the rendering canvas.",
1321
+ evalInstruction: `Evaluate VISUAL COMPOSITION: Is the component composed deliberately for its canvas?
1322
+
1323
+ 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).
1324
+ 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.
1325
+
1326
+ Only list ACTUAL composition problems. Use 'fail' only for a fundamentally incoherent composition.`
1327
+ }
1328
+ ];
1329
+ function criteriaFor(designMode = "constrained") {
1330
+ if (designMode === "constrained") return CRITERIA;
1331
+ return CRITERIA.map(
1332
+ (c) => FREE_DESIGN_CRITERIA_OVERRIDES.find((o) => o.id === c.id) ?? c
1333
+ );
1235
1334
  }
1236
- function buildCodingCriteriaSummary() {
1335
+ function getCriteriaByPriority(priority, designMode = "constrained") {
1336
+ return criteriaFor(designMode).filter((c) => c.priority === priority);
1337
+ }
1338
+ function buildCodingCriteriaSummary(designMode = "constrained") {
1237
1339
  const lines = ["## Priority (P0 first, then P1, then P2)", ""];
1238
1340
  for (const priority of ["P0", "P1", "P2"]) {
1239
1341
  const label = priority === "P0" ? "Must (compile + complete)" : priority === "P1" ? "Should (safety)" : "Nice (quality)";
1240
- const criteria = getCriteriaByPriority(priority);
1342
+ const criteria = getCriteriaByPriority(priority, designMode);
1241
1343
  lines.push(`**${priority} \u2014 ${label}:**`);
1242
1344
  for (const c of criteria) {
1243
1345
  lines.push(`- ${c.codingGuidance}`);
@@ -1246,6 +1348,427 @@ function buildCodingCriteriaSummary() {
1246
1348
  }
1247
1349
  return lines.join("\n");
1248
1350
  }
1351
+
1352
+ // src/boilerplate/hard-sections.ts
1353
+ var PROTOCOL_NOTES = `## Protocol Notes
1354
+ 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:
1355
+ 1. **Do NOT delete any pre-declared hook.** \`self_check\` fails with \`wire_preservation:<kind>:<name>\` if you remove one.
1356
+ 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\`.
1357
+ 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.
1358
+
1359
+ Renaming a binding is fine \u2014 the wiring is the string-literal argument, not the identifier.`;
1360
+ var CONTRACT_SURFACE = `## Contract surface \u2014 four specs + two catalogs
1361
+
1362
+ 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:
1363
+
1364
+ | Surface | Direction | Role |
1365
+ | -------------------- | -------------------------- | -------------------------------------------------------------------- |
1366
+ | \`propsSpec\` | server \u2192 UI (one-shot) | Initial render values delivered once at \`ggui_render\` |
1367
+ | \`streamSpec\` | agent \u2192 UI (many) | Typed channels for live updates via \`ggui_emit\` |
1368
+ | \`actionSpec\` | UI \u2192 agent (events) | Discrete events driving the agent's next turn (consumed via \`ggui_consume\`) |
1369
+ | \`contextSpec\` | UI \u2192 server (state mirror) | UI state the agent observes between turns |
1370
+ | \`agentCapabilities.tools\` | catalog | Tools the contract references via \`actionSpec[*].nextStep\` and \`streamSpec[*].source.tool\` |
1371
+ | \`clientCapabilities.gadgets\` | catalog | Browser-capability gadget hooks the component code mounts (e.g., \`useGeolocation\`) |
1372
+
1373
+ **Placement rule for inbound specs**: actions drive turns; context observes state. There is no third category.
1374
+
1375
+ **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.`;
1376
+ var DEFENSIVE_CODING = `## Defensive coding for absent / late-arriving data
1377
+
1378
+ 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.**
1379
+
1380
+ - **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.
1381
+ - **Array iteration**: always default to \`[]\` before \`.map\`/\`.filter\`/\`.length\`. Use \`(props.items ?? []).map(...)\` not \`props.items.map(...)\`. Same for stream.all, stream.latest, etc.
1382
+ - **Object access**: optional-chain through nested fields. \`props.user?.name ?? 'Anonymous'\` not \`props.user.name\`.
1383
+ - **Number ops**: default before arithmetic. \`(props.count ?? 0) + 1\` not \`props.count + 1\`.
1384
+ - **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\`.
1385
+ - **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.
1386
+ - **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.
1387
+ - **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.
1388
+ - **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.
1389
+
1390
+ 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.`;
1391
+ var GESTURE_ROUTING = `## Picking the right primitive for user gestures
1392
+
1393
+ Choose by what the user is DOING, not where the result goes \u2014 the runtime handles the routing.
1394
+
1395
+ | Gesture intent | LLM writes | Notes |
1396
+ | -------------- | ---------- | ----- |
1397
+ | 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. |
1398
+ | 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. |
1399
+ | 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. |
1400
+ | 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. |
1401
+ | 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. |
1402
+
1403
+ 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.
1404
+
1405
+ **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.
1406
+
1407
+ **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.`;
1408
+ var INTERACTIVE_TRAITS = `## Making a primitive interactive \u2014 \`as={Trait}\`
1409
+
1410
+ Structural primitives (\`Box\`, \`Stack\`, \`Row\`, \`Card\`) have NO \`onClick\` by default. Add interactivity with the \`as\` prop \u2014 a trait, not a wrapper:
1411
+
1412
+ \`\`\`tsx
1413
+ <Card as={Clickable} onClick={() => dispatch('select', { id })}
1414
+ hoverStyle={{ boxShadow: 'var(--ggui-shape-shadow-lg)' }}>\u2026</Card>
1415
+ \`\`\`
1416
+
1417
+ - \`as={Clickable}\` \u2192 \`onClick\` + keyboard activation (Enter/Space) + \`role="button"\` + \`hoverStyle\`/\`activeStyle\`/\`cursor\`.
1418
+ - \`as={Hoverable}\` \u2192 \`hoverStyle\` only (no click). \`as={Pressable}\` \u2192 \`onPress\` + \`pressStyle\`.
1419
+
1420
+ \`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.
1421
+
1422
+ **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\`.
1423
+
1424
+ **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.
1425
+
1426
+ **\`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\`:
1427
+
1428
+ \`\`\`tsx
1429
+ // Click-to-edit a label: wrap the Text in a Clickable structural primitive.
1430
+ <Box as={Clickable} onClick={() => setEditingId(task.id)}
1431
+ style={{ cursor: 'pointer' }}>
1432
+ <Text weight="semibold">{task.title}</Text>
1433
+ </Box>
1434
+
1435
+ // Or pair the label with an explicit edit Button (clearer affordance).
1436
+ <Row gap="xs" align="center">
1437
+ <Text weight="semibold">{task.title}</Text>
1438
+ <Button variant="ghost" size="xs" aria-label="Edit title"
1439
+ onClick={() => setEditingId(task.id)}>Edit</Button>
1440
+ </Row>
1441
+
1442
+ // In edit mode, swap the Text for an Input.
1443
+ {editingId === task.id
1444
+ ? <Input value={draftTitle} onChange={setDraftTitle} label="Task title" />
1445
+ : <Text weight="semibold">{task.title}</Text>}
1446
+ \`\`\``;
1447
+ var ANTI_PATTERNS = `## Anti-patterns \u2014 DO NOT WRITE
1448
+
1449
+ 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:
1450
+
1451
+ - \`useWiredTool\`, \`useClientTool\` \u2014 retired hooks. Replace with \`useAction\` (events) and the named hook from \`@ggui-ai/gadgets\` (browser capabilities).
1452
+ - \`dispatch: { kind: 'tool', tool: '...' }\` / \`dispatch: { kind: 'agent', intendedTool: '...' }\` \u2014 retired discriminated-union. Use the flat optional \`nextStep?: '<tool>'\` instead.
1453
+ - \`mode: 'host-routed'\` / \`mode: 'tool'\` \u2014 retired \`mode\` field. Same fix: flat \`nextStep?\`.
1454
+ - \`broadcast: {...}\` on the contract \u2014 retired top-level field. Use \`streamSpec[channel].source: {tool, args?}\` to declare a tool-fed channel.
1455
+ - \`wiredTools\` / \`agentTools\` (top-level) \u2014 retired catalog names. Use \`agentCapabilities.tools\`.
1456
+ - \`clientTools\` / \`clientCapabilities.capabilities\` \u2014 retired catalog shapes. Use \`clientCapabilities.gadgets\` (entries declare hooks, not RPC).
1457
+ - \`@ggui-ai/client-tools\` \u2014 retired package name. Import gadget hooks from \`@ggui-ai/gadgets\`.
1458
+ - \`intendedTool\` \u2014 retired. Use \`nextStep\` (flat).
1459
+ - \`props: { properties: {...} }\` as a CONTRACT field \u2014 retired. The contract field is \`propsSpec\` (the wire \`props\` field on render / update still carries VALUES).`;
1460
+ var CROSS_REFERENCE_RULES = `## Cross-reference rules
1461
+
1462
+ When you declare a reference, also declare the catalog entry it points at:
1463
+
1464
+ - \`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\`.
1465
+ - \`streamSpec[X].source.tool = 'list_messages'\` \u2192 \`agentCapabilities.tools.list_messages\` MUST exist. Cross-ref code: \`CTR_REF_STREAM_SOURCE\`.
1466
+ - The catalog entry's schemas MUST be a superset of the referencing spec's schema. Cross-ref code: \`CTR_SCHEMA_INCOMPAT\`.`;
1467
+ function renderGadgetCatalogSection(gadgetsSection) {
1468
+ return `## clientCapabilities \u2014 registered catalog
1469
+
1470
+ ${gadgetsSection}
1471
+
1472
+ 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.
1473
+
1474
+ 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\`.`;
1475
+ }
1476
+ var CONTEXT_SPEC_SECTION = `## Observable state via \`contextSpec\`
1477
+
1478
+ 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**:
1479
+
1480
+ \`\`\`tsx
1481
+ import { useGguiContext } from '@ggui-ai/wire';
1482
+
1483
+ export default function Component(props: Props) {
1484
+ // AUTO-GENERATED \u2014 do not remove or rename:
1485
+ const [currentStep, setCurrentStep] = useGguiContext<number>('currentStep');
1486
+ const [draftText, setDraftText] = useGguiContext<string>('draftText');
1487
+
1488
+ // Plain JSX. No Provider wrap. The runtime already wrapped your
1489
+ // component in nested SingleSlotProviders before this code ran.
1490
+ return (
1491
+ <Container>
1492
+ <Text>Step {currentStep}</Text>
1493
+ <Input value={draftText} onChange={(e) => setDraftText(e.target.value)} />
1494
+ <Button onClick={() => setCurrentStep((s) => s + 1)}>Next</Button>
1495
+ </Container>
1496
+ );
1497
+ }
1498
+ \`\`\`
1499
+
1500
+ For every declared slot you have **\`slotName\` + \`setSlotName\`** in scope:
1501
+ - **Read** the value to render: \`<Text>Step {currentStep}</Text>\`
1502
+ - **Write** via the setter: \`setCurrentStep(s => s + 1)\` (in callbacks, effects, anywhere)
1503
+
1504
+ 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.
1505
+
1506
+ **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.
1507
+
1508
+ **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.
1509
+
1510
+ **\`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.
1511
+
1512
+ **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.`;
1513
+ var DATA_PARAMETERIZATION = `## Data Parameterization (CRITICAL)
1514
+
1515
+ 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:
1516
+
1517
+ \`\`\`tsx
1518
+ // BAD \u2014 hardcoded, only works for Tokyo
1519
+ const city = "Tokyo";
1520
+ const temp = 18;
1521
+
1522
+ // GOOD \u2014 parameterized via props with defaults from the request
1523
+ interface Props {
1524
+ city?: string;
1525
+ temperature?: number;
1526
+ }
1527
+ export default function WeatherCard({ city = "Tokyo", temperature = 18 }: Props) {
1528
+ // A controller can override for Seoul, Paris, etc.
1529
+ }
1530
+ \`\`\`
1531
+
1532
+ Rules:
1533
+ 1. All request-specific data \u2192 props with defaults. City names, tickers, user names, dates, counts.
1534
+ 2. Layout and styling are universal. Colors, spacing, structure \u2014 these are the reusable part.
1535
+ 3. Default values come from the current request \u2014 so the component renders correctly standalone.
1536
+ 4. Props interface must be typed and exported.`;
1537
+ var COMPONENT_STRUCTURE = `## Component Structure
1538
+
1539
+ 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.
1540
+
1541
+ \`\`\`tsx
1542
+ import { useState } from 'react';
1543
+ import { Container, Card, Stack, Text, Button, Input } from '@ggui-ai/design';
1544
+
1545
+ interface Props {
1546
+ onSubmit?: (data: unknown) => void;
1547
+ }
1548
+
1549
+ function ItemCard({ item, onEdit }: { item: Item; onEdit: (id: string) => void }) {
1550
+ return <Card padding="md">\u2026</Card>;
1551
+ }
1552
+
1553
+ export default function GeneratedComponent({ onSubmit }: Props) {
1554
+ return (
1555
+ <Container>
1556
+ {items.map((item) => <ItemCard key={item.id} item={item} onEdit={handleEdit} />)}
1557
+ </Container>
1558
+ );
1559
+ }
1560
+ \`\`\``;
1561
+
1562
+ // src/boilerplate/free-design-prompt.ts
1563
+ var FREE_GESTURE_SURFACE = `## One gesture surface per action binding
1564
+
1565
+ 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.`;
1566
+ var FREE_DESIGN_FREEDOM = `## Design freedom
1567
+
1568
+ 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).
1569
+
1570
+ \`@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.
1571
+
1572
+ 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.`;
1573
+ var COLOR_PREFIX = "--ggui-color-";
1574
+ var RAMP_FAMILIES = ["primary", "neutral", "success", "warning", "error", "info"];
1575
+ var SEMANTIC_ROLES = [
1576
+ { names: ["ground", "onGround"], role: "the page / chat canvas behind everything + its text" },
1577
+ { names: ["container", "onContainer"], role: "a card, a bubble, a panel + body text on it" },
1578
+ { names: ["elevated", "onElevated"], role: "popover, menu, modal, toast \u2014 floats above a container" },
1579
+ { names: ["sunken", "onSunken"], role: "wells, inputs at rest, code blocks + secondary text" },
1580
+ { names: ["ground-subtle", "ground-gradient"], role: "quiet canvas fills" },
1581
+ { names: ["onPrimary"], role: "text on the brand color" },
1582
+ { names: ["outline", "outlineVariant"], role: "borders + dividers" },
1583
+ { names: ["onError"], role: "text on an error fill" }
1584
+ ];
1585
+ function colorVocabularyFromManifest(manifest) {
1586
+ const colors = manifest.filter((t) => t.startsWith(COLOR_PREFIX)).map((t) => t.slice(COLOR_PREFIX.length));
1587
+ const ramps = [];
1588
+ const claimed = /* @__PURE__ */ new Set();
1589
+ for (const family of RAMP_FAMILIES) {
1590
+ const steps = [];
1591
+ for (const name of colors) {
1592
+ const m = new RegExp(`^${family}-(\\d+)$`).exec(name);
1593
+ if (m) {
1594
+ steps.push(Number(m[1]));
1595
+ claimed.add(name);
1596
+ }
1597
+ }
1598
+ if (steps.length === 0) continue;
1599
+ steps.sort((a, b) => a - b);
1600
+ const bare = colors.includes(family);
1601
+ if (bare) claimed.add(family);
1602
+ ramps.push({ family, steps, bare });
1603
+ }
1604
+ const roles = colors.filter((n) => !claimed.has(n)).sort();
1605
+ return { ramps, roles };
1606
+ }
1607
+ function renderRamp(r) {
1608
+ return `\`${r.family}-${r.steps.join("/")}\`${r.bare ? ` (plus bare \`${r.family}\`)` : ""}`;
1609
+ }
1610
+ function renderFreeColorRule(manifest = consumedTokenManifest) {
1611
+ const { ramps, roles } = colorVocabularyFromManifest(manifest);
1612
+ const brand = ramps.filter((r) => r.family === "primary" || r.family === "neutral");
1613
+ const state = ramps.filter((r) => r.family !== "primary" && r.family !== "neutral");
1614
+ const roleLines = [];
1615
+ const named = /* @__PURE__ */ new Set();
1616
+ for (const g of SEMANTIC_ROLES) {
1617
+ const present = g.names.filter((n) => roles.includes(n));
1618
+ if (present.length === 0) continue;
1619
+ for (const n of present) named.add(n);
1620
+ roleLines.push(`${present.map((n) => `\`${n}\``).join(" / ")} (${g.role})`);
1621
+ }
1622
+ const other = roles.filter((n) => !named.has(n));
1623
+ if (other.length > 0) roleLines.push(`other roles: ${other.map((n) => `\`${n}\``).join(", ")}`);
1624
+ const vocabulary = [
1625
+ roleLines.length > 0 ? `- Semantic roles cover most needs: ${roleLines.join("; ")}.` : "",
1626
+ brand.length > 0 ? `- Brand + neutral ramps (every step that exists, nothing else): ${brand.map(renderRamp).join(", ")}.` : "",
1627
+ state.length > 0 ? `- State ramps (every step that exists, nothing else): ${state.map(renderRamp).join(", ")}.` : "",
1628
+ "- A step not listed does not exist and renders unset; pick the nearest listed step."
1629
+ ].filter((l) => l.length > 0).join("\n");
1630
+ return `## Color stays tokenized (the one hard styling rule)
1631
+
1632
+ 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))\`.
1633
+
1634
+ - 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.
1635
+ - 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.
1636
+ - 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\`).
1637
+ - Shadows: \`var(--ggui-shape-shadow-sm|md|lg|xl)\`, or a literal offset/blur whose color is a token \u2014 never an \`rgba()\` tint.
1638
+ - 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.
1639
+
1640
+ The color vocabulary (rendered from the manifest \u2014 these names and steps, exactly):
1641
+ ${vocabulary}`;
1642
+ }
1643
+ var FREE_COLOR_RULE = renderFreeColorRule();
1644
+ var FREE_HOST_ENVELOPE = `## Where this renders
1645
+
1646
+ The compiled component is loaded into a sandboxed iframe by an MCP Apps host (chat clients, the ggui console, embedded panels):
1647
+
1648
+ - **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.
1649
+ - **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.
1650
+ - **No host document access**: \`window.*\`, \`document.*\` (other than the intercepted \`requestFullscreen\` / \`exitFullscreen\`), \`localStorage\`, \`sessionStorage\`, \`navigator\`, \`location\`, \`history\`, \`innerHTML\` / \`dangerouslySetInnerHTML\`, \`<script>\` \u2014 all rejected.
1651
+ - **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".
1652
+ - **Display modes**: the host advertises \`availableDisplayModes\` (\`inline\` | \`fullscreen\` | \`pip\`); \`el.requestFullscreen()\` asks the host to switch \u2014 never assume it will.
1653
+ - **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.`;
1654
+ var FREE_BUDGETS = `## Budgets (deterministic caps)
1655
+
1656
+ - Source \u2264 50 KB and \u2264 500 lines.
1657
+ - Compiled bundle \u2264 2 MB.
1658
+ - One file, one \`export default function Component(props: Props)\`.`;
1659
+ var FREE_IMPORTS_AND_SECURITY = `## Imports & security (what you may import, what you may not call)
1660
+
1661
+ 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()\`.
1662
+
1663
+ 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.`;
1664
+ var FREE_RESPONSIVE_INVARIANT = `## Responsive invariant
1665
+
1666
+ 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\`).`;
1667
+ var FREE_ACCESSIBILITY = `## Accessibility (REQUIRED)
1668
+
1669
+ 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).
1670
+
1671
+ 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.
1672
+ 2. **Form inputs have labels.** \`<label htmlFor={id}>\` paired with the input's \`id\`, or \`aria-label\`; errors via \`aria-invalid\` + \`aria-describedby\`.
1673
+ 3. **Images have \`alt\`** (\`alt=""\` for decorative). Icon-only buttons need \`aria-label\`; decorative icons and emoji are \`aria-hidden="true"\`.
1674
+ 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.
1675
+ 5. **Headings nest**: one \`<h1>\` per screen, \`<h2>\` for sections, \`<h3>\` below \u2014 never skipped or inverted.
1676
+ 6. **Busy state is announced**: \`<button disabled={isLoading} aria-busy={isLoading}>{isLoading ? 'Submitting\u2026' : 'Submit'}</button>\`.
1677
+ 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.
1678
+ 8. **Focus is visible** \u2014 style \`:focus-visible\` with a token color; never \`outline: none\` without a replacement.`;
1679
+ var FREE_QUALITY_CHECKLIST = `## Quality Checklist (verify before returning)
1680
+
1681
+ - [ ] Imports ONLY from: react, react-dom, @ggui-ai/design, @ggui-ai/wire, @ggui-ai/gadgets (+ contract gadget packages)
1682
+ - [ ] 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
1683
+ - [ ] Fluid width (\`width: 100%\`, \`max-width\`), holds across the whole canvas range, no horizontal scroll
1684
+ - [ ] Typed Props interface exported; request-specific data is a prop with default
1685
+ - [ ] Every \`useAction\` binding is wired to exactly ONE gesture surface \u2014 no handler on both a parent and a child
1686
+ - [ ] Real controls (\`<button>\`, \`<a>\`, \`<input>\` + \`<label>\`), \`alt\` on images, \`aria-label\` on icon-only buttons
1687
+ - [ ] State is ARIA-expressed (\`aria-checked\` / \`aria-pressed\` / \`aria-selected\` / \`aria-expanded\`) \u2014 never style-only
1688
+ - [ ] Live/streaming regions wrapped in \`aria-live="polite"\`
1689
+ - [ ] Headings nest \u2014 one \`<h1>\`, then \`<h2>\` / \`<h3>\` \u2014 never skipped or inverted
1690
+ - [ ] No \`fetch\` / \`eval\` / \`window\` / \`document\` / \`localStorage\` / external stylesheets or fonts
1691
+ - [ ] Source \u2264 50 KB / \u2264 500 lines; wire hooks (\`useAction\`, \`useStream\`, \`useGguiContext\`) kept and consumed`;
1692
+ 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.";
1693
+ var TOKEN_GROUPS = [
1694
+ { label: "Color (mandatory for every color)", prefixes: ["--ggui-color-"], note: "" },
1695
+ { label: "Spacing (optional \u2014 literals are fine)", prefixes: ["--ggui-spacing-"], note: "" },
1696
+ { label: "Typography (optional)", prefixes: ["--ggui-font-"], note: "" },
1697
+ { label: "Radius (optional)", prefixes: ["--ggui-shape-radius-"], note: "" },
1698
+ { label: "Shadow (optional)", prefixes: ["--ggui-shape-shadow-"], note: "" }
1699
+ ];
1700
+ function renderTokenVocabulary(manifest = consumedTokenManifest) {
1701
+ const sorted = [...manifest].sort();
1702
+ const claimed = /* @__PURE__ */ new Set();
1703
+ const lines = [
1704
+ "### Reference (optional): theme token vocabulary",
1705
+ "",
1706
+ "The closed manifest \u2014 the ONLY `--ggui-*` names the runtime defines on `:root`. Color names are mandatory for color; the rest are optional conveniences.",
1707
+ ""
1708
+ ];
1709
+ for (const group of TOKEN_GROUPS) {
1710
+ const names = sorted.filter((t) => group.prefixes.some((p) => t.startsWith(p)));
1711
+ if (names.length === 0) continue;
1712
+ for (const n of names) claimed.add(n);
1713
+ lines.push(`- **${group.label}**: ${names.map((n) => `\`${n}\``).join(", ")}`);
1714
+ }
1715
+ const other = sorted.filter((t) => !claimed.has(t));
1716
+ if (other.length > 0) {
1717
+ lines.push(`- **Other**: ${other.map((n) => `\`${n}\``).join(", ")}`);
1718
+ }
1719
+ return lines.join("\n");
1720
+ }
1721
+ function buildFreeDesignPrompt(inputs) {
1722
+ const axisSection = inputs.axisSection.length > 0 ? `${inputs.axisSection}
1723
+ ${FREE_SHAPE_GUIDANCE_NOTE}
1724
+ ` : "";
1725
+ const head = `You are ggui's UI builder. You receive a typed boilerplate and fill it in using apply_changes.
1726
+
1727
+ ## Your Task
1728
+ ${inputs.userRequest}
1729
+
1730
+ ## Rendering canvas
1731
+ ${describeCanvas(inputs.canvas)}
1732
+
1733
+ ## How It Works
1734
+ 1. Read the boilerplate \u2014 typed Props and wire hooks are pre-configured; the JSX body and its styling are yours to compose
1735
+ 2. Respond with one apply_changes call \u2014 add state, helpers, styles and JSX
1736
+ 3. If compilation or evaluation fails, you'll get errors to fix in the next turn
1737
+
1738
+ ${inputs.criteriaBlock}
1739
+ ${axisSection}
1740
+ `;
1741
+ const sections = [
1742
+ PROTOCOL_NOTES,
1743
+ CONTRACT_SURFACE,
1744
+ DEFENSIVE_CODING,
1745
+ GESTURE_ROUTING,
1746
+ FREE_GESTURE_SURFACE,
1747
+ ANTI_PATTERNS,
1748
+ CROSS_REFERENCE_RULES,
1749
+ renderGadgetCatalogSection(inputs.gadgetsSection),
1750
+ CONTEXT_SPEC_SECTION,
1751
+ `## Reference: Wire Hooks
1752
+ ${inputs.wireDoc}`,
1753
+ FREE_DESIGN_FREEDOM,
1754
+ FREE_COLOR_RULE,
1755
+ FREE_HOST_ENVELOPE,
1756
+ FREE_BUDGETS,
1757
+ FREE_IMPORTS_AND_SECURITY,
1758
+ DATA_PARAMETERIZATION,
1759
+ COMPONENT_STRUCTURE,
1760
+ FREE_RESPONSIVE_INVARIANT,
1761
+ FREE_ACCESSIBILITY,
1762
+ FREE_QUALITY_CHECKLIST,
1763
+ renderTokenVocabulary(),
1764
+ `### Reference (optional): \`@ggui-ai/design\` component catalog
1765
+
1766
+ Optional \u2014 import a primitive only when it helps. Raw HTML + your own CSS is a first-class choice.
1767
+
1768
+ ${inputs.primitivesDoc}`
1769
+ ];
1770
+ return head + sections.join("\n\n") + "\n";
1771
+ }
1249
1772
  var VIRTUAL_DTS_PATH = "/__gadget__.d.ts";
1250
1773
  var EXTRACTOR_COMPILER_OPTIONS = {
1251
1774
  target: ts.ScriptTarget.ESNext,
@@ -1568,7 +2091,8 @@ function buildSystemPrompt(inputs) {
1568
2091
  const scr = inputs.screen ?? "universal";
1569
2092
  const shellDesc = SHELL_DESCRIPTIONS[shell] ?? SHELL_DESCRIPTIONS.fullscreen;
1570
2093
  const screenDesc = SCREEN_DESCRIPTIONS[scr] ?? SCREEN_DESCRIPTIONS.universal;
1571
- const criteriaBlock = inputs.criteriaBlock ?? buildCodingCriteriaSummary();
2094
+ const designMode = inputs.designMode ?? DEFAULT_DESIGN_MODE;
2095
+ const criteriaBlock = inputs.criteriaBlock ?? buildCodingCriteriaSummary(designMode);
1572
2096
  const pitfallsBlock = inputs.pitfallsBlock ?? "";
1573
2097
  const designSystemDocs = inputs.designSystemDocs ?? "";
1574
2098
  const primitivesDoc = inputs.primitivesDoc ?? "";
@@ -1581,6 +2105,17 @@ function buildSystemPrompt(inputs) {
1581
2105
  ## Shape Guidance
1582
2106
  ${inputs.axisDelta}
1583
2107
  ` : "";
2108
+ if (designMode === "free") {
2109
+ return buildFreeDesignPrompt({
2110
+ userRequest: inputs.userRequest,
2111
+ canvas: inputs.canvas ?? canvasForRendering(inputs.shellType, inputs.screen),
2112
+ axisSection,
2113
+ criteriaBlock,
2114
+ wireDoc,
2115
+ primitivesDoc,
2116
+ gadgetsSection
2117
+ });
2118
+ }
1584
2119
  return `You are ggui's UI builder. You receive a typed boilerplate and fill it in using apply_changes.
1585
2120
 
1586
2121
  ## Your Task
@@ -1597,172 +2132,17 @@ ${inputs.userRequest}
1597
2132
 
1598
2133
  ${criteriaBlock}
1599
2134
  ${axisSection}
1600
- ## Protocol Notes
1601
- 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:
1602
- 1. **Do NOT delete any pre-declared hook.** \`self_check\` fails with \`wire_preservation:<kind>:<name>\` if you remove one.
1603
- 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\`.
1604
- 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.
1605
-
1606
- Renaming a binding is fine \u2014 the wiring is the string-literal argument, not the identifier.
1607
-
1608
- ## Contract surface \u2014 four specs + two catalogs
1609
-
1610
- 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:
1611
-
1612
- | Surface | Direction | Role |
1613
- | -------------------- | -------------------------- | -------------------------------------------------------------------- |
1614
- | \`propsSpec\` | server \u2192 UI (one-shot) | Initial render values delivered once at \`ggui_render\` |
1615
- | \`streamSpec\` | agent \u2192 UI (many) | Typed channels for live updates via \`ggui_emit\` |
1616
- | \`actionSpec\` | UI \u2192 agent (events) | Discrete events driving the agent's next turn (consumed via \`ggui_consume\`) |
1617
- | \`contextSpec\` | UI \u2192 server (state mirror) | UI state the agent observes between turns |
1618
- | \`agentCapabilities.tools\` | catalog | Tools the contract references via \`actionSpec[*].nextStep\` and \`streamSpec[*].source.tool\` |
1619
- | \`clientCapabilities.gadgets\` | catalog | Browser-capability gadget hooks the component code mounts (e.g., \`useGeolocation\`) |
1620
-
1621
- **Placement rule for inbound specs**: actions drive turns; context observes state. There is no third category.
1622
-
1623
- **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.
1624
-
1625
- ## Defensive coding for absent / late-arriving data
1626
-
1627
- 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.**
1628
-
1629
- - **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.
1630
- - **Array iteration**: always default to \`[]\` before \`.map\`/\`.filter\`/\`.length\`. Use \`(props.items ?? []).map(...)\` not \`props.items.map(...)\`. Same for stream.all, stream.latest, etc.
1631
- - **Object access**: optional-chain through nested fields. \`props.user?.name ?? 'Anonymous'\` not \`props.user.name\`.
1632
- - **Number ops**: default before arithmetic. \`(props.count ?? 0) + 1\` not \`props.count + 1\`.
1633
- - **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\`.
1634
- - **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.
1635
- - **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.
1636
- - **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.
1637
- - **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.
1638
-
1639
- 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.
1640
-
1641
- ## Picking the right primitive for user gestures
1642
-
1643
- Choose by what the user is DOING, not where the result goes \u2014 the runtime handles the routing.
1644
-
1645
- | Gesture intent | LLM writes | Notes |
1646
- | -------------- | ---------- | ----- |
1647
- | 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. |
1648
- | 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. |
1649
- | 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. |
1650
- | 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. |
1651
- | 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. |
1652
-
1653
- 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.
1654
-
1655
- **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.
1656
-
1657
- **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.
1658
-
1659
- ## Making a primitive interactive \u2014 \`as={Trait}\`
1660
-
1661
- Structural primitives (\`Box\`, \`Stack\`, \`Row\`, \`Card\`) have NO \`onClick\` by default. Add interactivity with the \`as\` prop \u2014 a trait, not a wrapper:
1662
-
1663
- \`\`\`tsx
1664
- <Card as={Clickable} onClick={() => dispatch('select', { id })}
1665
- hoverStyle={{ boxShadow: 'var(--ggui-shape-shadow-lg)' }}>\u2026</Card>
1666
- \`\`\`
1667
-
1668
- - \`as={Clickable}\` \u2192 \`onClick\` + keyboard activation (Enter/Space) + \`role="button"\` + \`hoverStyle\`/\`activeStyle\`/\`cursor\`.
1669
- - \`as={Hoverable}\` \u2192 \`hoverStyle\` only (no click). \`as={Pressable}\` \u2192 \`onPress\` + \`pressStyle\`.
1670
-
1671
- \`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.
1672
-
1673
- **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\`.
1674
-
1675
- **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.
1676
-
1677
- **\`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\`:
1678
-
1679
- \`\`\`tsx
1680
- // Click-to-edit a label: wrap the Text in a Clickable structural primitive.
1681
- <Box as={Clickable} onClick={() => setEditingId(task.id)}
1682
- style={{ cursor: 'pointer' }}>
1683
- <Text weight="semibold">{task.title}</Text>
1684
- </Box>
1685
-
1686
- // Or pair the label with an explicit edit Button (clearer affordance).
1687
- <Row gap="xs" align="center">
1688
- <Text weight="semibold">{task.title}</Text>
1689
- <Button variant="ghost" size="xs" aria-label="Edit title"
1690
- onClick={() => setEditingId(task.id)}>Edit</Button>
1691
- </Row>
1692
-
1693
- // In edit mode, swap the Text for an Input.
1694
- {editingId === task.id
1695
- ? <Input value={draftTitle} onChange={setDraftTitle} label="Task title" />
1696
- : <Text weight="semibold">{task.title}</Text>}
1697
- \`\`\`
1698
-
1699
- ## Anti-patterns \u2014 DO NOT WRITE
1700
-
1701
- 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:
1702
-
1703
- - \`useWiredTool\`, \`useClientTool\` \u2014 retired hooks. Replace with \`useAction\` (events) and the named hook from \`@ggui-ai/gadgets\` (browser capabilities).
1704
- - \`dispatch: { kind: 'tool', tool: '...' }\` / \`dispatch: { kind: 'agent', intendedTool: '...' }\` \u2014 retired discriminated-union. Use the flat optional \`nextStep?: '<tool>'\` instead.
1705
- - \`mode: 'host-routed'\` / \`mode: 'tool'\` \u2014 retired \`mode\` field. Same fix: flat \`nextStep?\`.
1706
- - \`broadcast: {...}\` on the contract \u2014 retired top-level field. Use \`streamSpec[channel].source: {tool, args?}\` to declare a tool-fed channel.
1707
- - \`wiredTools\` / \`agentTools\` (top-level) \u2014 retired catalog names. Use \`agentCapabilities.tools\`.
1708
- - \`clientTools\` / \`clientCapabilities.capabilities\` \u2014 retired catalog shapes. Use \`clientCapabilities.gadgets\` (entries declare hooks, not RPC).
1709
- - \`@ggui-ai/client-tools\` \u2014 retired package name. Import gadget hooks from \`@ggui-ai/gadgets\`.
1710
- - \`intendedTool\` \u2014 retired. Use \`nextStep\` (flat).
1711
- - \`props: { properties: {...} }\` as a CONTRACT field \u2014 retired. The contract field is \`propsSpec\` (the wire \`props\` field on render / update still carries VALUES).
1712
-
1713
- ## Cross-reference rules
1714
-
1715
- When you declare a reference, also declare the catalog entry it points at:
1716
-
1717
- - \`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\`.
1718
- - \`streamSpec[X].source.tool = 'list_messages'\` \u2192 \`agentCapabilities.tools.list_messages\` MUST exist. Cross-ref code: \`CTR_REF_STREAM_SOURCE\`.
1719
- - The catalog entry's schemas MUST be a superset of the referencing spec's schema. Cross-ref code: \`CTR_SCHEMA_INCOMPAT\`.
1720
-
1721
- ## clientCapabilities \u2014 registered catalog
1722
-
1723
- ${gadgetsSection}
1724
-
1725
- 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.
1726
-
1727
- 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\`.
1728
-
1729
- ## Observable state via \`contextSpec\`
1730
-
1731
- 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**:
1732
-
1733
- \`\`\`tsx
1734
- import { useGguiContext } from '@ggui-ai/wire';
1735
-
1736
- export default function Component(props: Props) {
1737
- // AUTO-GENERATED \u2014 do not remove or rename:
1738
- const [currentStep, setCurrentStep] = useGguiContext<number>('currentStep');
1739
- const [draftText, setDraftText] = useGguiContext<string>('draftText');
1740
-
1741
- // Plain JSX. No Provider wrap. The runtime already wrapped your
1742
- // component in nested SingleSlotProviders before this code ran.
1743
- return (
1744
- <Container>
1745
- <Text>Step {currentStep}</Text>
1746
- <Input value={draftText} onChange={(e) => setDraftText(e.target.value)} />
1747
- <Button onClick={() => setCurrentStep((s) => s + 1)}>Next</Button>
1748
- </Container>
1749
- );
1750
- }
1751
- \`\`\`
1752
-
1753
- For every declared slot you have **\`slotName\` + \`setSlotName\`** in scope:
1754
- - **Read** the value to render: \`<Text>Step {currentStep}</Text>\`
1755
- - **Write** via the setter: \`setCurrentStep(s => s + 1)\` (in callbacks, effects, anywhere)
1756
-
1757
- 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.
1758
-
1759
- **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.
1760
-
1761
- **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.
1762
-
1763
- **\`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.
1764
-
1765
- **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.
2135
+ ` + [
2136
+ PROTOCOL_NOTES,
2137
+ CONTRACT_SURFACE,
2138
+ DEFENSIVE_CODING,
2139
+ GESTURE_ROUTING,
2140
+ INTERACTIVE_TRAITS,
2141
+ ANTI_PATTERNS,
2142
+ CROSS_REFERENCE_RULES,
2143
+ renderGadgetCatalogSection(gadgetsSection),
2144
+ CONTEXT_SPEC_SECTION
2145
+ ].join("\n\n") + `
1766
2146
 
1767
2147
  ${pitfallsBlock}
1768
2148
 
@@ -1778,7 +2158,7 @@ ${designSystemDocs}
1778
2158
  ${primitivesDoc}
1779
2159
  `;
1780
2160
  }
1781
- var DESIGN_SYSTEM_GUIDANCE = `## Imports & Component Surface
2161
+ var DESIGN_SYSTEM_GUIDANCE_SURFACE_AND_TOKENS = `## Imports & Component Surface
1782
2162
 
1783
2163
  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.
1784
2164
 
@@ -1813,7 +2193,7 @@ EXACT primitive prop values (other values are silently ignored \u2014 the design
1813
2193
  - \`<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\`.
1814
2194
  - \`<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.
1815
2195
  - \`<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\`.
1816
- - \`<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.
2196
+ - \`<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.
1817
2197
 
1818
2198
  **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'\`).
1819
2199
 
@@ -1846,8 +2226,8 @@ MANDATORY:
1846
2226
 
1847
2227
  Token categories:
1848
2228
  - Brand: \`var(--ggui-color-primary-600)\`, \`var(--ggui-color-primary-50)\`
1849
- - Text: \`var(--ggui-color-onSurface)\`, \`var(--ggui-color-onSurfaceVariant)\`
1850
- - Backgrounds: \`var(--ggui-color-surface)\`, \`var(--ggui-color-surfaceVariant)\`
2229
+ - Text: \`var(--ggui-color-onContainer)\`, \`var(--ggui-color-onSunken)\`
2230
+ - Backgrounds: \`var(--ggui-color-container)\`, \`var(--ggui-color-sunken)\`
1851
2231
  - Borders: \`var(--ggui-color-outline)\`
1852
2232
  - Spacing: \`var(--ggui-spacing-4)\`, \`var(--ggui-spacing-6)\`
1853
2233
  - Typography: \`var(--ggui-font-size-sm)\`, \`var(--ggui-font-weight-semibold)\`
@@ -1868,7 +2248,7 @@ Use the FULL primary palette throughout the component \u2014 NOT only on submit
1868
2248
  | Buttons, CTAs, filled interactive elements | \`primary-600\` / \`primary-700\` | Primary actions |
1869
2249
  | Headings on light primary backgrounds | \`primary-800\` / \`primary-900\` | High-contrast branded text |
1870
2250
 
1871
- 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.
2251
+ 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.
1872
2252
 
1873
2253
  ### Theme-Agnostic Design
1874
2254
 
@@ -1877,7 +2257,7 @@ Components MUST be theme-agnostic \u2014 they reference CSS variables but NEVER
1877
2257
  DO:
1878
2258
  - Use \`var(--ggui-color-primary-*)\` for brand elements \u2014 the theme controls what "primary" means
1879
2259
  - Use \`var(--ggui-shape-shadow-*)\` for depth, \`var(--ggui-shape-radius-*)\` for corners
1880
- - Use semantic color roles: primary for brand, surface/onSurface for structure, success/error/warning for state
2260
+ - Use semantic color roles: primary for brand; the layering roles (ground / container / elevated / sunken + their on* inks) for structure; success/error/warning for state
1881
2261
 
1882
2262
  DON'T:
1883
2263
  - Don't assume primary is blue \u2014 could be red, green, purple
@@ -1898,59 +2278,8 @@ Generated components become reusable blueprints \u2014 the same blueprint serves
1898
2278
  2. Relative/fluid units \u2014 prefer \`%\`, \`em\`, \`rem\`, \`min()\`, \`max()\`, \`clamp()\` over fixed \`px\`.
1899
2279
  3. Fluid widths \u2014 \`max-width\` with \`width: 100%\`. Never set a fixed width.
1900
2280
  4. Compact padding \u2014 components are embedded in containers that provide their own chrome.
1901
- 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.
1902
-
1903
- ## Data Parameterization (CRITICAL)
1904
-
1905
- 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:
1906
-
1907
- \`\`\`tsx
1908
- // BAD \u2014 hardcoded, only works for Tokyo
1909
- const city = "Tokyo";
1910
- const temp = 18;
1911
-
1912
- // GOOD \u2014 parameterized via props with defaults from the request
1913
- interface Props {
1914
- city?: string;
1915
- temperature?: number;
1916
- }
1917
- export default function WeatherCard({ city = "Tokyo", temperature = 18 }: Props) {
1918
- // A controller can override for Seoul, Paris, etc.
1919
- }
1920
- \`\`\`
1921
-
1922
- Rules:
1923
- 1. All request-specific data \u2192 props with defaults. City names, tickers, user names, dates, counts.
1924
- 2. Layout and styling are universal. Colors, spacing, structure \u2014 these are the reusable part.
1925
- 3. Default values come from the current request \u2014 so the component renders correctly standalone.
1926
- 4. Props interface must be typed and exported.
1927
-
1928
- ## Component Structure
1929
-
1930
- 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.
1931
-
1932
- \`\`\`tsx
1933
- import { useState } from 'react';
1934
- import { Container, Card, Stack, Text, Button, Input } from '@ggui-ai/design';
1935
-
1936
- interface Props {
1937
- onSubmit?: (data: unknown) => void;
1938
- }
1939
-
1940
- function ItemCard({ item, onEdit }: { item: Item; onEdit: (id: string) => void }) {
1941
- return <Card padding="md">\u2026</Card>;
1942
- }
1943
-
1944
- export default function GeneratedComponent({ onSubmit }: Props) {
1945
- return (
1946
- <Container>
1947
- {items.map((item) => <ItemCard key={item.id} item={item} onEdit={handleEdit} />)}
1948
- </Container>
1949
- );
1950
- }
1951
- \`\`\`
1952
-
1953
- ## Aesthetic Guidance (READ CAREFULLY \u2014 this is what separates "polished" from "ok")
2281
+ 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.`;
2282
+ var DESIGN_SYSTEM_GUIDANCE_AESTHETICS_AND_CHECKLIST = `## Aesthetic Guidance (READ CAREFULLY \u2014 this is what separates "polished" from "ok")
1954
2283
 
1955
2284
  ### Visual hierarchy \u2014 the SCALE GAP rule
1956
2285
 
@@ -1972,11 +2301,11 @@ A polished UI has ONE hero that dominates. Everything else supports it. Bad layo
1972
2301
  ### Color discipline \u2014 the 60/30/10 rule
1973
2302
 
1974
2303
  Don't paint everything in primary. Use:
1975
- - **60% surface** (\`var(--ggui-color-surface)\` / \`onSurface\`) \u2014 body text, default backgrounds, structure
1976
- - **30% surfaceVariant + onSurfaceVariant** \u2014 secondary text, captions, labels, dividers
2304
+ - **60% container** (\`var(--ggui-color-container)\` / \`onContainer\`) \u2014 body text, default backgrounds, structure
2305
+ - **30% sunken + onSunken** \u2014 wells, secondary text, captions, labels, dividers
1977
2306
  - **10% primary** \u2014 hero number, ONE highlight element, CTAs, brand accent
1978
2307
 
1979
- 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.
2308
+ 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.
1980
2309
 
1981
2310
  \`\`\`tsx
1982
2311
  // BAD \u2014 everything purple, eye has no anchor
@@ -1985,7 +2314,7 @@ If your component is 100% purple text on purple backgrounds, you've lost the eye
1985
2314
  <Text tone="emphasized">all body text</Text>
1986
2315
 
1987
2316
  // GOOD \u2014 hero pops, body is neutral, primary is reserved
1988
- <Heading>Title</Heading> {/* defaults to onSurface */}
2317
+ <Heading>Title</Heading> {/* defaults to onContainer */}
1989
2318
  <Text size="4xl" weight="bold" tone="emphasized">42</Text>
1990
2319
  <Text tone="muted">all body text</Text>
1991
2320
  \`\`\`
@@ -2043,6 +2372,12 @@ Hero sections should feel airy. Use \`padding="xl"\` (32px) on the main card, no
2043
2372
  - [ ] Live/streaming regions wrapped in \`aria-live="polite"\`
2044
2373
  - [ ] Headings nest \u2014 one \`level={1}\`, then \`level={2}\`/\`{3}\` \u2014 never skipped or inverted
2045
2374
  - [ ] Wire hooks (\`useAction\`, \`useStream\`) imported from \`@ggui-ai/wire\` and consumed`;
2375
+ var DESIGN_SYSTEM_GUIDANCE = [
2376
+ DESIGN_SYSTEM_GUIDANCE_SURFACE_AND_TOKENS,
2377
+ DATA_PARAMETERIZATION,
2378
+ COMPONENT_STRUCTURE,
2379
+ DESIGN_SYSTEM_GUIDANCE_AESTHETICS_AND_CHECKLIST
2380
+ ].join("\n\n");
2046
2381
 
2047
2382
  // src/tools.ts
2048
2383
  var APPLY_CHANGES_TOOL = {
@@ -2283,13 +2618,16 @@ function countCacheTiers(fragments) {
2283
2618
  function createHarness(input) {
2284
2619
  const { classification, contract, prompt, shellType, screen, overrides } = input;
2285
2620
  const ctx = { classification, contract, prompt };
2621
+ const designMode = input.designMode ?? DEFAULT_DESIGN_MODE;
2286
2622
  const composed = compose(classification);
2287
2623
  const systemPromptBuilder = input.systemPromptBuilder ?? buildSystemPrompt;
2288
2624
  const systemPrompt = systemPromptBuilder({
2289
2625
  userRequest: prompt,
2290
2626
  shellType,
2291
2627
  screen,
2292
- axisDelta: composed.promptText
2628
+ axisDelta: composed.promptText,
2629
+ designMode,
2630
+ ...input.canvas !== void 0 ? { canvas: input.canvas } : {}
2293
2631
  });
2294
2632
  const howFragments = composed.fragments.filter(
2295
2633
  (f) => f.promptText && f.promptText.trim().length > 0
@@ -2307,7 +2645,8 @@ function createHarness(input) {
2307
2645
  shellType,
2308
2646
  screen,
2309
2647
  composed.boilerplateSections,
2310
- input.appGadgets
2648
+ input.appGadgets,
2649
+ designMode
2311
2650
  );
2312
2651
  const whatFragments = composed.fragments.filter(
2313
2652
  (f) => f.boilerplateMarker && f.boilerplateMarker.trim().length > 0
@@ -2358,6 +2697,7 @@ function createHarness(input) {
2358
2697
  if (overrides?.process) overrideLabels.push("process");
2359
2698
  if (overrides?.label) overrideLabels.push(`label:${overrides.label}`);
2360
2699
  if (!isDefaultHarnessPolicy(policy)) overrideLabels.push("policy");
2700
+ if (designMode !== DEFAULT_DESIGN_MODE) overrideLabels.push(`designMode:${designMode}`);
2361
2701
  const id = computeHarnessId({
2362
2702
  classificationHash,
2363
2703
  howVersion: how.version,
@@ -2385,6 +2725,7 @@ function createHarness(input) {
2385
2725
  id,
2386
2726
  name,
2387
2727
  classification,
2728
+ designMode,
2388
2729
  how,
2389
2730
  what,
2390
2731
  check,