@ggui-ai/ui-gen 0.6.3 → 0.7.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 (35) hide show
  1. package/dist/adapters/generation-dispatch.js +20 -8
  2. package/dist/adapters/generation-dispatch.js.map +1 -1
  3. package/dist/adapters/index.js +1 -1
  4. package/dist/adapters/index.js.map +1 -1
  5. package/dist/advanced/index.js +20 -8
  6. package/dist/advanced/index.js.map +1 -1
  7. package/dist/boilerplate.js +9 -5
  8. package/dist/boilerplate.js.map +1 -1
  9. package/dist/check/index.js.map +1 -1
  10. package/dist/evaluation/axis-checks/index.js.map +1 -1
  11. package/dist/evaluation/index.js +3 -3
  12. package/dist/evaluation/index.js.map +1 -1
  13. package/dist/harness/index.js +9 -5
  14. package/dist/harness/index.js.map +1 -1
  15. package/dist/harness/runtime.js +10 -6
  16. package/dist/harness/runtime.js.map +1 -1
  17. package/dist/harness/types-public.js +9 -5
  18. package/dist/harness/types-public.js.map +1 -1
  19. package/dist/index.js +20 -8
  20. package/dist/index.js.map +1 -1
  21. package/dist/tools/get-primitives-ts.d.ts +1 -1
  22. package/dist/tools/get-primitives-ts.js +1 -1
  23. package/dist/tools/get-primitives-ts.js.map +1 -1
  24. package/dist/validation/index.d.ts +1 -1
  25. package/dist/validation/index.js +1 -1
  26. package/dist/validation/index.js.map +1 -1
  27. package/package.json +12 -12
  28. package/src/boilerplate/generate.ts +2 -0
  29. package/src/boilerplate/system-prompt.ts +3 -1
  30. package/src/boilerplate/templates/base.tsx.tmpl +1 -1
  31. package/src/evaluation/llm-evaluator.ts +8 -1
  32. package/src/evaluation/types-public.ts +4 -3
  33. package/src/harness/primitive-slice.ts +1 -1
  34. package/src/tools/get-primitives-ts.ts +1 -1
  35. package/src/validation/primitives.ts +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/openrouter/types.ts","../../src/adapters/openrouter/client.ts","../../src/evaluation/types-public.ts","../../src/adapters/claude/client.ts","../../src/adapters/provider-router.ts","../../src/adapters/tool-bridge.ts","../../src/harness/llm-trace-sink.ts","../../src/harness/llm-router.ts","../../src/evaluation/evaluator.ts","../../src/evaluation/message-parsing.ts","../../src/evaluation/prompts.ts","../../src/evaluation/types.ts","../../src/evaluation/loop.ts","../../src/evaluation/mcp-server.ts","../../src/evaluation/axis-checks/helpers.ts","../../src/evaluation/axis-checks/checks/universal.ts","../../src/evaluation/axis-checks/checks/state-merge.ts","../../src/evaluation/axis-checks/checks/realtime.ts","../../src/evaluation/axis-checks/checks/writes.ts","../../src/evaluation/axis-checks/checks/state-payload.ts","../../src/evaluation/axis-checks/checks/tooling.ts","../../src/evaluation/axis-checks/extras.ts","../../src/evaluation/axis-checks/registry.ts","../../src/evaluation/axis-checks/dispatch.ts"],"names":["tool","OpenRouterClient","z","REALTIME_ACTIVE","mkIssue","matches"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,IA4Ha,eAAA;AA5Hb,IAAA,UAAA,GAAA,KAAA,CAAA;AAAA,EAAA,kCAAA,GAAA;AA4HO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,MACzC,WAAA,CACE,OAAA,EACgB,MAAA,EACA,IAAA,EAChB;AACA,QAAA,KAAA,CAAM,OAAO,CAAA;AAHG,QAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,QAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,QAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AAAA,MACd;AAAA,MALkB,MAAA;AAAA,MACA,IAAA;AAAA,MAMlB,IAAI,WAAA,GAAuB;AACzB,QAAA,OAAO,IAAA,CAAK,MAAA,KAAW,GAAA,IAAO,IAAA,CAAK,MAAA,KAAW,OACzC,IAAA,CAAK,MAAA,KAAW,GAAA,IAAO,IAAA,CAAK,MAAA,KAAW,GAAA;AAAA,MAC9C;AAAA,KACF;AAAA,EAAA;AAAA,CAAA,CAAA;;;AC1IA,IAAA,cAAA,GAA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,EACH,GAAG,kBAAA;AAAA,EACH,GAAG,eAAA;AAAA,EACH,GAAG,aAAA;AAAA,EACH,GAAG,oBAAA;AAAA,EACH,GAAG,cAAA;AAAA,EACH,GAAG;AACL,CAAA;;;ACLO,SAAS,aAAA,CACd,gBACA,KAAA,EACa;AACb,EAAA,IAAI,KAAA,CAAM,YAAA,KAAiB,IAAA,EAAM,OAAO,EAAC;AAEzC,EAAA,MAAM,SAAA,GAA4B;AAAA,IAChC,YAAY,KAAA,CAAM,UAAA;AAAA,IAClB,cAAc,KAAA,CAAM,YAAA;AAAA,IACpB,GAAI,MAAM,QAAA,KAAa,MAAA,GAAY,EAAE,QAAA,EAAU,KAAA,CAAM,QAAA,EAAS,GAAI,EAAC;AAAA,IACnE,gBAAgB,KAAA,CAAM,cAAA;AAAA,IACtB;AAAA,GACF;AAEA,EAAA,MAAM,SAAsB,EAAC;AAC7B,EAAA,MAAM,QAAA,uBAAe,GAAA,EAAY;AACjC,EAAA,KAAA,MAAW,SAAS,QAAA,EAAU;AAC5B,IAAA,IAAI,CAAC,OAAA,CAAQ,cAAA,CAAe,MAAA,EAAQ,KAAK,CAAA,EAAG;AAE5C,IAAA,IAAI,QAAA,CAAS,GAAA,CAAI,KAAA,CAAM,EAAE,CAAA,EAAG;AAC5B,IAAA,QAAA,CAAS,GAAA,CAAI,MAAM,EAAE,CAAA;AACrB,IAAA,MAAA,CAAO,IAAA,CAAK,GAAG,KAAA,CAAM,GAAA,CAAI,SAAS,CAAC,CAAA;AAAA,EACrC;AACA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["// packages/ui-gen/src/adapters/openrouter/types.ts\n//\n// OpenRouter-specific types for the chat completion API.\n// Reference: https://openrouter.ai/docs/api-reference\n\nimport type { JsonObject } from '@ggui-ai/protocol';\n\n// =============================================================================\n// Model metadata (from GET /api/v1/models)\n// =============================================================================\n\n/** Model entry from OpenRouter's /api/v1/models endpoint */\nexport interface OpenRouterModelEntry {\n id: string;\n name: string;\n description: string;\n pricing: { prompt: string; completion: string; image?: string };\n context_length: number;\n architecture: {\n modality: string;\n tokenizer: string;\n instruct_type: string | null;\n };\n top_provider: {\n context_length: number;\n max_completion_tokens: number;\n is_moderated: boolean;\n };\n per_request_limits: Record<string, string> | null;\n}\n\n// =============================================================================\n// Chat Completion API\n// =============================================================================\n\nexport interface OpenRouterMessage {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string | OpenRouterContentBlock[] | null;\n tool_calls?: OpenRouterToolCall[];\n tool_call_id?: string;\n}\n\nexport interface OpenRouterContentBlock {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral' };\n}\n\nexport interface OpenRouterTool {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: JsonObject;\n };\n}\n\nexport interface OpenRouterToolCall {\n id: string;\n type: 'function';\n function: { name: string; arguments: string };\n}\n\nexport interface OpenRouterChatRequest {\n model: string;\n messages: OpenRouterMessage[];\n tools?: OpenRouterTool[];\n tool_choice?: 'auto' | 'required' | 'none';\n max_tokens?: number;\n temperature?: number;\n stream?: boolean;\n thinking?: { type: 'enabled'; budget_tokens: number };\n}\n\nexport interface OpenRouterChatResponse {\n id: string;\n model: string;\n choices: Array<{\n index: number;\n message: {\n role: 'assistant';\n content: string | null;\n tool_calls?: OpenRouterToolCall[];\n thinking?: string;\n };\n finish_reason: string;\n }>;\n usage: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n };\n}\n\n// =============================================================================\n// SSE Streaming\n// =============================================================================\n\nexport interface OpenRouterStreamDelta {\n id: string;\n model: string;\n choices: Array<{\n index: number;\n delta: {\n role?: 'assistant';\n content?: string | null;\n tool_calls?: Array<{\n index: number;\n id?: string;\n type?: 'function';\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason: string | null;\n }>;\n usage?: OpenRouterChatResponse['usage'];\n}\n\n// =============================================================================\n// Error\n// =============================================================================\n\nexport class OpenRouterError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code?: string,\n ) {\n super(message);\n this.name = 'OpenRouterError';\n }\n\n get isTransient(): boolean {\n return this.status === 408 || this.status === 429\n || this.status === 502 || this.status === 503;\n }\n}\n","// packages/ui-gen/src/adapters/openrouter/client.ts\n//\n// Direct fetch()-based HTTP client for OpenRouter's API.\n// No OpenAI SDK dependency — independent implementation.\n\nimport type {\n OpenRouterChatRequest,\n OpenRouterChatResponse,\n OpenRouterStreamDelta,\n} from './types';\nimport { OpenRouterError } from './types';\n\nexport interface OpenRouterClientConfig {\n apiKey: string;\n baseUrl?: string;\n siteUrl?: string;\n siteName?: string;\n}\n\nconst DEFAULT_BASE_URL = 'https://openrouter.ai/api/v1';\n\nexport class OpenRouterClient {\n private readonly baseUrl: string;\n private readonly headers: Record<string, string>;\n\n constructor(private readonly config: OpenRouterClientConfig) {\n this.baseUrl = config.baseUrl ?? process.env.OPENROUTER_BASE_URL ?? DEFAULT_BASE_URL;\n this.headers = {\n 'Authorization': `Bearer ${config.apiKey}`,\n 'Content-Type': 'application/json',\n 'HTTP-Referer': config.siteUrl ?? process.env.OPENROUTER_SITE_URL ?? 'https://ggui.ai',\n 'X-Title': config.siteName ?? process.env.OPENROUTER_SITE_NAME ?? 'ggui',\n };\n }\n\n /**\n * Non-streaming chat completion.\n */\n async chatCompletion(\n params: Omit<OpenRouterChatRequest, 'stream'>,\n ): Promise<OpenRouterChatResponse> {\n const body: OpenRouterChatRequest = { ...params, stream: false };\n const response = await fetch(`${this.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: this.headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));\n const message = (errorBody as { error?: { message?: string } }).error?.message ?? response.statusText;\n throw new OpenRouterError(message, response.status);\n }\n\n return response.json() as Promise<OpenRouterChatResponse>;\n }\n\n /**\n * Streaming chat completion via SSE.\n * Yields delta chunks, accumulates the final usage from the last chunk.\n */\n async *chatCompletionStream(\n params: Omit<OpenRouterChatRequest, 'stream'>,\n ): AsyncGenerator<OpenRouterStreamDelta> {\n const body: OpenRouterChatRequest = { ...params, stream: true };\n const response = await fetch(`${this.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: this.headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));\n const message = (errorBody as { error?: { message?: string } }).error?.message ?? response.statusText;\n throw new OpenRouterError(message, response.status);\n }\n\n if (!response.body) {\n throw new OpenRouterError('No response body for streaming request', 500);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(':')) continue;\n if (trimmed === 'data: [DONE]') return;\n if (!trimmed.startsWith('data: ')) continue;\n\n const json = trimmed.slice('data: '.length);\n try {\n yield JSON.parse(json) as OpenRouterStreamDelta;\n } catch {\n // Skip malformed chunks\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n","// Evaluation type vocabulary shared between the harness runtime and its\n// check/evaluator surfaces. This is the narrow contract layer — the\n// type language every harness leg is written against:\n//\n// - `EvalIssue` — the single issue shape everything produces.\n// - `EvalTier` / `EvalOutcome` / `EvalCategory` — the issue's axes.\n// - `Priority` — P0/P1/P2 ranking referenced by the retry formatter.\n// - `EvalResult` — aggregate shape a runner returns.\n// - `QualityMode` / `QualityConfig` / `DEFAULT_QUALITY_CONFIG` —\n// the quality-mode knob the adapter surface consumes.\n// - `priorityForIssue` / `isBlocked` / `getActionableIssues` — the\n// purely-typed helpers over the vocabulary.\n//\n// `EvalIssue` is referenced by `PatchFn`, `TierCheck`, `LLMEvaluator`,\n// and `RuntimeRenderCheck` in the harness types hub.\n\n// ─── Priority ──────────────────────────────────────────────────────────────\n// P0 = must (compile + complete), P1 = should (safety), P2 = nice (quality).\n// Single source of truth for the retry-formatter ranking.\n\nexport type Priority = \"P0\" | \"P1\" | \"P2\";\n\n// ─── Issue shape ───────────────────────────────────────────────────────────\n\nexport type EvalTier = 0 | 1 | 2;\nexport type EvalOutcome = \"fail\" | \"warn\" | \"pass\";\n\nexport type EvalCategory =\n | \"compile\"\n | \"security\"\n | \"contract\"\n | \"types\"\n | \"imports\"\n | \"tokens\" // tier 0\n | \"mode\" // tier 0 — per-mode deterministic\n | \"functionality\"\n | \"crash\" // tier 1\n | \"interactivity\"\n | \"accessibility\"\n | \"layout\"\n | \"loading\"\n | \"visual\"; // tier 2\n\nexport interface EvalIssue {\n tier: EvalTier;\n result: EvalOutcome;\n category: EvalCategory;\n /**\n * Priority tier — threaded through to the retry formatter so the LLM can\n * rank its next patch against the prompt's P0/P1/P2 priority schema.\n * Derived from (category, result) via {@link priorityForIssue} when not\n * explicitly set. Optional on construction; check-runners typically\n * populate it before returning.\n */\n priority?: Priority;\n subcategory?: string;\n severity?: \"critical\" | \"major\";\n description: string;\n fix: string;\n line?: number;\n}\n\n/**\n * Runtime-render probe execution status — three-valued so \"the probe\n * never ran\" is never conflated with \"the probe ran clean\".\n *\n * - `ran` — probe executed; its findings (possibly none) are\n * in the issue stream under `runtime:*` subcategories.\n * - `infra-skipped` — probe could NOT execute (environment failure:\n * happy-dom load, user-event document capture,\n * ESM/CJS interop). Carries ZERO probe evidence;\n * consumers MUST NOT count it as a pass.\n * - `not-applicable`— nothing to probe (no compiled code, no contract\n * surface, or no runtimeRender check configured).\n */\nexport type RuntimeProbeStatus = \"ran\" | \"infra-skipped\" | \"not-applicable\";\n\n/**\n * Probe execution meta stamped onto an `EvalResult` at the exit-decision\n * points that invoke the probe. Absence of this field means the eval\n * path never reached a probe invocation at all — consumers treat that\n * the same as not-run, never as a pass.\n */\nexport interface RuntimeProbeMeta {\n readonly status: RuntimeProbeStatus;\n /** Populated for `infra-skipped` / `not-applicable` — why the probe didn't run. */\n readonly reason?: string;\n}\n\nexport interface EvalResult {\n issues: EvalIssue[];\n pass: string[];\n /**\n * Runtime-render probe execution meta. Stamped by the exit-decision\n * probe runner; absent on eval paths that never invoke the probe.\n */\n runtimeProbe?: RuntimeProbeMeta;\n}\n\n// ─── Quality mode ──────────────────────────────────────────────────────────\n\nexport type QualityMode = \"fast\" | \"auto-improve\" | \"high-quality\";\n\nexport interface QualityConfig {\n quality: QualityMode;\n visualEval: boolean;\n maxCostPerGeneration: number;\n model?: { provider?: string; model?: string };\n}\n\nexport const DEFAULT_QUALITY_CONFIG: QualityConfig = {\n quality: \"fast\",\n visualEval: false,\n maxCostPerGeneration: 3,\n};\n\n// ─── Axis-check types ──────────────────────────────────────────────────────\n// The `AxisCheck` type vocabulary lives here. The check bodies\n// themselves (REGISTRY, per-axis implementations) live under\n// `./axis-checks/`.\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { AxisVector, Classification } from \"../classifier/axes.js\";\nimport type { AxisKey } from \"../fragments/index.js\";\n\nexport interface AxisCheckInput {\n sourceCode: string;\n compiledCode: string | null;\n contract?: DataContract;\n originalPrompt: string;\n /** Full classification — checks may read sibling axes. */\n classification: Classification;\n}\n\n/**\n * A gated check. Runs only when the classification's axis value matches\n * one of the gate's accepted values. Multiple gates (implicit AND) support\n * cross-axis combinations.\n */\nexport interface AxisCheck {\n /** Stable id used in issue subcategories. */\n id: string;\n /** Primary axis this check gates on. */\n axis: AxisKey;\n /** Which values of that axis activate the check. */\n values: readonly string[];\n /** Optional extra gate on a sibling axis (e.g., only when state=merge AND writes=per-item). */\n and?: { axis: AxisKey; values: readonly string[] };\n /** Execute the check and emit zero or more issues. */\n run(input: AxisCheckInput): EvalIssue[];\n}\n\n/**\n * Whether a check's gate(s) match the given axis vector. Pure function,\n * no issue emission.\n */\nexport function matches(vector: AxisVector, check: AxisCheck): boolean {\n const primary = vector[check.axis] as string;\n if (!check.values.includes(primary)) return false;\n if (check.and) {\n const sibling = vector[check.and.axis] as string;\n if (!check.and.values.includes(sibling)) return false;\n }\n return true;\n}\n\n// ─── Purely-typed helpers ──────────────────────────────────────────────────\n\n/**\n * Map a tier-0 issue category to the canonical P0/P1/P2 priority.\n *\n * Sourced from the criteria priority assignments:\n * - P0 (must): compile, security, imports, contract, types, mode\n * - P1 (safety): tokens, crash, functionality\n * - P2 (quality): interactivity, accessibility, layout, loading, visual\n */\nexport function priorityForIssue(category: EvalCategory): Priority {\n if (\n category === \"interactivity\" ||\n category === \"accessibility\" ||\n category === \"layout\" ||\n category === \"loading\" ||\n category === \"visual\"\n ) {\n return \"P2\";\n }\n if (category === \"tokens\" || category === \"crash\" || category === \"functionality\") {\n return \"P1\";\n }\n // compile, security, imports, contract, types, mode → P0.\n return \"P0\";\n}\n\n/** Whether any issue blocks shipping (has result = 'fail'). */\nexport function isBlocked(result: EvalResult): boolean {\n return result.issues.some((i) => i.result === \"fail\");\n}\n\n/**\n * Return the issues the agent should act on, depending on quality mode.\n * - fast: only fails (blocking issues)\n * - auto-improve / high-quality: fails + warns\n */\nexport function getActionableIssues(result: EvalResult, mode: QualityMode): EvalIssue[] {\n if (mode === \"fast\") {\n return result.issues.filter((i) => i.result === \"fail\");\n }\n return result.issues.filter((i) => i.result === \"fail\" || i.result === \"warn\");\n}\n\n// ─── Criteria (single source of truth for coding + eval sides) ─────────────\n//\n// Each criterion is defined ONCE with both sides of the contract:\n// - codingGuidance: what the coding agent should DO\n// - evalInstruction: what the eval agent should CHECK\n// They must be compatible — changing one means reviewing the other.\n//\n// This is *validated* shipping content: it's what the hosted runtime sends\n// to every generation today. External OSS implementers building their own\n// prompts should be able to use the same rubric — hence it's open.\n\nexport interface EvalCriterion {\n /** Unique identifier matching the eval tool name (e.g., 'functionality') */\n id: string;\n /** Human-readable name shown to both agents */\n name: string;\n /** Priority tier — P0 must, P1 should, P2 nice */\n priority: Priority;\n /** What the coding agent should DO to satisfy this criterion */\n codingGuidance: string;\n /** What the eval agent should CHECK — the evaluation prompt */\n evalInstruction: string;\n /** Tier 0 = programmatic, Tier 1 = LLM critical, Tier 2 = LLM quality */\n tier: 0 | 1 | 2;\n /** Eval outcome when this criterion fails */\n failOutcome: \"fail\" | \"warn\";\n}\n\nexport const CRITERIA: readonly EvalCriterion[] = [\n // ── P0: Correctness (must satisfy — failure = broken component) ──\n\n {\n id: \"compile\",\n name: \"Compile & type-check\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance:\n \"Code must compile. The typed Props and wire hook generics are enforced by the compiler.\",\n evalInstruction: \"Checked automatically by esbuild + TypeScript. No LLM evaluation needed.\",\n },\n {\n id: \"render-props\",\n name: \"Render all Props fields\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance: \"Render every Props field in JSX. Access via props.fieldName.\",\n evalInstruction:\n \"Check that every field from interface Props appears as props.fieldName in the function body.\",\n },\n {\n id: \"wire-hooks\",\n name: \"Wire all contract hooks\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Wire every useAction/useStream and every clientCapabilities.gadgets hook (e.g., useGeolocation) to a UI element. `agentCapabilities.tools` is a catalog the AGENT invokes — NOT a component hook surface.\",\n evalInstruction:\n \"Check that every hook variable from the boilerplate appears in the JSX or an effect.\",\n },\n {\n id: \"imports\",\n name: \"Valid imports only\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Only import from react, @ggui-ai/design/*, and @ggui-ai/wire.\",\n evalInstruction: \"Flag any import from a package not in the allowlist.\",\n },\n {\n id: \"security\",\n name: \"No eval/fetch/window\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Never use eval(), fetch(), or window. Data comes from props and hooks.\",\n evalInstruction: \"Flag any call to eval(), fetch(), or window access.\",\n },\n\n // ── P1: Safety (should satisfy — failure = crash or bad UX) ──\n\n {\n id: \"functionality\",\n name: \"All features implemented\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance: \"Implement ALL features from the request AND the data contract.\",\n evalInstruction: `Evaluate FUNCTIONALITY: Does this component implement ALL features from the request AND the data contract?\n\nCheck against BOTH sources:\n1. Original request — each feature must be coded AND rendered in JSX\n2. Data contract (if present) — verify:\n - Props fields are rendered in the UI. EXCEPTION: pure identifier fields (\\`id\\`, \\`*Id\\`, keys) that exist only to be echoed back inside an action payload do NOT need to be visibly rendered.\n - ALL useAction hooks are wired to clickable UI elements\n - ALL useStream hooks are consumed — the streamed data must reach the UI. Merging stream events into rendered state (a list, a counter, the displayed records) COUNTS as consuming the stream; it need not be a literal \\`.latest\\` render.\n - ALL clientCapabilities gadgets are used. \\`clientCapabilities.gadgets\\` is keyed by npm package: built-in browser capabilities (useGeolocation / useCamera / …) import from @ggui-ai/gadgets; registered third-party gadgets (e.g. useChartTheme) import from their OWN package. Any gadget the contract declares IS a contract feature — NEVER flag it as \"not part of the contract\".\n - \\`agentCapabilities.tools\\` is a catalog declaration only; do NOT flag missing component-side calls for it\n\nA contract hook that is declared but never used at all is a MISSING feature.\n\nCRITICAL: The \"issues\" array must ONLY contain features you are CERTAIN are missing or broken — never an implemented feature. (See \"Issue-array discipline\" above: no speculative, self-negating, or \"verify that…\" entries.)`,\n },\n {\n id: \"crash\",\n name: \"No crash scenarios\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance:\n \"Guard optional props (props.field?.x). stream.latest is T|null — always null-guard. .all is always an array.\",\n evalInstruction: `Evaluate CRASH SAFETY: Are there ACTUAL runtime crash scenarios?\n\nWILL crash (include in issues):\n- .map()/.filter()/.length on an uninitialized variable\n- Accessing property of undefined without guard\n- useStream().latest.field WITHOUT null guard — .latest is T | null\n- Optional Props field accessed as props.field.x without guard\n- Array item optional field: items.map(item => item.priority.toUpperCase()) when priority is optional\n\nSAFE (do NOT include):\n- Optional chaining: props.items?.map() — SAFE\n- Fallback: items || [] — SAFE\n- useState initializer: useState([]) — SAFE\n- Null check: items && items.map() — SAFE\n- stream.latest && stream.latest.field — SAFE, guarded\n- stream.all.map(...) — SAFE, .all is always an array\n- stream.all.length — SAFE, always a number\n\nThe \"issues\" array is ONLY for a specific line that WILL throw at runtime. NEVER put a line you have determined is safe into the issues array — not even to note that it is safe (\"…so this is safely guarded\", \"…so there is no crash\"). If you cannot name a concrete line that will throw, the answer is {\"pass\": true} — return that and an empty issues array.`,\n },\n {\n id: \"tokens\",\n name: \"Design system tokens\",\n priority: \"P1\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Use CSS variables for colors (var(--ggui-color-*)); use the spacing scale for gap/padding/margin (gap=\\\"md\\\", padding=\\\"lg\\\").\",\n evalInstruction:\n \"Flag hardcoded hex colors, rgba/hsl functions, and numeric or raw-CSS-length spacing props. A t-shirt-scale spacing name (gap=\\\"md\\\") IS a token — never flag it.\",\n },\n\n // ── P2: Quality (nice to have — failure = lower score, not broken) ──\n\n {\n id: \"interactivity\",\n name: \"Sufficient interactive elements\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Add appropriate interactive elements for the component purpose.\",\n evalInstruction: `Evaluate INTERACTIVITY: Does this component have sufficient interactive elements?\n\nConsider: forms need submit buttons, lists need selection, editable content needs save/cancel.\nContract actions (if present): every useAction hook should be triggered by a visible UI element.\n\nOnly list MISSING interactive elements. Use 'fail' only for issues blocking core purpose.`,\n },\n {\n id: \"accessibility\",\n name: \"Accessible markup\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Add labels on form inputs, alt text on images, semantic HTML.\",\n evalInstruction: `Evaluate ACCESSIBILITY: missing labels, alt text, semantic HTML, keyboard support.\n\nggui primitives bake in their own ARIA — see \"Primitive Accessibility\" in the Design System context above. NEVER flag a ggui primitive (Input/Select/TextArea, RadioGroup, Checkbox, Toggle, Progress, Slider, Spinner, Skeleton, Tabs, Accordion, Alert, Toast, Tooltip, Clickable, Icon) for a missing role / aria-* / label / keyboard handler — it is already there and not visible in the source you are reading.\n\nFlag ONLY real gaps: a raw div/span used as an interactive control; an image with no alt text; an Input/Select/TextArea with no \\`label\\` prop; an icon-only Button with no aria-label; live/streaming data not wrapped in an aria-live region; inverted heading hierarchy.\n\nOnly list MISSING accessibility features. Use 'fail' only if it blocks delivery.`,\n },\n {\n id: \"layout\",\n name: \"Clean layout\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use proper spacing and visual grouping.\",\n evalInstruction: `Evaluate LAYOUT: Check spacing, alignment, visual grouping, and composition.\n\nOnly list ACTUAL layout problems. Use 'fail' only for fundamentally broken layouts.`,\n },\n {\n id: \"loading\",\n name: \"Loading/empty/error states\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Handle async data, empty collections, and error cases.\",\n evalInstruction: `Evaluate LOADING/EMPTY/ERROR STATES: Does the component handle async data and edge cases?\n\nContract-specific: useStream should handle pre-data state. clientCapabilities hooks may return undefined / permission-denied — defensive guards expected before threading values into JSX.\nProps-only components (no async, no streams, no client capabilities) do NOT need loading states — return pass.\n\nOnly list MISSING states.`,\n },\n {\n id: \"visual\",\n name: \"Design system consistency\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use design system tokens consistently.\",\n evalInstruction: `Evaluate VISUAL CONSISTENCY: Is the component using the design system correctly?\n\nFlag: hardcoded colors instead of CSS variables, numeric or raw-CSS-length spacing instead of the t-shirt scale, style objects bypassing design system.\nA t-shirt-scale spacing name (gap=\"md\", padding=\"lg\") IS correct token usage — never flag it.\nIntentional custom colors (status indicators) are acceptable when no semantic token fits.\n\nOnly list ACTUAL violations. Use 'fail' only for pervasive violations.`,\n },\n] as const;\n\n/** Get all criteria for a specific priority level */\nexport function getCriteriaByPriority(priority: Priority): EvalCriterion[] {\n return CRITERIA.filter((c) => c.priority === priority);\n}\n\n/** Get a specific criterion by ID */\nexport function getCriterionById(id: string): EvalCriterion | undefined {\n return CRITERIA.find((c) => c.id === id);\n}\n\n/** Get all LLM-evaluated criteria (tier 1 + 2) */\nexport function getLLMCriteria(): EvalCriterion[] {\n return CRITERIA.filter((c) => c.tier > 0);\n}\n\n/**\n * Build the coding agent's criteria summary from the single source of truth.\n * Grouped by priority for the P0→P1→P2 hierarchy.\n */\nexport function buildCodingCriteriaSummary(): string {\n const lines: string[] = [\"## Priority (P0 first, then P1, then P2)\", \"\"];\n\n for (const priority of [\"P0\", \"P1\", \"P2\"] as Priority[]) {\n const label =\n priority === \"P0\"\n ? \"Must (compile + complete)\"\n : priority === \"P1\"\n ? \"Should (safety)\"\n : \"Nice (quality)\";\n const criteria = getCriteriaByPriority(priority);\n lines.push(`**${priority} — ${label}:**`);\n for (const c of criteria) {\n lines.push(`- ${c.codingGuidance}`);\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n","// packages/ui-gen/src/adapters/claude/client.ts\n//\n// SINGLE SOURCE OF TRUTH for Anthropic SDK construction.\n//\n// The BYOK resolver writes the raw credential string into\n// `process.env.ANTHROPIC_API_KEY`, which the Anthropic SDK auto-reads as\n// `x-api-key`. Adapters MUST go through `createAnthropicClient` (no\n// inline `new Anthropic(...)`) so future header / baseURL tweaks land\n// in one place.\n\nimport Anthropic from '@anthropic-ai/sdk';\n\n/**\n * Construct an Anthropic SDK client from a raw API key string.\n *\n * - `string` → standard `apiKey` path (sends `x-api-key`).\n * - `undefined` → still construct a client; SDK auto-reads\n * `process.env.ANTHROPIC_API_KEY` or throws on first call.\n *\n * **SINGLE SOURCE OF TRUTH for Anthropic client construction.** Every\n * adapter that constructs an Anthropic client MUST go through this\n * helper — no inline `new Anthropic(...)` allowed in adapter code.\n */\nexport function createAnthropicClient(\n rawKey: string | undefined,\n): Anthropic {\n if (rawKey === undefined) {\n return new Anthropic({\n baseURL: 'https://api.anthropic.com',\n });\n }\n return new Anthropic({\n apiKey: rawKey,\n baseURL: 'https://api.anthropic.com',\n });\n}\n","// packages/ui-gen/src/adapters/provider-router.ts\n//\n// Provider router for multi-provider BYOK support. Determines how to\n// route LLM requests based on the typed `LlmRoute` discriminator and\n// API-key availability.\n//\n// The previous `getUpstreamModelId` strip + `UPSTREAM_MAP` are gone:\n// the typed `LlmRoute` (slice #43) guarantees `route.model` is\n// wire-canonical at construction time, so there is no LiteLLM prefix\n// to strip at this boundary. `getBedrockModelId` stays — the\n// \"anthropic route + bedrock IAM\" mixed-mode escape hatch (cloud-pod\n// legacy) still needs the wire-canonical anthropic id → cross-region\n// profile id upcast.\n\nimport type { LlmRoute } from '@ggui-ai/protocol';\n\n/**\n * Map a wire-canonical Anthropic model id (or already-bedrock id) to\n * the AWS Bedrock cross-region inference profile id. Used by the\n * mixed-mode `anthropic` route + bedrock-IAM fallback path in\n * {@link resolveRoute} (cloud-pod legacy) and the analogous branch in\n * `harness/llm-router.ts::AnthropicAgent.resolveModel`.\n *\n * Operators picking the bedrock route explicitly (slice #43 Phase 4)\n * pass the cross-region id directly — this helper is purely the\n * fallback escape hatch.\n */\nexport function getBedrockModelId(model: string): string {\n const BEDROCK_MAP: Record<string, string> = {\n 'anthropic/claude-haiku-4-5': 'us.anthropic.claude-haiku-4-5-20251001-v1:0',\n 'anthropic/claude-sonnet-4-6': 'us.anthropic.claude-sonnet-4-6',\n 'anthropic/claude-opus-4-6': 'us.anthropic.claude-opus-4-6-v1:0',\n };\n // Normalize the Bedrock dot-form opt-in (e.g. `anthropic.claude-haiku-4-5`,\n // produced when cloud-pod's `resolvePoolRoute` strips a `bedrock/` opt-in\n // prefix) to the Anthropic slash form. Both spellings should resolve to\n // the same cross-region inference profile id — without this, the dot\n // form would skip the BEDROCK_MAP hit, fall through the `^anthropic\\/`\n // strip (which is a no-op for the dot form), and re-prepend\n // `us.anthropic.` to produce a double-`anthropic.` id that Bedrock\n // rejects with 400 (cloud e2e regression 2026-05-25, bedrock-iam.spec).\n const normalized = model.replace(/^anthropic\\./, 'anthropic/');\n if (BEDROCK_MAP[normalized]) return BEDROCK_MAP[normalized];\n if (normalized.startsWith('us.anthropic.') || normalized.startsWith('arn:')) {\n return normalized;\n }\n const stripped = normalized.replace(/^anthropic\\//, '');\n return `us.anthropic.${stripped}`;\n}\n\nexport interface RoutingDecision {\n /**\n * Upstream model id the dispatch adapter will pass to the provider\n * SDK. For most routes this is `route.model` verbatim — the typed\n * `LlmRoute` (slice #43) carries the wire-canonical id, so no\n * transformation is needed. The exception is the mixed-mode\n * \"anthropic route + bedrock IAM fallback\" branch, which upcasts\n * the wire-canonical Anthropic id to the corresponding Bedrock\n * cross-region inference profile id via {@link getBedrockModelId}.\n */\n readonly model: string;\n /**\n * Env-var mutations the caller MUST apply to `process.env` before\n * invoking the dispatch adapter. `undefined` values are deletions\n * (the wrong provider's stale key must be cleared so the dispatch\n * doesn't accidentally fire against it). See {@link applyRouteToEnv}.\n */\n readonly env: Record<string, string | undefined>;\n}\n\nexport interface RoutingInput {\n /** Typed `(provider, model)` route — model is wire-canonical. */\n readonly route: LlmRoute;\n /** API key for byok-capable providers; ignored for `bedrock`. */\n readonly apiKey?: string;\n /** Current env snapshot — feeds the anthropic mixed-mode branch. */\n readonly env: Record<string, string | undefined>;\n}\n\n/**\n * Sibling-provider env vars that MUST be cleared for every non-self\n * route. Centralized so the per-provider branches below stay\n * symmetric — a single missing entry would let a stale key leak into\n * the next render (e.g. an OpenRouter route inheriting a previous\n * call's `OPENAI_API_KEY` and firing the wrong adapter).\n */\nconst SIBLING_ENV_KEYS = [\n 'ANTHROPIC_API_KEY',\n 'ANTHROPIC_BASE_URL',\n 'CLAUDE_CODE_USE_BEDROCK',\n 'OPENAI_API_KEY',\n 'GEMINI_API_KEY',\n 'GOOGLE_API_KEY',\n 'OPENROUTER_API_KEY',\n] as const;\n\nfunction clearSiblings(\n keep: ReadonlySet<(typeof SIBLING_ENV_KEYS)[number]>,\n): Record<string, undefined> {\n const out: Record<string, undefined> = {};\n for (const k of SIBLING_ENV_KEYS) {\n if (!keep.has(k)) out[k] = undefined;\n }\n return out;\n}\n\n/**\n * Determine the routing strategy for a generation request. Pure\n * function over `(route, apiKey, env)` — returns the upstream model\n * id (usually `route.model` verbatim) and the env-var mutations the\n * caller must apply before dispatch.\n *\n * Dispatch is on `route.provider`:\n *\n * - `openai` — direct OpenAI API (sets `OPENAI_API_KEY`).\n * - `google` — direct Gemini API (sets `GEMINI_API_KEY` + `GOOGLE_API_KEY`).\n * - `openrouter` — direct OpenRouter API (sets `OPENROUTER_API_KEY`).\n * - `bedrock` — AWS Bedrock via host IAM (sets `CLAUDE_CODE_USE_BEDROCK=1`,\n * no API key in flight; model passes verbatim).\n * - `anthropic` — three-way fallback chain:\n * 1. With `apiKey` → direct Anthropic API.\n * 2. Without `apiKey` AND explicit `env.CLAUDE_CODE_USE_BEDROCK === '1'`\n * (or no `env.ANTHROPIC_API_KEY`) → mixed-mode bedrock fallback\n * (model upcast to cross-region profile via `getBedrockModelId`).\n * Cloud-pod legacy escape hatch; the OSS Phase 4 strict-fail\n * prevents end-users from reaching this branch implicitly.\n * 3. Otherwise → direct Anthropic API with whatever\n * `ANTHROPIC_API_KEY` is already in `env`.\n *\n * For non-Anthropic non-Bedrock providers, an `apiKey` is REQUIRED —\n * there's no IAM-style fallback. Callers that don't have a key MUST\n * surface a \"no API key\" envelope to their agent before reaching the\n * dispatch path; throwing here is defense in depth.\n */\nexport function resolveRoute(input: RoutingInput): RoutingDecision {\n const { route, apiKey, env } = input;\n\n switch (route.provider) {\n case 'openai': {\n if (!apiKey) {\n throw new Error(\n `openai:${route.model} requires an API key. ` +\n `Set 'apiKey' on the RoutingInput (BYOK) or supply your key ` +\n `via your dispatch layer.`,\n );\n }\n return {\n model: route.model,\n env: {\n OPENAI_API_KEY: apiKey,\n ...clearSiblings(new Set(['OPENAI_API_KEY'])),\n },\n };\n }\n\n case 'google': {\n if (!apiKey) {\n throw new Error(\n `google:${route.model} requires an API key. ` +\n `Set 'apiKey' on the RoutingInput (BYOK) or supply your key ` +\n `via your dispatch layer.`,\n );\n }\n return {\n model: route.model,\n env: {\n // `harness/llm-router.ts`'s GoogleAgent reads `GEMINI_API_KEY\n // || GOOGLE_API_KEY`. Set both so either slot wins;\n // unsetting one would leave a stale value behind.\n GEMINI_API_KEY: apiKey,\n GOOGLE_API_KEY: apiKey,\n ...clearSiblings(new Set(['GEMINI_API_KEY', 'GOOGLE_API_KEY'])),\n },\n };\n }\n\n case 'openrouter': {\n if (!apiKey) {\n throw new Error(\n `openrouter:${route.model} requires an API key. ` +\n `Set 'apiKey' on the RoutingInput (BYOK) or supply your key ` +\n `via your dispatch layer.`,\n );\n }\n return {\n model: route.model,\n env: {\n OPENROUTER_API_KEY: apiKey,\n ...clearSiblings(new Set(['OPENROUTER_API_KEY'])),\n },\n };\n }\n\n case 'bedrock': {\n // IAM auth — no apiKey in flight. The model is already a\n // cross-region profile id (e.g.\n // `us.anthropic.claude-haiku-4-5-20251001-v1:0`); pass it\n // verbatim.\n return {\n model: route.model,\n env: {\n CLAUDE_CODE_USE_BEDROCK: '1',\n ...clearSiblings(new Set(['CLAUDE_CODE_USE_BEDROCK'])),\n },\n };\n }\n\n case 'anthropic': {\n if (apiKey) {\n return {\n model: route.model,\n env: {\n ANTHROPIC_API_KEY: apiKey,\n ...clearSiblings(new Set(['ANTHROPIC_API_KEY'])),\n },\n };\n }\n // Mixed-mode legacy: anthropic route + bedrock IAM fallback.\n // Cloud-pod escape hatch when `ANTHROPIC_API_KEY` isn't seeded.\n const explicitBedrock = env.CLAUDE_CODE_USE_BEDROCK === '1';\n const noApiKey = !env.ANTHROPIC_API_KEY;\n if (explicitBedrock || noApiKey) {\n return {\n model: getBedrockModelId(route.model),\n env: {\n CLAUDE_CODE_USE_BEDROCK: '1',\n ...clearSiblings(new Set(['CLAUDE_CODE_USE_BEDROCK'])),\n },\n };\n }\n // Anthropic via process.env.ANTHROPIC_API_KEY (no in-call key).\n return {\n model: route.model,\n env: clearSiblings(new Set(['ANTHROPIC_API_KEY'])),\n };\n }\n }\n}\n\n/**\n * Apply routing decision to an environment object.\n */\nexport function applyRouteToEnv(\n baseEnv: Record<string, string>,\n route: RoutingDecision,\n): Record<string, string> {\n const result = { ...baseEnv };\n for (const [key, value] of Object.entries(route.env)) {\n if (value === undefined) {\n delete result[key];\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n","// packages/ui-gen/src/adapters/tool-bridge.ts\n//\n// Bridges between SDK tool wire formats and ggui's JSON types:\n// Zod → JSON Schema for tool declarations, and validated narrowing of\n// decoded tool-call arguments to `JsonObject`.\n\nimport { z } from 'zod';\nimport type { JsonObject, JsonValue } from '@ggui-ai/protocol';\n\n/**\n * Convert a Zod object schema to JSON Schema.\n * Uses Zod v4's built-in toJSONSchema() function.\n */\nexport function zodToJsonSchema(schema: z.ZodType): JsonObject {\n return z.toJSONSchema(schema) as JsonObject;\n}\n\n/**\n * Validate that a decoded tool-call `arguments` object is plain JSON data\n * and narrow it to {@link JsonObject}. Provider SDKs type tool-call\n * arguments as `{ [key: string]: unknown }`; values decoded from a JSON\n * wire payload are JSON by construction, so a failure here means the SDK\n * handed us something that never came from JSON — a bug worth surfacing,\n * not erasing with a cast.\n */\nexport function toolArgsToJsonObject(args: { [key: string]: unknown }): JsonObject {\n const out: JsonObject = {};\n for (const [key, value] of Object.entries(args)) {\n // `JsonObject` keys admit `undefined` (TS optional properties);\n // JSON.stringify omits them, so pass-through is JSON-safe.\n out[key] = value === undefined ? undefined : toJsonValue(value, key);\n }\n return out;\n}\n\nfunction toJsonValue(value: unknown, path: string): JsonValue {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((item, i) => toJsonValue(item, `${path}[${i}]`));\n }\n if (typeof value === 'object') {\n const out: JsonObject = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = entry === undefined ? undefined : toJsonValue(entry, `${path}.${key}`);\n }\n return out;\n }\n throw new Error(\n `Tool-call arguments contain a non-JSON value at '${path}' (${typeof value})`,\n );\n}\n","/**\n * Live LLM trace sink — devtools introspection of every LLM call the\n * generation harness makes.\n *\n * **Distinct from {@link TelemetrySink} and {@link AuditSink}.**\n * - **Telemetry** (mcp-server-core) = ops signals (`pair.completed`,\n * `render.duration_ms`). Sink may be lossy and drops on backpressure.\n * Attributes are flat scalars (`string | number | boolean`).\n * - **Audit** (mcp-server-core) = compliance log of privileged\n * mutations. Durable, async, may throw.\n * - **LLM trace** (this) = devtools-only, hostable in-memory ring\n * buffer of every LLM call's full payload (system prompt, user\n * prompt, tool defs, completion, token counts, cache hits, error).\n * Lossy by default. A hosted closed runtime may swap in a durable\n * sink for internal debugging; OSS ships an in-memory sink the\n * `/devtools/llm-trace` page reads.\n *\n * **Why module-level registry instead of constructor injection.** The\n * harness constructs LLM agents on every generation via\n * {@link createAgent}. Threading a sink through every call site\n * (createAgent → run-coding-turn → llm-evaluator → file-agent → …)\n * touches ~5 packages for a devtools-only surface. The OSS ggui server\n * is a single process per CLI invocation — global state has no\n * confusion-cost there. A hosted closed runtime isolates per request\n * via process-pool, so a global per-pool is also safe. If we ever\n * multi-tenant inside one process we'll thread it then.\n *\n * **Default = no sink.** When unset, the router emits nothing and\n * spends no CPU formatting events. Passing `null` removes a previously\n * registered sink.\n */\nimport type { LLMToolDef } from '../llm.js';\n\n/** Provider tag that produced the call. Mirrors {@link AgentConfig.provider}. */\nexport type LlmTraceProvider = 'anthropic' | 'openai' | 'google' | 'openrouter';\n\n/** Which `LLMAgent` method initiated the call. */\nexport type LlmTraceKind =\n | 'callText'\n | 'callTools'\n | 'callWithTools'\n | 'callStructured';\n\n/**\n * One LLM call. Emitted **after** the call completes (success or error)\n * — single event, not start/end split. Devtools UI is timeline-friendly\n * because each event carries `at` (start) + `endedAt` (end).\n */\nexport interface LlmTraceEvent {\n /** Random per-event ID. */\n readonly id: string;\n /** Epoch ms when the call was issued. */\n readonly at: number;\n /** Epoch ms when the call completed (success or error). */\n readonly endedAt: number;\n /** `endedAt - at` — convenience. */\n readonly durationMs: number;\n readonly provider: LlmTraceProvider;\n readonly model: string;\n readonly kind: LlmTraceKind;\n readonly systemPrompt?: string;\n readonly userPrompt?: string;\n /**\n * Tool defs sent on the call (if any). Stripped to `name + description`\n * — full JSON schema would balloon the trace and is rarely useful in\n * the operator UI.\n */\n readonly tools?: ReadonlyArray<{\n readonly name: string;\n readonly description: string;\n }>;\n /** Set on successful completion. */\n readonly result?: {\n readonly inputTokens: number;\n readonly outputTokens: number;\n /** Anthropic only. Bytes counted toward the cache write. */\n readonly cacheCreated?: number;\n /** Anthropic only. Bytes served from cache (90% discounted). */\n readonly cacheRead?: number;\n /** Set when the call returned text content. */\n readonly text?: string;\n /** Set when the call returned tool_use blocks. */\n readonly toolCalls?: ReadonlyArray<{\n readonly name: string;\n readonly input: unknown;\n }>;\n /** Set for `callWithTools` — number of agentic turns consumed. */\n readonly turnsUsed?: number;\n };\n /** Set on failure. `result` is undefined. */\n readonly error?: { readonly message: string };\n}\n\n/**\n * Sink that receives one event per LLM call. Implementations MUST be\n * sync + non-throwing — the harness fires events on the hot path and\n * cannot tolerate backpressure or rejected promises. Buffer + drop or\n * fan out to a queue inside the implementation.\n */\nexport interface LlmTraceSink {\n emit(event: LlmTraceEvent): void;\n}\n\nlet activeSink: LlmTraceSink | null = null;\n\n/**\n * Register the active sink. Pass `null` to remove. Subsequent\n * {@link emitLlmTraceEvent} calls dispatch to this sink.\n */\nexport function setLlmTraceSink(sink: LlmTraceSink | null): void {\n activeSink = sink;\n}\n\n/** Read the active sink. Mostly for tests. */\nexport function getLlmTraceSink(): LlmTraceSink | null {\n return activeSink;\n}\n\n/**\n * Internal — used by `LLMAgent` adapters. No-op when no sink is\n * registered. Swallows sink-thrown errors (a broken devtools sink must\n * not break generation).\n */\nexport function emitLlmTraceEvent(event: LlmTraceEvent): void {\n const sink = activeSink;\n if (!sink) return;\n try {\n sink.emit(event);\n } catch {\n // Devtools sink is allowed to be buggy — generation must not die.\n }\n}\n\n/** Strip `LLMToolDef[]` to the trace-friendly subset. */\nexport function summarizeTools(\n tools: ReadonlyArray<LLMToolDef>,\n): ReadonlyArray<{ readonly name: string; readonly description: string }> {\n return tools.map((t) => ({ name: t.name, description: t.description }));\n}\n\n/**\n * Crockford-style random ID. Crypto.randomUUID() would do, but we want\n * to keep this dep-free for non-Node runtimes the harness might run in.\n */\nexport function newLlmTraceId(): string {\n return (\n Date.now().toString(36) +\n Math.random().toString(36).slice(2, 10)\n );\n}\n","// packages/ui-gen/src/harness/llm-router.ts\n//\n// Provider-agnostic LLM routing via LLMAgent class hierarchy.\n// Each provider implements its own SDK interface with proper types.\n//\n// Key methods:\n// callText() — plain text response\n// callStructured() — JSON structured output (for coding agent)\n// callWithTools() — multi-turn agentic loop\n\nimport type Anthropic from '@anthropic-ai/sdk';\nimport type {\n TextBlock,\n TextBlockParam,\n ToolUseBlock,\n} from '@anthropic-ai/sdk/resources/messages';\nimport type OpenAI from 'openai';\nimport type {\n Response as OpenAIResponse,\n ResponseFunctionToolCall,\n} from 'openai/resources/responses/responses';\nimport type {\n GoogleGenAI,\n Interactions,\n} from '@google/genai';\nimport type { JsonObject } from '@ggui-ai/protocol';\nimport type { LLMToolDef } from '../llm.js';\nimport type { AnthropicBedrock } from '@anthropic-ai/bedrock-sdk';\nimport { createAnthropicClient } from '../adapters/claude/client.js';\nimport { getBedrockModelId } from '../adapters/provider-router.js';\nimport { toolArgsToJsonObject } from '../adapters/tool-bridge.js';\nimport {\n emitLlmTraceEvent,\n newLlmTraceId,\n summarizeTools,\n} from './llm-trace-sink.js';\n\n// `LLMToolDef` lives in `@ggui-ai/ui-gen/llm`. This file re-exports it\n// so `../harness/llm-router.js` importers (evaluator.ts,\n// llm-evaluator.ts, run-coding-turn.ts) can reach it here.\nexport type { LLMToolDef };\n\n// =============================================================================\n// Shared Types\n// =============================================================================\n\nexport interface AgentConfig {\n provider: 'anthropic' | 'openai' | 'google' | 'openrouter';\n model: string;\n /**\n * Sampling temperature. When defined it is threaded into the provider\n * request; when undefined the provider default is used (unchanged\n * behavior for all existing callers).\n */\n temperature?: number;\n}\n\nexport interface LLMResponse {\n text: string;\n inputTokens: number;\n outputTokens: number;\n}\n\nexport interface LLMTool {\n name: string;\n description: string;\n parameters: JsonObject;\n handler: (\n args: JsonObject,\n ) => Promise<{ content: Array<{ text: string }>; isError?: boolean }>;\n}\n\nexport interface LLMWithToolsResponse {\n text: string;\n inputTokens: number;\n outputTokens: number;\n turnsUsed: number;\n}\n\nexport interface LLMToolCall {\n /** Provider-specific call ID (for sendToolResult) */\n id?: string;\n name: string;\n input: JsonObject;\n}\n\nexport interface LLMToolCallResponse {\n toolCalls: LLMToolCall[];\n inputTokens: number;\n outputTokens: number;\n /**\n * Tokens read from / written to the prompt cache, when the provider\n * reports them. Optional because not every provider exposes\n * prompt-cache accounting — absent means \"unreported\", never zero.\n */\n cacheReadTokens?: number;\n cacheCreationTokens?: number;\n}\n\n// Backward compat alias\nexport type LLMSingleTurnResponse = LLMToolCallResponse;\n\n/** Result of executing a tool — passed to sendToolResult to close the API contract. */\nexport interface LLMToolResult {\n /** Tool call ID from the response (for providers that need it) */\n callId?: string;\n /** Tool name */\n name: string;\n /** Text result of executing the tool */\n result: string;\n /** Whether the tool execution failed */\n isError?: boolean;\n}\n\n// =============================================================================\n// Schema helpers\n// =============================================================================\n\n/**\n * Add `additionalProperties: false` to all object schemas and ensure all\n * properties are in `required`. Required by OpenAI strict mode.\n * Recursively processes nested objects and array items.\n */\nfunction addStrictSchemaConstraints(schema: JsonObject): JsonObject {\n const result = { ...schema };\n\n if (result.type === 'object' && result.properties) {\n result.additionalProperties = false;\n // All properties must be required for strict mode\n const propKeys = Object.keys(result.properties as JsonObject);\n if (!result.required || (result.required as string[]).length < propKeys.length) {\n result.required = propKeys;\n }\n // Recurse into nested properties\n const props = { ...(result.properties as JsonObject) };\n for (const [key, value] of Object.entries(props)) {\n if (typeof value === 'object' && value !== null) {\n props[key] = addStrictSchemaConstraints(value as JsonObject);\n }\n }\n result.properties = props;\n }\n\n // Recurse into array items\n if (result.type === 'array' && result.items && typeof result.items === 'object') {\n result.items = addStrictSchemaConstraints(result.items as JsonObject);\n }\n\n return result;\n}\n\n// =============================================================================\n// Error helpers\n// =============================================================================\n\n/** One-line error summary for logging — includes HTTP status, error code, and response body excerpt. */\nfunction errorSummary(e: unknown): string {\n if (!(e instanceof Error)) return String(e);\n const status = 'status' in e ? ` (${(e as { status: number }).status})` : '';\n const code = 'code' in e ? ` [${(e as { code: string }).code}]` : '';\n // Extract error body if available (Google/OpenAI SDKs attach it)\n let body = '';\n if ('error' in e && typeof (e as { error: unknown }).error === 'object') {\n const errObj = (e as { error: { message?: string } }).error;\n if (errObj?.message) body = ` body=\"${errObj.message.slice(0, 200)}\"`;\n }\n return `${e.constructor.name}${status}${code}: ${e.message.slice(0, 120)}${body}`;\n}\n\n// =============================================================================\n// LLMAgent — abstract base\n// =============================================================================\n\nexport abstract class LLMAgent {\n abstract readonly provider: AgentConfig['provider'];\n private client: unknown = null;\n\n // ── Session state for server-side chaining ──────────────\n // Google: previous_interaction_id, OpenAI: previous_response_id\n // Enables turn 2+ to skip re-sending system prompt + history.\n // Call resetSession() between independent generation runs.\n protected lastSessionId: string | undefined;\n\n\n protected abstract resolveModel(model: string): string;\n protected abstract createClient(): Promise<unknown>;\n\n protected async getClient<T>(): Promise<T> {\n if (!this.client) {\n this.client = await this.createClient();\n }\n return this.client as T;\n }\n\n /** Text-only call — no tools */\n abstract callText(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n temperature?: number,\n ): Promise<LLMResponse>;\n\n /**\n * Single-turn function calling — returns tool calls without executing them.\n * Each provider uses its native function/tool calling:\n * - Anthropic: tool_use blocks\n * - OpenAI: function_call output items\n * - Google: functionCall parts\n * SDK handles JSON escaping — safe for code, diffs, and other content.\n */\n abstract callTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMToolDef[],\n toolChoice?: 'required' | 'auto',\n /**\n * Optional scoped fallback tools. If the primary tools fail with a\n * transport-class error (e.g. `malformed_tool_call` on Gemini after\n * retry exhaustion), the provider may retry once with these narrower\n * tools before throwing. Universal signal — not provider-gated.\n */\n scopedTools?: LLMToolDef[],\n ): Promise<LLMToolCallResponse>;\n\n /** Multi-turn agentic loop — executes tools internally */\n abstract callWithTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number,\n ): Promise<LLMWithToolsResponse>;\n\n /**\n * Pre-warm cache for repeated callTools() calls with the same system prompt + tools.\n * Override in providers that support server-side context caching (e.g., Google).\n * No-op by default (Anthropic/OpenAI handle caching automatically per-request).\n */\n async warmCache(\n _model: string,\n _systemPrompt: string,\n _tools: LLMToolDef[],\n _toolChoice?: 'required' | 'auto',\n ): Promise<void> {}\n\n /** Cleanup any cached resources. Call after generation completes. No-op by default. */\n async cleanup(): Promise<void> {}\n\n /** Reset session state between independent generation runs. */\n resetSession(): void {\n this.lastSessionId = undefined;\n }\n\n /**\n * Send tool execution results back to the provider to close the API contract.\n * Call this after executing tools from callTools() and before the next callTools().\n *\n * For providers with server-side state (Google, OpenAI), this sends the\n * function results so the next callTools() can chain properly.\n * For stateless providers (Anthropic), this is a no-op.\n *\n * Override in providers that need it.\n */\n async sendToolResult(_results: LLMToolResult[]): Promise<void> {\n // No-op by default — Anthropic doesn't need this (stateless + auto prompt cache)\n }\n\n /**\n * Execute an API call. No retry — if it fails, it fails.\n * Logs the error with provider context and re-throws.\n */\n protected async apiCall<T>(fn: () => Promise<T>): Promise<T> {\n const start = Date.now();\n try {\n return await fn();\n } catch (e: unknown) {\n const ms = Date.now() - start;\n console.error(`[${this.provider}] API error after ${ms}ms: ${errorSummary(e)}`);\n throw e;\n }\n }\n\n}\n\n// =============================================================================\n// AnthropicAgent\n// =============================================================================\n\nexport class AnthropicAgent extends LLMAgent {\n readonly provider = 'anthropic' as const;\n\n protected resolveModel(model: string): string {\n // Bedrock IAM path — the upstream model id must be the cross-region\n // inference-profile form (`us.anthropic.*`), not the bare API id.\n if (process.env.CLAUDE_CODE_USE_BEDROCK === '1') {\n return getBedrockModelId(model);\n }\n return model.startsWith('anthropic/')\n ? model.slice('anthropic/'.length)\n : model;\n }\n\n protected async createClient(): Promise<Anthropic | AnthropicBedrock> {\n // Bedrock IAM path: `resolveRoute` (provider-router) sets\n // CLAUDE_CODE_USE_BEDROCK=1 and clears ANTHROPIC_API_KEY for the\n // pool-funded cloud pod. Auth is the pod's IRSA role — no API key.\n // `AnthropicBedrock` is wire-compatible with `Anthropic` for the\n // `.messages` API this agent uses.\n if (process.env.CLAUDE_CODE_USE_BEDROCK === '1') {\n const { AnthropicBedrock } = await import('@anthropic-ai/bedrock-sdk');\n return new AnthropicBedrock({\n awsRegion:\n process.env.AWS_REGION ??\n process.env.AWS_DEFAULT_REGION ??\n 'us-east-1',\n });\n }\n // SDK construction lives in `adapters/claude/client.ts`. The BYOK\n // resolver writes the raw key into `process.env.ANTHROPIC_API_KEY`\n // before this runs (see `applyRouteToEnv` in provider-router).\n return createAnthropicClient(process.env.ANTHROPIC_API_KEY);\n }\n\n async callText(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n temperature?: number,\n ): Promise<LLMResponse> {\n const client = await this.getClient<Anthropic>();\n const traceId = newLlmTraceId();\n const startedAt = Date.now();\n const resolvedModel = this.resolveModel(model);\n\n // Use prompt caching beta API (90% discount on cached reads)\n const system: TextBlockParam[] = [\n {\n type: 'text',\n text: systemPrompt,\n cache_control: { type: 'ephemeral' },\n },\n ];\n\n try {\n const response = await this.apiCall(() =>\n client.messages.create({\n model: resolvedModel,\n max_tokens: maxTokens ?? 4096,\n system,\n messages: [{ role: 'user', content: userPrompt }],\n ...(temperature !== undefined && { temperature }),\n }),\n );\n\n const usage = response.usage as typeof response.usage & {\n cache_creation_input_tokens?: number | null;\n cache_read_input_tokens?: number | null;\n };\n const cacheCreated = usage.cache_creation_input_tokens ?? 0;\n const cacheRead = usage.cache_read_input_tokens ?? 0;\n if (cacheCreated || cacheRead) {\n console.log(`[anthropic] callText cache: created=${cacheCreated} read=${cacheRead} input=${usage.input_tokens} output=${usage.output_tokens}`);\n }\n\n const text = response.content\n .filter((block): block is TextBlock => block.type === 'text')\n .map((block) => block.text)\n .join('');\n\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callText',\n systemPrompt,\n userPrompt,\n result: {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n cacheCreated,\n cacheRead,\n text,\n },\n });\n\n return {\n text,\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n };\n } catch (e) {\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callText',\n systemPrompt,\n userPrompt,\n error: { message: e instanceof Error ? e.message : String(e) },\n });\n throw e;\n }\n }\n\n async callTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMToolDef[],\n toolChoice: 'required' | 'auto' = 'required',\n _scopedTools?: LLMToolDef[],\n ): Promise<LLMToolCallResponse> {\n const client = await this.getClient<Anthropic>();\n const traceId = newLlmTraceId();\n const startedAt = Date.now();\n const resolvedModel = this.resolveModel(model);\n\n // Cache system prompt + tools via prompt caching beta (90% discount)\n const system: TextBlockParam[] = [\n {\n type: 'text',\n text: systemPrompt,\n cache_control: { type: 'ephemeral' },\n },\n ];\n\n const cachedTools: Anthropic.Tool[] = tools.map((t, i) => ({\n name: t.name,\n description: t.description,\n input_schema: t.parameters as Anthropic.Tool.InputSchema,\n // Mark last tool to cache the entire tool list\n ...(i === tools.length - 1\n ? { cache_control: { type: 'ephemeral' as const } }\n : {}),\n }));\n\n try {\n // `max_tokens >= 21_334` mandates streaming on the\n // @anthropic-ai/sdk >=0.40 path (the API rejects non-streamed\n // long-form generation with `Streaming is required for\n // operations that may take longer than 10 minutes`). We still\n // want the final-message shape downstream, so use the stream\n // helper's `finalMessage()` which folds the events back to the\n // same `Message` Type the non-streaming path returned.\n const response = await this.apiCall(() =>\n client.messages\n .stream({\n model: resolvedModel,\n max_tokens: 32768,\n system,\n messages: [{ role: 'user', content: userPrompt }],\n tools: cachedTools,\n tool_choice: { type: toolChoice === 'required' ? 'any' : 'auto' },\n })\n .finalMessage(),\n );\n\n const usage = response.usage as typeof response.usage & {\n cache_creation_input_tokens?: number | null;\n cache_read_input_tokens?: number | null;\n };\n const cacheCreated = usage.cache_creation_input_tokens ?? 0;\n const cacheRead = usage.cache_read_input_tokens ?? 0;\n if (cacheCreated || cacheRead) {\n console.log(`[anthropic] callTools cache: created=${cacheCreated} read=${cacheRead} input=${usage.input_tokens} output=${usage.output_tokens}`);\n }\n\n const toolUses = response.content.filter(\n (block): block is ToolUseBlock => block.type === 'tool_use',\n );\n\n const toolCalls = toolUses.map((tu) => ({\n id: tu.id,\n name: tu.name,\n input: (tu.input ?? {}) as JsonObject,\n }));\n\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callTools',\n systemPrompt,\n userPrompt,\n tools: summarizeTools(tools),\n result: {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n cacheCreated,\n cacheRead,\n toolCalls: toolCalls.map((c) => ({ name: c.name, input: c.input })),\n },\n });\n\n return {\n toolCalls,\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n cacheReadTokens: cacheRead,\n cacheCreationTokens: cacheCreated,\n };\n } catch (e) {\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callTools',\n systemPrompt,\n userPrompt,\n tools: summarizeTools(tools),\n error: { message: e instanceof Error ? e.message : String(e) },\n });\n throw e;\n }\n }\n\n async callWithTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number,\n ): Promise<LLMWithToolsResponse> {\n const client = await this.getClient<Anthropic>();\n const resolvedModel = this.resolveModel(model);\n const traceId = newLlmTraceId();\n const startedAt = Date.now();\n\n const anthropicTools: Anthropic.Tool[] = tools.map((t) => ({\n name: t.name,\n description: t.description,\n input_schema: t.parameters as Anthropic.Tool.InputSchema,\n }));\n\n const messages: Anthropic.MessageParam[] = [\n { role: 'user', content: userPrompt },\n ];\n let totalIn = 0;\n let totalOut = 0;\n let allText = '';\n\n try {\n for (let turn = 0; turn < maxTurns; turn++) {\n // Same streaming requirement as callTools — see comment there.\n const response = await this.apiCall(() =>\n client.messages\n .stream({\n model: resolvedModel,\n max_tokens: 32768,\n system: systemPrompt,\n messages,\n tools: anthropicTools,\n })\n .finalMessage(),\n );\n totalIn += response.usage.input_tokens;\n totalOut += response.usage.output_tokens;\n\n for (const block of response.content) {\n if (block.type === 'text') allText += block.text;\n }\n\n const toolUses = response.content.filter(\n (b): b is ToolUseBlock => b.type === 'tool_use',\n );\n if (toolUses.length === 0) break;\n\n messages.push({ role: 'assistant', content: response.content });\n\n const toolResults: Anthropic.ToolResultBlockParam[] = [];\n for (const tu of toolUses) {\n const tool = tools.find((t) => t.name === tu.name);\n if (!tool) {\n toolResults.push({\n type: 'tool_result',\n tool_use_id: tu.id,\n content: `Tool '${tu.name}' not found`,\n });\n continue;\n }\n const result = await tool.handler(\n (tu.input ?? {}) as JsonObject,\n );\n toolResults.push({\n type: 'tool_result',\n tool_use_id: tu.id,\n content: result.content[0]?.text ?? '',\n });\n }\n messages.push({ role: 'user', content: toolResults });\n }\n\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callWithTools',\n systemPrompt,\n userPrompt,\n tools: tools.map((t) => ({ name: t.name, description: t.description })),\n result: {\n inputTokens: totalIn,\n outputTokens: totalOut,\n text: allText,\n turnsUsed: messages.length,\n },\n });\n\n return {\n text: allText,\n inputTokens: totalIn,\n outputTokens: totalOut,\n turnsUsed: messages.length,\n };\n } catch (e) {\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callWithTools',\n systemPrompt,\n userPrompt,\n tools: tools.map((t) => ({ name: t.name, description: t.description })),\n error: { message: e instanceof Error ? e.message : String(e) },\n });\n throw e;\n }\n }\n}\n\n// =============================================================================\n// OpenAIAgent\n// =============================================================================\n\nexport class OpenAIAgent extends LLMAgent {\n readonly provider = 'openai' as const;\n\n protected resolveModel(model: string): string {\n return model.startsWith('openai/')\n ? model.slice('openai/'.length)\n : model;\n }\n\n protected async createClient(): Promise<OpenAI> {\n const { default: OpenAISDK } = await import('openai');\n return new OpenAISDK({ apiKey: process.env.OPENAI_API_KEY });\n }\n\n async callText(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n temperature?: number,\n ): Promise<LLMResponse> {\n const client = await this.getClient<OpenAI>();\n const response: OpenAIResponse = await this.apiCall(() =>\n client.responses.create({\n model: this.resolveModel(model),\n instructions: systemPrompt,\n input: [{ role: 'user', content: userPrompt }],\n ...(maxTokens && { max_output_tokens: maxTokens }),\n ...(temperature !== undefined && { temperature }),\n }),\n );\n\n let text = '';\n for (const item of response.output) {\n if (item.type === 'message') {\n for (const part of item.content) {\n if (part.type === 'output_text') text += part.text;\n }\n }\n }\n\n return {\n text,\n inputTokens: response.usage?.input_tokens ?? 0,\n outputTokens: response.usage?.output_tokens ?? 0,\n };\n }\n\n async callTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMToolDef[],\n toolChoice: 'required' | 'auto' = 'required',\n _scopedTools?: LLMToolDef[],\n ): Promise<LLMToolCallResponse> {\n const client = await this.getClient<OpenAI>();\n // strict: true enables constrained decoding — guarantees valid JSON matching the schema.\n // Requires additionalProperties: false on all objects and all fields in required.\n const openaiTools = tools.map((t) => ({\n type: 'function' as const,\n name: t.name,\n description: t.description,\n parameters: addStrictSchemaConstraints(t.parameters),\n strict: true,\n }));\n\n // Consume pending tool results — prepend to input for proper contract\n const pending = this.pendingToolResults;\n this.pendingToolResults = [];\n const input = pending.length > 0\n ? [...pending, { role: 'user' as const, content: userPrompt }]\n : [{ role: 'user' as const, content: userPrompt }];\n\n const response: OpenAIResponse = await this.apiCall(() =>\n client.responses.create({\n model: this.resolveModel(model),\n instructions: systemPrompt,\n input,\n tools: openaiTools,\n tool_choice: toolChoice,\n store: true, // Enable response storage + server-side chaining\n ...(this.lastSessionId && { previous_response_id: this.lastSessionId }),\n }),\n );\n\n // Save session ID for chaining subsequent calls\n this.lastSessionId = response.id;\n\n // Log cache utilization\n const usage = response.usage;\n if (usage) {\n // Typed in the SDK as required, but widened to optional here —\n // tolerate responses that omit the breakdown at runtime.\n const cached: { cached_tokens?: number } | undefined =\n usage.input_tokens_details;\n if (cached?.cached_tokens) {\n console.log(`[openai] session ${this.lastSessionId ? 'chained' : 'new'}: ${cached.cached_tokens} cached of ${usage.input_tokens} input`);\n }\n }\n\n const functionCalls = response.output.filter(\n (o): o is ResponseFunctionToolCall => o.type === 'function_call',\n );\n\n return {\n toolCalls: functionCalls.map((fc) => ({\n id: fc.call_id,\n name: fc.name,\n input: JSON.parse(fc.arguments ?? '{}') as JsonObject,\n })),\n inputTokens: response.usage?.input_tokens ?? 0,\n outputTokens: response.usage?.output_tokens ?? 0,\n };\n }\n\n // Pending tool results — stored by sendToolResult, consumed by next callTools\n private pendingToolResults: OpenAI.Responses.ResponseInputItem[] = [];\n\n override async sendToolResult(results: LLMToolResult[]): Promise<void> {\n // Store results locally — they'll be prepended to the next callTools input.\n // No API call here! Saves a round-trip.\n this.pendingToolResults = results.map((r) => ({\n type: 'function_call_output',\n call_id: r.callId ?? '',\n output: r.result,\n }));\n }\n\n async callWithTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number,\n ): Promise<LLMWithToolsResponse> {\n const client = await this.getClient<OpenAI>();\n const resolvedModel = this.resolveModel(model);\n const openaiTools = tools.map((t) => ({\n type: 'function' as const,\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n strict: false,\n }));\n\n let input: OpenAI.Responses.ResponseInputItem[] = [\n { role: 'user', content: userPrompt },\n ];\n let totalIn = 0;\n let totalOut = 0;\n let allText = '';\n\n for (let turn = 0; turn < maxTurns; turn++) {\n const response: OpenAIResponse = await this.apiCall(() =>\n client.responses.create({\n model: resolvedModel,\n instructions: systemPrompt,\n input,\n tools: openaiTools,\n }),\n );\n totalIn += response.usage?.input_tokens ?? 0;\n totalOut += response.usage?.output_tokens ?? 0;\n\n const functionCalls = response.output.filter(\n (o): o is ResponseFunctionToolCall => o.type === 'function_call',\n );\n for (const item of response.output) {\n if (item.type === 'message') {\n for (const part of item.content) {\n if (part.type === 'output_text') allText += part.text;\n }\n }\n }\n\n if (functionCalls.length === 0) break;\n\n input = [\n ...(response.output as OpenAI.Responses.ResponseInputItem[]),\n ];\n for (const fc of functionCalls) {\n const tool = tools.find((t) => t.name === fc.name);\n const result = tool\n ? await tool.handler(\n JSON.parse(fc.arguments ?? '{}') as JsonObject,\n )\n : { content: [{ text: `Tool '${fc.name}' not found` }] };\n input.push({\n type: 'function_call_output',\n call_id: fc.call_id,\n output: result.content[0]?.text ?? '',\n });\n }\n }\n\n return {\n text: allText,\n inputTokens: totalIn,\n outputTokens: totalOut,\n turnsUsed: input.length,\n };\n }\n}\n\n// =============================================================================\n// GoogleAgent — uses Interactions API (server-side state, automatic caching)\n// =============================================================================\n\n/**\n * Concatenate text across all `model_output` steps of an interaction\n * (@google/genai >= 2.0.0 'steps' schema). Steps form a discriminated\n * union — even at thinking_level 'minimal' a `thought` step is present,\n * so iterate by discriminant and skip step types we don't consume.\n */\nfunction interactionText(interaction: Interactions.Interaction): string {\n let text = '';\n for (const step of interaction.steps ?? []) {\n if (step.type === 'model_output') {\n for (const content of step.content ?? []) {\n if (content.type === 'text') {\n text += content.text;\n }\n }\n }\n }\n return text;\n}\n\n/** Collect the function-call steps of an interaction. */\nfunction functionCallSteps(\n interaction: Interactions.Interaction,\n): Interactions.FunctionCallStep[] {\n return (interaction.steps ?? []).filter(\n (s): s is Interactions.FunctionCallStep => s.type === 'function_call',\n );\n}\n\n/**\n * Wrap a user prompt as a `user_input` step. In the 2.x request union a\n * mixed input array is `Array<Step>` — bare `{type:'text'}` content is\n * not a Step, so prompts sent alongside function_result steps must be\n * wrapped.\n */\nfunction toUserInputStep(text: string): Interactions.UserInputStep {\n return { type: 'user_input', content: [{ type: 'text', text }] };\n}\n\nexport class GoogleAgent extends LLMAgent {\n readonly provider = 'google' as const;\n\n protected resolveModel(model: string): string {\n // Strip the LiteLLM transport prefix `gemini/` (Google AI Studio\n // route) so the GenAI SDK receives the bare model id it expects.\n // Pre-slice-#43 close-out this stripped `google/` instead — which\n // (a) doesn't match LiteLLM's `gemini/` convention and (b) silently\n // no-op'd against canonical `gemini/...` strings, then passed\n // them to the GenAI SDK which 4xx's on the prefixed form. Fixed\n // as part of the slice #43 audit. Bare ids pass through verbatim\n // (typed `LlmRoute` already guarantees wire-canonical at every\n // OSS call site).\n return model.startsWith('gemini/')\n ? model.slice('gemini/'.length)\n : model;\n }\n\n protected async createClient(): Promise<GoogleGenAI> {\n const { GoogleGenAI: GoogleGenAISDK } = await import('@google/genai');\n return new GoogleGenAISDK({\n apiKey: process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY,\n httpOptions: { timeout: 300_000 }, // 5 min — Pro models can be slow\n });\n }\n\n async callText(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n temperature?: number,\n ): Promise<LLMResponse> {\n const client = await this.getClient<GoogleGenAI>();\n\n const generationConfig: Interactions.GenerationConfig = {\n ...(maxTokens ? { max_output_tokens: maxTokens } : {}),\n ...(temperature !== undefined ? { temperature } : {}),\n };\n\n const interaction = await this.apiCall(() =>\n client.interactions.create({\n model: this.resolveModel(model),\n system_instruction: systemPrompt,\n input: userPrompt,\n generation_config:\n Object.keys(generationConfig).length > 0 ? generationConfig : undefined,\n }),\n );\n\n return {\n text: interactionText(interaction),\n inputTokens: interaction.usage?.total_input_tokens ?? 0,\n outputTokens: interaction.usage?.total_output_tokens ?? 0,\n };\n }\n\n async callTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMToolDef[],\n _toolChoice: 'required' | 'auto' = 'required',\n scopedTools?: LLMToolDef[],\n ): Promise<LLMToolCallResponse> {\n const client = await this.getClient<GoogleGenAI>();\n\n\n const interactionTools: Interactions.Function[] = tools.map((t) => ({\n type: 'function' as const,\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n }));\n const scopedInteractionTools: Interactions.Function[] | undefined = scopedTools?.map((t) => ({\n type: 'function' as const,\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n }));\n\n // Chain off previous interaction if available — server has system prompt + tools\n const resolvedModel = this.resolveModel(model);\n\n // Consume pending tool results — prepend them to the input so the API\n // sees function_result + the new prompt (as a user_input step) in one\n // call (saves a round-trip)\n const pending = this.pendingToolResults;\n this.pendingToolResults = [];\n const input: string | Interactions.Step[] = pending.length > 0\n ? [...pending, toUserInputStep(userPrompt)]\n : userPrompt;\n\n const createInteraction = () =>\n this.lastSessionId\n ? client.interactions.create({\n model: resolvedModel,\n previous_interaction_id: this.lastSessionId,\n input,\n tools: interactionTools,\n generation_config: { max_output_tokens: 16384 },\n })\n : client.interactions.create({\n model: resolvedModel,\n system_instruction: systemPrompt,\n tools: interactionTools,\n input: userPrompt,\n generation_config: { max_output_tokens: 16384 },\n });\n\n // Retry up to 3 attempts for malformed_tool_call (model generates invalid JSON).\n // If all 3 fail AND scopedTools were provided, one final attempt with the\n // narrower scoped tool schema. Universal runtime-signal fallback — the\n // signal is the transport error, not the provider identity.\n let interaction!: Interactions.Interaction;\n const MAX_MALFORMED_RETRIES = 3;\n let succeeded = false;\n for (let attempt = 0; attempt < MAX_MALFORMED_RETRIES; attempt++) {\n try {\n if (attempt === 0) {\n interaction = await this.apiCall(createInteraction);\n } else {\n const jsonHint = '\\n\\nIMPORTANT: Your previous response had invalid JSON. Produce valid JSON in your tool call arguments.';\n const retryPrompt = userPrompt + jsonHint;\n interaction = await this.apiCall(() =>\n this.lastSessionId\n ? client.interactions.create({\n model: resolvedModel,\n previous_interaction_id: this.lastSessionId,\n input: pending.length > 0\n ? [...pending, toUserInputStep(retryPrompt)]\n : retryPrompt,\n tools: interactionTools,\n generation_config: { max_output_tokens: 16384 },\n })\n : client.interactions.create({\n model: resolvedModel,\n system_instruction: systemPrompt,\n tools: interactionTools,\n input: retryPrompt,\n generation_config: { max_output_tokens: 16384 },\n }),\n );\n }\n succeeded = true;\n break;\n } catch (e: unknown) {\n const msg = e instanceof Error ? e.message : String(e);\n if (msg.includes('malformed_tool_call') && attempt < MAX_MALFORMED_RETRIES - 1) {\n console.warn(`[google] malformed_tool_call (attempt ${attempt + 1}/${MAX_MALFORMED_RETRIES}) — retrying`);\n continue;\n }\n if (msg.includes('malformed_tool_call') && scopedInteractionTools) {\n // Exhausted primary retries — try once more with the scoped\n // tool schema. The narrower tool forces a smaller payload\n // that's less likely to trip JSON emission.\n console.warn('[google] malformed_tool_call exhausted — retrying with scoped tool schema');\n const scopedHint = '\\n\\nYour previous response exceeded the tool-call payload budget. Produce a SINGLE small change (≤20 lines) using the narrowed tool schema.';\n const scopedPrompt = userPrompt + scopedHint;\n try {\n interaction = await this.apiCall(() =>\n this.lastSessionId\n ? client.interactions.create({\n model: resolvedModel,\n previous_interaction_id: this.lastSessionId,\n input: pending.length > 0\n ? [...pending, toUserInputStep(scopedPrompt)]\n : scopedPrompt,\n tools: scopedInteractionTools,\n generation_config: { max_output_tokens: 16384 },\n })\n : client.interactions.create({\n model: resolvedModel,\n system_instruction: systemPrompt,\n tools: scopedInteractionTools,\n input: scopedPrompt,\n generation_config: { max_output_tokens: 16384 },\n }),\n );\n succeeded = true;\n break;\n } catch (e2: unknown) {\n const msg2 = e2 instanceof Error ? e2.message : String(e2);\n console.error(`[google] scoped retry FAILED: ${msg2.slice(0, 300)}`);\n throw e2;\n }\n }\n console.error(`[google] callTools FAILED: ${msg.slice(0, 300)}`);\n throw e;\n }\n }\n if (!succeeded) throw new Error('[google] callTools: exhausted retries without success');\n\n // Save session ID for chaining subsequent calls\n this.lastSessionId = interaction.id;\n\n const toolCalls = functionCallSteps(interaction).map((fc) => ({\n id: fc.id,\n name: fc.name,\n input: toolArgsToJsonObject(fc.arguments),\n }));\n\n return {\n toolCalls,\n inputTokens: interaction.usage?.total_input_tokens ?? 0,\n outputTokens: interaction.usage?.total_output_tokens ?? 0,\n };\n }\n\n // Pending tool results — stored by sendToolResult, consumed by next callTools\n private pendingToolResults: Interactions.FunctionResultStep[] = [];\n\n override async sendToolResult(results: LLMToolResult[]): Promise<void> {\n // Store results locally — they'll be prepended to the next callTools input.\n // No API call here! Saves ~5.8s per turn.\n this.pendingToolResults = results.map((r) => ({\n type: 'function_result' as const,\n call_id: r.callId ?? '',\n name: r.name,\n result: r.result,\n is_error: r.isError,\n }));\n }\n\n async callWithTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number,\n ): Promise<LLMWithToolsResponse> {\n const client = await this.getClient<GoogleGenAI>();\n\n\n const interactionTools: Interactions.Function[] = tools.map((t) => ({\n type: 'function' as const,\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n }));\n\n let totalIn = 0;\n let totalOut = 0;\n let allText = '';\n let turnsUsed = 0;\n\n // Turn 1: system instruction + tools + user prompt\n let interaction = await this.apiCall(() =>\n client.interactions.create({\n model: this.resolveModel(model),\n system_instruction: systemPrompt,\n tools: interactionTools,\n input: userPrompt,\n }),\n );\n\n for (let turn = 0; turn < maxTurns; turn++) {\n turnsUsed = turn + 1;\n\n if (interaction.usage) {\n totalIn += interaction.usage.total_input_tokens ?? 0;\n totalOut += interaction.usage.total_output_tokens ?? 0;\n }\n\n // Collect text\n allText += interactionText(interaction);\n\n // Collect function calls\n const fnCalls = functionCallSteps(interaction);\n\n if (fnCalls.length === 0) break;\n\n // Execute tools and build function_result inputs\n const results: Interactions.FunctionResultStep[] = [];\n for (const fc of fnCalls) {\n const tool = tools.find((t) => t.name === fc.name);\n if (!tool) {\n results.push({\n type: 'function_result',\n call_id: fc.id,\n name: fc.name,\n result: JSON.stringify({ error: `Tool '${fc.name}' not found` }),\n is_error: true,\n });\n continue;\n }\n const result = await tool.handler(toolArgsToJsonObject(fc.arguments));\n results.push({\n type: 'function_result',\n call_id: fc.id,\n name: fc.name,\n result: result.content.map((c) => c.text).join('\\n'),\n });\n }\n\n // Next turn: only send function results — server has the history\n interaction = await this.apiCall(() =>\n client.interactions.create({\n model: this.resolveModel(model),\n previous_interaction_id: interaction.id,\n input: results,\n }),\n );\n }\n\n return {\n text: allText,\n inputTokens: totalIn,\n outputTokens: totalOut,\n turnsUsed,\n };\n }\n}\n\n// =============================================================================\n// OpenRouterAgent\n// =============================================================================\n\nexport class OpenRouterAgent extends LLMAgent {\n readonly provider = 'openrouter' as const;\n\n // Client-side session history — system prompt sent once, subsequent\n // callTools() calls append to the conversation without re-sending it.\n private sessionMessages: import('../adapters/openrouter/types').OpenRouterMessage[] = [];\n\n protected resolveModel(model: string): string {\n // Strip 'openrouter/' prefix — OpenRouter API expects 'provider/model'\n // e.g., 'openrouter/anthropic/claude-3.5-sonnet' → 'anthropic/claude-3.5-sonnet'\n return model.startsWith('openrouter/')\n ? model.slice('openrouter/'.length)\n : model;\n }\n\n override resetSession(): void {\n super.resetSession();\n this.sessionMessages = [];\n }\n\n protected async createClient(): Promise<unknown> {\n const { OpenRouterClient } = await import('../adapters/openrouter/client');\n return new OpenRouterClient({\n apiKey: process.env.OPENROUTER_API_KEY!,\n });\n }\n\n async callText(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n temperature?: number,\n ): Promise<LLMResponse> {\n type Client = import('../adapters/openrouter/client').OpenRouterClient;\n const client = await this.getClient<Client>();\n const resolved = this.resolveModel(model);\n\n const response = await this.apiCall(() =>\n client.chatCompletion({\n model: resolved,\n messages: [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userPrompt },\n ],\n max_tokens: maxTokens ?? 4096,\n ...(temperature !== undefined && { temperature }),\n }),\n );\n\n const text = response.choices[0]?.message.content ?? '';\n return {\n text,\n inputTokens: response.usage.prompt_tokens,\n outputTokens: response.usage.completion_tokens,\n };\n }\n\n async callTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMToolDef[],\n toolChoice?: 'required' | 'auto',\n _scopedTools?: LLMToolDef[],\n ): Promise<LLMToolCallResponse> {\n type Client = import('../adapters/openrouter/client').OpenRouterClient;\n const client = await this.getClient<Client>();\n const resolved = this.resolveModel(model);\n\n const orTools = tools.map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n }));\n\n // Build messages — first call sends system prompt, subsequent calls reuse session\n if (this.sessionMessages.length === 0) {\n this.sessionMessages.push({ role: 'system', content: systemPrompt });\n }\n this.sessionMessages.push({ role: 'user', content: userPrompt });\n\n const response = await this.apiCall(() =>\n client.chatCompletion({\n model: resolved,\n messages: this.sessionMessages,\n tools: orTools,\n tool_choice: toolChoice ?? 'auto',\n }),\n );\n\n // Append assistant response to session history\n const choice = response.choices[0];\n if (choice?.message) {\n this.sessionMessages.push({\n role: 'assistant',\n content: choice.message.content,\n tool_calls: choice.message.tool_calls,\n });\n }\n\n const toolCalls = (choice?.message.tool_calls ?? []).map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments || '{}') as JsonObject,\n }));\n\n return {\n toolCalls,\n inputTokens: response.usage.prompt_tokens,\n outputTokens: response.usage.completion_tokens,\n };\n }\n\n override async sendToolResult(results: LLMToolResult[]): Promise<void> {\n // Append tool results to session history — proper chat contract\n for (const r of results) {\n this.sessionMessages.push({\n role: 'tool',\n tool_call_id: r.callId,\n content: r.result,\n });\n }\n }\n\n async callWithTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number,\n ): Promise<LLMWithToolsResponse> {\n type Client = import('../adapters/openrouter/client').OpenRouterClient;\n const client = await this.getClient<Client>();\n const resolved = this.resolveModel(model);\n\n const orTools = tools.map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n }));\n\n type ORMessage = import('../adapters/openrouter/types').OpenRouterMessage;\n const messages: ORMessage[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userPrompt },\n ];\n\n let totalInput = 0;\n let totalOutput = 0;\n let turnsUsed = 0;\n let finalText = '';\n\n for (let turn = 0; turn < maxTurns; turn++) {\n turnsUsed = turn + 1;\n\n const response = await this.apiCall(() =>\n client.chatCompletion({\n model: resolved,\n messages: messages as import('../adapters/openrouter/types').OpenRouterMessage[],\n tools: orTools,\n tool_choice: 'auto',\n }),\n );\n\n totalInput += response.usage.prompt_tokens;\n totalOutput += response.usage.completion_tokens;\n\n const choice = response.choices[0];\n if (!choice) break;\n\n if (choice.message.content) {\n finalText = choice.message.content;\n }\n\n const toolCalls = choice.message.tool_calls;\n if (!toolCalls || toolCalls.length === 0) break;\n\n messages.push({\n role: 'assistant',\n content: choice.message.content,\n tool_calls: toolCalls,\n });\n\n for (const tc of toolCalls) {\n const toolDef = tools.find((t) => t.name === tc.function.name);\n let resultText: string;\n if (!toolDef) {\n resultText = JSON.stringify({ error: `Tool '${tc.function.name}' not found` });\n } else {\n const args = JSON.parse(tc.function.arguments || '{}') as JsonObject;\n const result = await toolDef.handler(args);\n resultText = result.content.map((c) => c.text).join('\\n');\n }\n messages.push({ role: 'tool', tool_call_id: tc.id, content: resultText });\n }\n }\n\n return { text: finalText, inputTokens: totalInput, outputTokens: totalOutput, turnsUsed };\n }\n}\n\n// =============================================================================\n// Agent Registry\n// =============================================================================\n\n/**\n * Create a fresh agent instance for the given provider.\n * Each call returns a new instance — no shared state between callers.\n */\nexport function createAgent(provider: AgentConfig['provider']): LLMAgent {\n switch (provider) {\n case 'anthropic':\n return new AnthropicAgent();\n case 'openai':\n return new OpenAIAgent();\n case 'google':\n return new GoogleAgent();\n case 'openrouter':\n return new OpenRouterAgent();\n }\n}\n\n// =============================================================================\n// Backward-compatible free functions\n// =============================================================================\n\nexport async function callLLM(\n config: AgentConfig,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n): Promise<LLMResponse> {\n const start = Date.now();\n const agent = createAgent(config.provider);\n const result = await agent.callText(\n config.model,\n systemPrompt,\n userPrompt,\n maxTokens,\n config.temperature,\n );\n console.log(\n `[llm-router] ${config.provider}/${config.model} | ${Date.now() - start}ms | in=${result.inputTokens} out=${result.outputTokens}`,\n );\n return result;\n}\n\nexport async function callLLMWithTools(\n config: AgentConfig,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number = 10,\n): Promise<LLMWithToolsResponse> {\n const start = Date.now();\n const agent = createAgent(config.provider);\n const result = await agent.callWithTools(\n config.model,\n systemPrompt,\n userPrompt,\n tools,\n maxTurns,\n );\n console.log(\n `[llm-router] agentic ${config.provider}/${config.model} | ${Date.now() - start}ms | turns=${result.turnsUsed} | in=${result.inputTokens} out=${result.outputTokens}`,\n );\n return result;\n}\n\n","// packages/ui-gen/src/evaluation/evaluator.ts\n//\n// Unified, provider-agnostic UI evaluation.\n//\n// One evaluation function that works with Claude, OpenAI, and Google.\n// Routes to the correct API based on config.provider.\n//\n// Responsibilities (things self_check CANNOT verify):\n// - Visual design quality, hierarchy, composition\n// - Interaction polish (hover, transitions, animations)\n// - Prompt completeness (does it match what was requested?)\n// - Data rendering quality (not just present, but well-formatted)\n//\n// Does NOT re-check (already handled by self_check):\n// - Hardcoded hex colors (self_check catches these)\n// - Raw pixel values (self_check catches these)\n// - Wrong imports (self_check catches these)\n// - Missing Props interface (self_check catches these)\n// - Null safety (TypeChecker strictNullChecks catches these)\n\nimport type { EvaluationConfig, EvaluationContext, EvaluationResult, DimensionScores, EvaluationIssue } from './types';\nimport { createAgent } from '../harness/llm-router';\nimport type { LLMToolDef } from '../harness/llm-router';\n\n// ---------------------------------------------------------------------------\n// Evaluation tool (structured output via tool calling)\n// ---------------------------------------------------------------------------\n\nconst EVAL_TOOL: LLMToolDef = {\n name: \"submit_evaluation\",\n description: \"Submit the UI quality evaluation scores and feedback.\",\n parameters: {\n type: \"object\",\n properties: {\n completeness: { type: \"number\", description: \"0-100: Does the component implement ALL features from the prompt?\" },\n visualDesign: { type: \"number\", description: \"0-100: Layout, visual hierarchy, spacing, polished appearance\" },\n interactivity: { type: \"number\", description: \"0-100: Hover/focus states, transitions, form validation, loading states\" },\n accessibility: { type: \"number\", description: \"0-100: Semantic HTML, ARIA labels, keyboard navigation, contrast\" },\n codeQuality: { type: \"number\", description: \"0-100: Clean structure, state management, event handlers, defaults\" },\n issues: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n dimension: { type: \"string\" },\n severity: { type: \"string\", description: \"critical, major, or minor\" },\n description: { type: \"string\" },\n fix: { type: \"string\" },\n },\n required: [\"dimension\", \"severity\", \"description\", \"fix\"],\n },\n description: \"List of specific issues found\",\n },\n critique: { type: \"string\", description: \"2-3 sentences: what's good and what needs improvement\" },\n },\n required: [\"completeness\", \"visualDesign\", \"interactivity\", \"accessibility\", \"codeQuality\", \"issues\", \"critique\"],\n },\n};\n\n// ---------------------------------------------------------------------------\n// Unified evaluation prompt\n// ---------------------------------------------------------------------------\n\nconst EVAL_SYSTEM_PROMPT = `You are a UI quality evaluator for ggui-generated React components.\n\nThe code has ALREADY passed automated checks for:\n- Design token usage (no hardcoded colors/spacing)\n- Import constraints (only react + @ggui-ai/design)\n- TypeScript types (Props interface, null safety)\n- Compilation + render smoke test\n\nDo NOT penalize for things the automated checks already cover. Focus ONLY on quality aspects that require human judgment.\n\n## Dimensions (score each 0-100)\n\n1. **completeness** (25%): Does the component implement ALL features from the original prompt? Are all requested UI elements present? Does it use ALL props from the contract (especially nested fields in arrays)?\n\n2. **visualDesign** (25%): Is the layout well-composed? Clear visual hierarchy (headings > subheadings > body)? Good use of whitespace and spacing? Proper use of primitive variants (primary for CTAs, outline for secondary, ghost for tertiary)? Professional, polished appearance?\n\n3. **interactivity** (20%): Are interactive elements polished? Hover/focus states on buttons and links? Smooth transitions (200ms ease)? Form validation with inline errors? Disabled states during submission? Loading indicators? Keyboard navigation?\n\n4. **accessibility** (15%): Semantic HTML (headings, lists, landmarks)? ARIA labels on inputs and interactive elements? Keyboard-navigable? Focus management? Readable text contrast?\n\n5. **codeQuality** (15%): Clean component structure? Proper state management? Event handlers wired correctly? No unnecessary re-renders? Default prop values for all optional props?\n\n## Scoring Scale\n\n- 90-100: Production-ready. Polished layout, smooth interactions, full accessibility, clean code.\n- 80-89: Good. Minor improvements needed (a missing hover state, slightly tight spacing).\n- 70-79: Acceptable. Works correctly but lacks polish (no transitions, generic layout).\n- 60-69: Below standard. Missing features, poor layout, no interactive states.\n- Below 60: Broken or fundamentally incomplete.\n\nCall the \\`submit_evaluation\\` tool with your scores, issues, and critique.`;\n\n// ---------------------------------------------------------------------------\n// Provider-agnostic evaluation\n// ---------------------------------------------------------------------------\n\n/**\n * Run a single evaluation round using any LLM provider.\n *\n * Provider-agnostic: routes to Claude, OpenAI, or Google API based on config.provider.\n * Falls back to Claude if no provider is specified.\n */\nexport async function runEvaluation(\n context: EvaluationContext,\n config: EvaluationConfig,\n): Promise<EvaluationResult> {\n const providerName = config.provider ?? 'claude';\n const model = config.model || getDefaultEvalModel(providerName);\n const routerProvider = providerName === 'claude' ? 'anthropic' as const : providerName as 'openai' | 'google' | 'openrouter';\n\n const userPrompt = buildEvalUserPrompt(context);\n const agent = createAgent(routerProvider);\n\n // Use tool calling for structured output — no JSON parsing needed\n const response = await agent.callTools(\n model,\n EVAL_SYSTEM_PROMPT,\n userPrompt,\n [EVAL_TOOL],\n 'required',\n );\n\n const call = response.toolCalls[0];\n if (!call) {\n throw new Error('Evaluator did not return a tool call');\n }\n\n const raw = call.input as Record<string, unknown>;\n return buildEvalResult(raw, config.passThreshold, response.inputTokens, response.outputTokens);\n}\n\n// ---------------------------------------------------------------------------\n// (Provider routing removed — uses LLM router via createAgent/callTools)\n// ---------------------------------------------------------------------------\n\n\n\n// ---------------------------------------------------------------------------\n// User prompt builder\n// ---------------------------------------------------------------------------\n\nfunction buildEvalUserPrompt(context: EvaluationContext): string {\n const parts: string[] = [];\n\n parts.push(`## Original Request\\n${context.originalPrompt}`);\n\n if (context.designContext) {\n parts.push(`## App Design Context\\n${context.designContext}`);\n }\n\n parts.push(`## Source Code\\n\\`\\`\\`tsx\\n${context.sourceCode.slice(0, 10000)}\\n\\`\\`\\``);\n\n return parts.join('\\n\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Response parsing\n// ---------------------------------------------------------------------------\n\n/**\n * Build EvaluationResult from tool call input (structured data, no JSON parsing).\n */\nfunction buildEvalResult(\n raw: Record<string, unknown>,\n passThreshold: number,\n inputTokens: number,\n outputTokens: number,\n): EvaluationResult {\n const dimensions: DimensionScores = {\n completeness: (raw.completeness as number) ?? 0,\n visualPolish: (raw.visualDesign as number) ?? (raw.visualPolish as number) ?? 0,\n interactivity: (raw.interactivity as number) ?? 0,\n accessibility: (raw.accessibility as number) ?? 0,\n codeQuality: (raw.codeQuality as number) ?? 0,\n };\n\n const weights = {\n completeness: 0.25,\n visualPolish: 0.25,\n interactivity: 0.20,\n accessibility: 0.15,\n codeQuality: 0.15,\n };\n\n const finalScore = Math.round(\n dimensions.completeness * weights.completeness +\n dimensions.visualPolish * weights.visualPolish +\n dimensions.interactivity * weights.interactivity +\n dimensions.accessibility * weights.accessibility +\n dimensions.codeQuality * weights.codeQuality,\n );\n\n const rawIssues = (raw.issues ?? []) as Array<Record<string, string>>;\n const issues: EvaluationIssue[] = rawIssues.map((i) => ({\n dimension: i.dimension || 'unknown',\n severity: (i.severity as 'critical' | 'major' | 'minor') || 'minor',\n description: i.description || '',\n fix: i.fix || '',\n }));\n\n return {\n passed: finalScore >= passThreshold,\n finalScore,\n dimensions,\n issues,\n critique: raw.critique as string,\n inputTokens,\n outputTokens,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Default models per provider (cheapest/fastest)\n// ---------------------------------------------------------------------------\n\nfunction getDefaultEvalModel(provider: string): string {\n switch (provider) {\n case 'claude': return 'claude-haiku-4-5-20251001';\n case 'openai': return 'gpt-5.6-luna';\n case 'google': return 'gemini-3.5-flash-lite';\n default: return 'claude-haiku-4-5-20251001';\n }\n}\n","// packages/ui-gen/src/evaluation/message-parsing.ts\n\n/**\n * Shared message parsing utilities for extracting structured data from\n * Claude Agent SDK `query()` messages.\n *\n * These functions are used by evaluator.ts, loop.ts, and generator.ts\n * to capture tool results, source code, and session state from the\n * SDK message stream.\n */\n\nimport type { EvaluationResult } from './types';\n\n// ── SDK message type aliases ────────────────────────────────────────\n\n/** A single SDK message from the `query()` async iterator. */\nexport type SdkMessage = Record<string, unknown>;\n\n/** Content block inside a user or assistant message. */\ntype ContentBlock = Record<string, unknown>;\n\n/** A text item inside a tool_result content array. */\ninterface TextItem {\n type?: string;\n text?: string;\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\n/**\n * Extract tool_result text items from a user-type SDK message.\n * Returns an empty array if the message isn't a user message or has no tool results.\n */\nexport function extractToolResultTexts(message: SdkMessage): string[] {\n if ((message.type as string) !== 'user') return [];\n\n const texts: string[] = [];\n const innerMessage = message.message as SdkMessage | undefined;\n const messageContent = innerMessage?.content as ContentBlock[] | undefined;\n\n if (!Array.isArray(messageContent)) return texts;\n\n for (const contentItem of messageContent) {\n if (contentItem.type === 'tool_result') {\n const toolResultContent = contentItem.content as TextItem[] | undefined;\n if (Array.isArray(toolResultContent)) {\n for (const textItem of toolResultContent) {\n if (textItem.type === 'text' && textItem.text) {\n texts.push(textItem.text);\n }\n }\n }\n }\n }\n\n return texts;\n}\n\n// ── EvaluationResult extraction ─────────────────────────────────────\n\n/**\n * Extract an `EvaluationResult` from an array of SDK messages.\n *\n * Scans for user messages containing a tool_result with JSON that has\n * `finalScore` (number) and `dimensions` fields. Returns the last\n * matching result, or `undefined` if none found.\n *\n * Used by: evaluator.ts\n */\nexport function extractEvalResult(messages: SdkMessage[]): EvaluationResult | undefined {\n let evalResult: EvaluationResult | undefined;\n\n for (const message of messages) {\n const msgStr = JSON.stringify(message);\n if (!msgStr.includes('finalScore') || !msgStr.includes('dimensions')) continue;\n\n for (const text of extractToolResultTexts(message)) {\n if (!text.includes('finalScore')) continue;\n try {\n const parsed = JSON.parse(text) as EvaluationResult;\n if (typeof parsed.finalScore === 'number' && parsed.dimensions) {\n evalResult = parsed;\n }\n } catch {\n // Not valid JSON\n }\n }\n }\n\n return evalResult;\n}\n\n// ── compiledCode extraction ─────────────────────────────────────────\n\n/**\n * Extract `compiledCode` from a single SDK message.\n *\n * Tries two strategies:\n * 1. Regex extraction from the full serialized message (fallback)\n * 2. Structured extraction from user/tool_result content\n *\n * Returns the extracted code or `undefined`.\n *\n * Used by: loop.ts, generator.ts\n */\nexport function extractCompiledCodeFromMessage(message: SdkMessage): string | undefined {\n const msgStr = JSON.stringify(message);\n if (!msgStr.includes('compiledCode')) return undefined;\n\n // Strategy 1: Regex fallback (catches compiledCode in any position)\n let regexCode: string | undefined;\n const match = msgStr.match(/\"compiledCode\"\\s*:\\s*\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/);\n if (match) {\n try {\n regexCode = JSON.parse(`\"${match[1]}\"`);\n } catch {\n // Not parseable\n }\n }\n\n // Strategy 2: Structured extraction from tool_result\n for (const text of extractToolResultTexts(message)) {\n if (!text.includes('compiledCode')) continue;\n try {\n const parsed = JSON.parse(text);\n if (parsed.success && parsed.compiledCode) {\n return parsed.compiledCode; // Prefer structured over regex\n }\n } catch {\n // Not JSON\n }\n }\n\n return regexCode;\n}\n\n// ── sourceCode extraction ───────────────────────────────────────────\n\n/**\n * Extract source code from an assistant's Write tool_use message.\n *\n * Looks for `tool_use` blocks with `name === 'Write'` and returns\n * the `input.content` string. If multiple Write calls exist, returns\n * the last one (the final version).\n *\n * Used by: loop.ts, generator.ts\n */\nexport function extractSourceCodeFromMessage(message: SdkMessage): string | undefined {\n if ((message.type as string) !== 'assistant') return undefined;\n\n let sourceCode: string | undefined;\n const betaMessage = message.message as SdkMessage | undefined;\n const content = betaMessage?.content as ContentBlock[] | undefined;\n\n if (!Array.isArray(content)) return undefined;\n\n for (const block of content) {\n if (block.type === 'tool_use' && block.name === 'Write') {\n const input = block.input as { content?: string } | undefined;\n if (input?.content) {\n sourceCode = input.content;\n }\n }\n }\n\n return sourceCode;\n}\n\n// ── Batch helpers ───────────────────────────────────────────────────\n\n/**\n * Scan all messages for the last compiledCode value.\n *\n * Convenience wrapper for tests and one-shot extraction.\n */\nexport function extractCompiledCode(messages: SdkMessage[]): string | undefined {\n let compiledCode: string | undefined;\n for (const message of messages) {\n const code = extractCompiledCodeFromMessage(message);\n if (code) compiledCode = code;\n }\n return compiledCode;\n}\n\n/**\n * Scan all messages for the last sourceCode from Write tool_use.\n *\n * Convenience wrapper for tests and one-shot extraction.\n */\nexport function extractSourceCode(messages: SdkMessage[]): string | undefined {\n let sourceCode: string | undefined;\n for (const message of messages) {\n const code = extractSourceCodeFromMessage(message);\n if (code) sourceCode = code;\n }\n return sourceCode;\n}\n","// packages/ui-gen/src/evaluation/prompts.ts\n\nimport type { EvaluationResult } from './types';\n\n/**\n * System prompt for the evaluator agent.\n * Static/cacheable — defines rubric, dimensions, and workflow.\n */\nexport function getEvaluatorSystemPrompt(): string {\n return `# UI Component Evaluator\n\nYou evaluate ggui-generated React components. You MUST call the \\`evaluate_score\\` tool — this is your only task. Do NOT write any text before calling the tool. Analyze the code silently, then immediately call \\`evaluate_score\\` with your scores and issues.\n\n## Dimensions (score each 0-100)\n\n- **Completeness**: All requested features present and functional\n- **Visual Polish**: Layout, spacing, design token usage, DESIGN.md compliance\n- **Interactivity**: Event handlers, state management, callbacks working\n- **Accessibility**: ARIA labels, keyboard nav, semantic HTML, contrast\n- **Code Quality**: Clean structure, proper primitives, no dead code, single default export GeneratedComponent\n\n## Scoring Scale\n\n- 90-100: Excellent, production-ready\n- 70-89: Good, minor improvements possible\n- 50-69: Needs work\n- 30-49: Poor\n- 0-29: Fundamentally broken\n\n## Issue Severities\n\n- **critical**: Missing core features, broken functionality, security problems\n- **major**: Poor accessibility, layout bugs, missing error handling\n- **minor**: Style inconsistencies, naming conventions\n\nIMPORTANT: Call the \\`evaluate_score\\` tool immediately. Do not write analysis text first.`;\n}\n\n/**\n * Build the fix prompt to resume the generator session with evaluation feedback.\n * Issues are grouped by severity (critical first) so the generator prioritizes correctly.\n */\nexport function buildFixPrompt(evalResult: EvaluationResult, originalPrompt: string): string {\n let prompt = `## Evaluation Feedback — Fix Required\n\nYour generated component was evaluated and scored **${evalResult.finalScore}/100** (threshold: 70).\n\n### Scores\n| Dimension | Score |\n|-----------|-------|\n| Completeness | ${evalResult.dimensions.completeness} |\n| Visual Polish | ${evalResult.dimensions.visualPolish} |\n| Interactivity | ${evalResult.dimensions.interactivity} |\n| Accessibility | ${evalResult.dimensions.accessibility} |\n| Code Quality | ${evalResult.dimensions.codeQuality} |\n`;\n\n if (evalResult.critique) {\n prompt += `\n### Overall Critique\n${evalResult.critique}\n`;\n }\n\n // Group issues by severity\n const critical = evalResult.issues.filter((i) => i.severity === 'critical');\n const major = evalResult.issues.filter((i) => i.severity === 'major');\n const minor = evalResult.issues.filter((i) => i.severity === 'minor');\n\n if (critical.length > 0) {\n prompt += `\n### Critical Issues (must fix)\n${critical.map((i) => `- **[${i.dimension}]** ${i.description}\\n Fix: ${i.fix}`).join('\\n')}\n`;\n }\n\n if (major.length > 0) {\n prompt += `\n### Major Issues (should fix)\n${major.map((i) => `- **[${i.dimension}]** ${i.description}\\n Fix: ${i.fix}`).join('\\n')}\n`;\n }\n\n if (minor.length > 0) {\n prompt += `\n### Minor Issues (nice to fix)\n${minor.map((i) => `- **[${i.dimension}]** ${i.description}\\n Fix: ${i.fix}`).join('\\n')}\n`;\n }\n\n prompt += `\n### Instructions\n\nFix the issues above, prioritizing critical and major issues. The original request was:\n\n> ${originalPrompt}\n\nAfter fixing, re-validate and re-compile the component. Write the updated code to Component.tsx, validate it, and compile it.`;\n\n return prompt;\n}\n","// packages/ui-gen/src/evaluation/types.ts\n\n/**\n * Per-dimension quality scores from the evaluator (0-100 each).\n */\nexport interface DimensionScores {\n /** How well the component fulfills the original prompt requirements */\n completeness: number;\n /** Visual quality: layout, typography, spacing, color usage */\n visualPolish: number;\n /** Interaction quality: hover states, transitions, form validation */\n interactivity: number;\n /** Accessibility: ARIA labels, keyboard navigation, contrast ratios */\n accessibility: number;\n /** Code quality: TypeScript types, clean structure, no anti-patterns */\n codeQuality: number;\n}\n\n/**\n * A specific issue found during evaluation.\n */\nexport interface EvaluationIssue {\n /** Which quality dimension this issue belongs to */\n dimension: string;\n /** Human-readable description of what is wrong */\n description: string;\n /** Severity level: critical blocks shipping, major degrades quality, minor is a polish issue */\n severity: 'critical' | 'major' | 'minor';\n /** Suggested fix for the agent to apply */\n fix: string;\n}\n\n/**\n * Result of a single evaluation round.\n */\nexport interface EvaluationResult {\n /** Whether the component passed the quality threshold */\n passed: boolean;\n /** Weighted average score across all dimensions (0-100) */\n finalScore: number;\n /** Per-dimension score breakdown */\n dimensions: DimensionScores;\n /** Specific issues identified in this round */\n issues: EvaluationIssue[];\n /** Free-form critique text from the evaluator LLM */\n critique?: string;\n /** Input tokens consumed by the evaluation LLM call */\n inputTokens?: number;\n /** Output tokens consumed by the evaluation LLM call */\n outputTokens?: number;\n}\n\n/**\n * Quality metadata attached to every generated component\n */\nexport interface QualityMetadata {\n /** Number of evaluation rounds run (0 = strict/no eval) */\n evaluationRounds: number;\n /** Final average score 0-100 */\n finalScore: number;\n /** Per-dimension breakdown */\n dimensions: DimensionScores;\n /** Whether the component passed (score >= threshold) */\n passed: boolean;\n /** Model used for evaluation */\n evaluatorModel: string;\n /** Total evaluation loop time in ms */\n evaluationTimeMs: number;\n /** S3 keys for screenshots (creative only) */\n screenshots?: string[];\n}\n\n/** Hard ceiling for evaluation rounds — never exceed this regardless of config */\nexport const MAX_EVAL_ROUNDS_HARD_LIMIT = 10;\n\n/** Default (soft) max rounds for the balanced strategy */\nexport const DEFAULT_EVAL_MAX_ROUNDS = 10;\n\n/**\n * Configuration for the evaluation loop\n */\nexport interface EvaluationConfig {\n /** Whether evaluation is enabled */\n enabled: boolean;\n /** Model to use for evaluation (default: provider's default) */\n model?: string;\n /** LLM provider for evaluation (default: same as generation provider) */\n provider?: 'claude' | 'openai' | 'google' | 'openrouter';\n /** Minimum average score to pass (default: 70) */\n passThreshold: number;\n /** Maximum evaluation rounds (soft max: 3, hard limit: 5) */\n maxRounds?: number;\n /** Budget cap per evaluation round in USD */\n maxBudgetPerEval?: number;\n /** Budget cap per fix round in USD */\n maxBudgetPerFix?: number;\n}\n\n/**\n * Context passed to the evaluator\n */\nexport interface EvaluationContext {\n /** TSX source code written by the generator */\n sourceCode: string;\n /** Compiled JavaScript output */\n compiledCode: string;\n /** Original user prompt */\n originalPrompt: string;\n /** DESIGN.md content (if present) */\n designContext?: string;\n /** CSS variable tokens for the app theme */\n themeTokens: string;\n}\n","// packages/ui-gen/src/evaluation/loop.ts\n\nimport { query, type McpServerConfig } from '@anthropic-ai/claude-agent-sdk';\nimport { runEvaluation } from './evaluator';\nimport {\n extractCompiledCodeFromMessage,\n extractSourceCodeFromMessage,\n} from './message-parsing';\nimport { buildFixPrompt } from './prompts';\nimport {\n MAX_EVAL_ROUNDS_HARD_LIMIT,\n} from './types';\nimport type {\n EvaluationConfig,\n EvaluationContext,\n EvaluationResult,\n QualityMetadata,\n} from './types';\nimport type { SdkMessage } from './message-parsing';\n\n/**\n * Options for running the evaluation loop.\n *\n * Controls the evaluate-fix-re-evaluate cycle that improves generated\n * component quality until it passes or the round limit is reached.\n */\nexport interface EvaluationLoopOptions {\n /** Session ID of the generator to resume for fixes */\n generatorSessionId: string;\n /** Evaluation context (code, prompt, design, theme) */\n context: EvaluationContext;\n /** Evaluation configuration (thresholds, budgets, round limits) */\n config: EvaluationConfig;\n /** Progress callback for evaluating/fixing status updates */\n onProgress?: (event: { type: 'evaluating' | 'fixing'; round: number }) => void;\n /** Generator context to pass when resuming the session for fixes */\n generatorOptions?: {\n /** Working directory for the generator session */\n cwd?: string;\n /** MCP servers available to the fix agent */\n mcpServers?: Record<string, McpServerConfig>;\n /** Tools the fix agent is allowed to call */\n allowedTools?: string[];\n /** LLM model for fix rounds */\n model?: string;\n /** Environment variables (includes BYOK credentials) */\n env?: Record<string, string>;\n /** Stderr capture callback for debugging */\n stderr?: (data: string) => void;\n };\n}\n\n/**\n * Result of the evaluation loop.\n *\n * Contains the final (possibly fixed) code, quality scores, and\n * the evaluation history from each round.\n */\nexport interface EvaluationLoopResult {\n /** Final compiled code (may be updated by fix rounds) */\n finalCode: string;\n /** Final source code (may be updated by fix rounds) */\n finalSourceCode?: string;\n /** Quality metadata for the generation result */\n qualityMetadata: QualityMetadata;\n /** All evaluation results from each round */\n evaluationResults: EvaluationResult[];\n}\n\n/**\n * Run the evaluation loop: evaluate -> fix -> re-evaluate (up to maxRounds).\n *\n * If the first evaluation passes, returns immediately.\n * If it fails, resumes the generator session with critique feedback,\n * captures the fixed code, and re-evaluates. Repeats until the score\n * passes or the round limit is reached.\n *\n * @param options - Evaluation loop configuration and callbacks\n * @returns The final code, quality metadata, and evaluation history\n */\nexport async function runEvaluationLoop(\n options: EvaluationLoopOptions\n): Promise<EvaluationLoopResult> {\n const { generatorSessionId, context, config, onProgress, generatorOptions } = options;\n const startTime = Date.now();\n const evaluationResults: EvaluationResult[] = [];\n\n let currentCode = context.compiledCode;\n let currentSourceCode: string | undefined = context.sourceCode;\n let round = 0;\n const maxRounds = Math.min(config.maxRounds ?? 3, MAX_EVAL_ROUNDS_HARD_LIMIT);\n\n while (round < maxRounds) {\n round++;\n\n // --- Evaluate ---\n onProgress?.({ type: 'evaluating', round });\n console.log(`[eval] Round ${round}: evaluating...`);\n\n const evalContext: EvaluationContext = {\n ...context,\n compiledCode: currentCode,\n sourceCode: currentSourceCode || context.sourceCode,\n };\n const evalResult = await runEvaluation(evalContext, config);\n evaluationResults.push(evalResult);\n\n console.log(\n `[eval] Round ${round}: score=${evalResult.finalScore}, passed=${evalResult.passed}, issues=${evalResult.issues.length}`\n );\n\n // If passed or last round, we're done\n if (evalResult.passed || round >= maxRounds) {\n break;\n }\n\n // --- Fix ---\n onProgress?.({ type: 'fixing', round });\n console.log(`[eval] Round ${round}: fixing...`);\n\n const fixPrompt = buildFixPrompt(evalResult, context.originalPrompt);\n\n // Get custom CLI path from environment (for Docker deployments)\n const cliPath = process.env.CLAUDE_WRAPPER_PATH;\n\n // Build environment — use BYOK-enriched env from generator if provided\n const env: Record<string, string> = {};\n if (generatorOptions?.env) {\n Object.assign(env, generatorOptions.env);\n } else {\n for (const [key, value] of Object.entries(process.env)) {\n if (value !== undefined) {\n env[key] = value;\n }\n }\n }\n\n let fixedCompiledCode: string | undefined;\n let fixedSourceCode: string | undefined;\n\n for await (const message of query({\n prompt: fixPrompt,\n options: {\n resume: generatorSessionId,\n maxTurns: 15,\n maxBudgetUsd: config.maxBudgetPerFix,\n env,\n permissionMode: 'bypassPermissions',\n allowDangerouslySkipPermissions: true,\n ...(cliPath && { pathToClaudeCodeExecutable: cliPath }),\n ...(generatorOptions?.cwd && { cwd: generatorOptions.cwd }),\n ...(generatorOptions?.mcpServers && { mcpServers: generatorOptions.mcpServers }),\n ...(generatorOptions?.allowedTools && { allowedTools: generatorOptions.allowedTools }),\n ...(generatorOptions?.model && { model: generatorOptions.model }),\n ...(generatorOptions?.stderr && { stderr: generatorOptions.stderr }),\n },\n })) {\n const msg = message as SdkMessage;\n\n // Capture fixed compiledCode\n const compiled = extractCompiledCodeFromMessage(msg);\n if (compiled) fixedCompiledCode = compiled;\n\n // Capture source code from Write tool\n const source = extractSourceCodeFromMessage(msg);\n if (source) fixedSourceCode = source;\n }\n\n // Update current code if fix produced new output\n if (fixedCompiledCode) {\n currentCode = fixedCompiledCode;\n console.log(`[eval] Round ${round}: fixed code captured (${currentCode.length} bytes)`);\n }\n if (fixedSourceCode) {\n currentSourceCode = fixedSourceCode;\n }\n }\n\n const lastResult = evaluationResults[evaluationResults.length - 1];\n const evaluationTimeMs = Date.now() - startTime;\n\n const qualityMetadata: QualityMetadata = {\n evaluationRounds: evaluationResults.length,\n finalScore: lastResult.finalScore,\n dimensions: lastResult.dimensions,\n passed: lastResult.passed,\n evaluatorModel: config.model ?? 'default',\n evaluationTimeMs,\n };\n\n return {\n finalCode: currentCode,\n finalSourceCode: currentSourceCode,\n qualityMetadata,\n evaluationResults,\n };\n}\n","// packages/ui-gen/src/evaluation/mcp-server.ts\n\nimport { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';\nimport { z } from 'zod';\nimport type { EvaluationIssue, EvaluationResult } from './types';\n\n/**\n * Input args for the evaluate_score computation.\n * Extracted so unit tests can call the real logic directly.\n */\nexport interface EvaluateScoreInput {\n completeness: number;\n visualPolish: number;\n interactivity: number;\n accessibility: number;\n codeQuality: number;\n issues: EvaluationIssue[];\n critique?: string;\n}\n\n/**\n * Core scoring logic — extracted from the tool handler so it can be\n * unit-tested directly without going through MCP protocol.\n */\nexport function computeEvaluationScore(\n args: EvaluateScoreInput,\n passThreshold: number\n): EvaluationResult {\n const scores = [\n args.completeness,\n args.visualPolish,\n args.interactivity,\n args.accessibility,\n args.codeQuality,\n ];\n const average = scores.reduce((a, b) => a + b, 0) / scores.length;\n const finalScore = Math.round(average * 10) / 10;\n const passed = finalScore >= passThreshold;\n\n return {\n passed,\n finalScore,\n dimensions: {\n completeness: args.completeness,\n visualPolish: args.visualPolish,\n interactivity: args.interactivity,\n accessibility: args.accessibility,\n codeQuality: args.codeQuality,\n },\n issues: args.issues,\n ...(args.critique && { critique: args.critique }),\n };\n}\n\n/**\n * Create the evaluation MCP server with the evaluate_score tool.\n *\n * The evaluator LLM provides qualitative scores per dimension.\n * This tool handles the arithmetic (average, pass/fail) so the LLM\n * doesn't need to do math.\n */\nexport function createEvaluationToolsServer(passThreshold = 70) {\n return createSdkMcpServer({\n name: 'eval-tools',\n version: '1.0.0',\n tools: [\n tool(\n 'evaluate_score',\n 'Compute evaluation score from dimension ratings. Call this after analyzing the component code against all 5 dimensions.',\n {\n completeness: z.number().min(0).max(100).describe('Score for feature completeness (0-100)'),\n visualPolish: z.number().min(0).max(100).describe('Score for visual polish and design (0-100)'),\n interactivity: z.number().min(0).max(100).describe('Score for interactivity and state management (0-100)'),\n accessibility: z.number().min(0).max(100).describe('Score for accessibility (ARIA, keyboard nav, contrast) (0-100)'),\n codeQuality: z.number().min(0).max(100).describe('Score for code quality and structure (0-100)'),\n issues: z.array(\n z.object({\n dimension: z.string().describe('Which dimension this issue affects'),\n description: z.string().describe('What the issue is'),\n severity: z.enum(['critical', 'major', 'minor']).describe('Issue severity'),\n fix: z.string().describe('How to fix this issue'),\n })\n ).describe('List of specific issues found'),\n critique: z.string().optional().describe('Optional overall critique summary'),\n },\n async (args) => {\n const result = computeEvaluationScore(args, passThreshold);\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n ),\n ],\n });\n}\n","// packages/ui-gen/src/evaluation/axis-checks/helpers.ts\n//\n// Shared contract inspection + source-scan helpers used by axis checks.\n// Ported from the retired mode-checks/ modules.\n\nimport type { ActionEntry, DataContract, JsonObject, JsonValue } from \"@ggui-ai/protocol\";\nimport {\n HOOK_NAME_RE,\n listContractGadgets,\n STDLIB_GADGETS_PACKAGE,\n} from \"@ggui-ai/protocol\";\nimport type { EvalIssue } from \"../types-public.js\";\n\n// =============================================================================\n// Contract shape helpers\n// =============================================================================\n\nexport interface PropShape {\n type?: string;\n required?: boolean;\n items?: { type?: string; properties?: Record<string, unknown> };\n schema?: {\n type?: string;\n items?: { type?: string; properties?: Record<string, unknown> };\n };\n}\n\nexport interface EntityCollection {\n name: string;\n idField: string;\n}\n\nexport interface SubmitAction {\n name: string;\n payloadKeys: string[];\n}\n\nconst ID_FIELD_CANDIDATES = [\"id\", \"uuid\", \"symbol\", \"key\", \"slug\", \"code\"];\n\nfunction getItemsProperties(p: PropShape): Record<string, unknown> | undefined {\n return p.items?.properties ?? p.schema?.items?.properties;\n}\n\nfunction inferIdField(itemProps: Record<string, unknown> | undefined): string {\n if (!itemProps) return \"id\";\n for (const cand of ID_FIELD_CANDIDATES) {\n if (cand in itemProps) return cand;\n }\n for (const [k, v] of Object.entries(itemProps)) {\n const vv = v as { type?: string; schema?: { type?: string } } | undefined;\n if (vv?.type === \"string\" || vv?.schema?.type === \"string\") return k;\n }\n return \"id\";\n}\n\nexport function getRequiredPropNames(contract?: DataContract): string[] {\n const propsField = contract?.propsSpec as\n | { properties?: Record<string, PropShape> }\n | undefined;\n const properties = propsField?.properties ?? {};\n return Object.entries(properties)\n .filter(([, p]) => p && typeof p === \"object\" && p.required === true)\n .map(([name]) => name);\n}\n\nexport function getActionNames(contract?: DataContract): string[] {\n return Object.keys(contract?.actionSpec ?? {});\n}\n\nexport function getStreamEventNames(contract?: DataContract): string[] {\n return Object.keys(contract?.streamSpec ?? {});\n}\n\n/**\n * Returns the local BINDING names the boilerplate emits for every\n * HOOK gadget the contract declares — `useGeolocation` → `geolocation`\n * (strip the `use` prefix, lowercase the first char). The wire\n * `clientCapabilities.gadgets` is package-keyed and carries only the\n * export NAME, not a separate binding name, so the binding is derived\n * here exactly as the boilerplate generator derives it.\n *\n * Component gadgets are excluded — they are rendered as JSX, not bound\n * to a `const`, so the `const <name> = …()` axis checks don't apply.\n *\n * The agentCapabilities.tools catalog has no parallel helper —\n * agent-side tools aren't component-side, so the axis checks don't\n * scan source for agent-tool bindings.\n */\nexport function getGadgetNames(contract?: DataContract): string[] {\n if (!contract) return [];\n return listContractGadgets(contract)\n .filter((use) => HOOK_NAME_RE.test(use.name))\n .map((use) =>\n use.name.length > 3\n ? use.name.charAt(3).toLowerCase() + use.name.slice(4)\n : use.name,\n );\n}\n\n/**\n * Like {@link getGadgetNames} but restricted to the first-party\n * `@ggui-ai/gadgets` stdlib package — the built-in browser capabilities\n * (`useGeolocation`, `useCamera`, …) that carry the `idle → prompting →\n * active` lifecycle and therefore need a `.start()` invocation.\n *\n * Registered third-party gadgets (e.g. `useBoardState` from\n * `@example/gadget-board`) are plain data hooks: the runtime resolves\n * them without a user gesture, so the `.start()` axis check must NOT\n * fire on them.\n */\nexport function getStdlibGadgetNames(contract?: DataContract): string[] {\n if (!contract) return [];\n return listContractGadgets(contract)\n .filter(\n (use) =>\n use.package === STDLIB_GADGETS_PACKAGE && HOOK_NAME_RE.test(use.name),\n )\n .map((use) =>\n use.name.length > 3\n ? use.name.charAt(3).toLowerCase() + use.name.slice(4)\n : use.name,\n );\n}\n\nexport function getEntityCollections(contract?: DataContract): EntityCollection[] {\n const propsField = contract?.propsSpec as\n | { properties?: Record<string, unknown> }\n | undefined;\n const properties = propsField?.properties ?? {};\n const entities: EntityCollection[] = [];\n for (const [name, p] of Object.entries(properties)) {\n if (!p || typeof p !== \"object\") continue;\n const pp = p as PropShape;\n const type = pp.type ?? pp.schema?.type;\n const items = pp.items ?? pp.schema?.items;\n if (type === \"array\" && items?.type === \"object\") {\n entities.push({ name, idField: inferIdField(getItemsProperties(pp)) });\n }\n }\n return entities;\n}\n\nfunction singularize(name: string): string {\n if (name.endsWith(\"ies\")) return name.slice(0, -3) + \"y\";\n if (name.endsWith(\"ses\")) return name.slice(0, -2);\n if (name.endsWith(\"s\") && !name.endsWith(\"ss\")) return name.slice(0, -1);\n return name;\n}\n\n/**\n * Entity collections that are actually mutated (referenced by a stream\n * event or by an action payload's entity-id key). Static reference lists\n * (e.g., kanban's `columns`) are excluded so they don't trigger\n * \"must be in useState\" false positives.\n */\nexport function getMutatedEntityCollections(\n contract: DataContract | undefined,\n allEntities: EntityCollection[],\n): EntityCollection[] {\n if (!contract) return allEntities;\n\n const actionSpec = contract.actionSpec ?? {};\n const streamSpec = contract.streamSpec ?? {};\n\n const hasStreams = Object.keys(streamSpec).length > 0;\n\n const referencedIdKeys = new Set<string>();\n for (const action of Object.values(actionSpec) as ActionEntry[]) {\n const ex = action.example;\n if (!ex || typeof ex !== \"object\" || Array.isArray(ex)) continue;\n for (const key of Object.keys(ex as JsonObject)) {\n if (key === \"id\" || key === \"key\" || key === \"index\") {\n referencedIdKeys.add(\"id\");\n referencedIdKeys.add(\"key\");\n referencedIdKeys.add(\"index\");\n } else if (/Id$/.test(key)) {\n referencedIdKeys.add(key.slice(0, -2).toLowerCase());\n }\n }\n }\n\n const mutated = allEntities.filter((e) =>\n referencedIdKeys.has(singularize(e.name).toLowerCase()),\n );\n\n if (mutated.length === 0 && hasStreams && allEntities.length > 0) {\n return [allEntities[0]];\n }\n return mutated.length > 0 ? mutated : allEntities;\n}\n\nfunction countScalarKeys(example: unknown): string[] {\n if (!example || typeof example !== \"object\" || Array.isArray(example)) return [];\n const keys: string[] = [];\n for (const [k, v] of Object.entries(example as Record<string, unknown>)) {\n const t = typeof v;\n if (t === \"string\" || t === \"number\" || t === \"boolean\") keys.push(k);\n }\n return keys;\n}\n\nexport function getSubmitActions(contract?: DataContract): SubmitAction[] {\n const actionSpec = contract?.actionSpec ?? {};\n const result: SubmitAction[] = [];\n for (const [name, action] of Object.entries(actionSpec) as Array<[string, ActionEntry]>) {\n const ex: JsonValue | undefined = action.example;\n const scalarKeys = countScalarKeys(ex);\n if (scalarKeys.length < 3) continue;\n const allKeys = ex && typeof ex === \"object\" && !Array.isArray(ex)\n ? Object.keys(ex as JsonObject)\n : scalarKeys;\n result.push({ name, payloadKeys: allKeys });\n }\n return result;\n}\n\nexport function getArrStrProps(contract?: DataContract): string[] {\n const propsField = contract?.propsSpec as\n | { properties?: Record<string, unknown> }\n | undefined;\n const properties = propsField?.properties ?? {};\n const names: string[] = [];\n for (const [name, p] of Object.entries(properties)) {\n if (!p || typeof p !== \"object\") continue;\n const pp = p as PropShape;\n const type = pp.type ?? pp.schema?.type;\n const items = pp.items ?? pp.schema?.items;\n if (type === \"array\" && items?.type === \"string\") names.push(name);\n }\n return names;\n}\n\nexport function getInitialValuePropNames(contract?: DataContract): string[] {\n const propsField = contract?.propsSpec as\n | { properties?: Record<string, unknown> }\n | undefined;\n const properties = propsField?.properties ?? {};\n const names: string[] = [];\n for (const [name, p] of Object.entries(properties)) {\n if (!p || typeof p !== \"object\") continue;\n const pp = p as PropShape;\n const type = pp.type ?? pp.schema?.type;\n if (type === \"object\" && /^initial/i.test(name)) names.push(name);\n }\n return names;\n}\n\n// =============================================================================\n// Source scanning helpers\n// =============================================================================\n\n/**\n * Collect all key names that appear as state slots — either keys inside a\n * `useState({ ... })` object literal, or standalone state variables.\n */\nexport function collectStateKeys(src: string): Set<string> {\n const keys = new Set<string>();\n const varRe = /const\\s*\\[\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\]\\s*=\\s*useState/g;\n for (const m of src.matchAll(varRe)) keys.add(m[1]);\n const objRe = /useState(?:<[^>]*>)?\\s*\\(\\s*\\{([\\s\\S]*?)\\}\\s*\\)/g;\n for (const m of src.matchAll(objRe)) {\n const keyRe = /(?:^|,)\\s*(\\w+)\\s*:/g;\n for (const km of m[1].matchAll(keyRe)) keys.add(km[1]);\n }\n const defaultObjRe = /useState(?:<[^>]*>)?\\s*\\([^)]*\\|\\|\\s*\\{([^}]*)\\}/g;\n for (const m of src.matchAll(defaultObjRe)) {\n const keyRe = /(?:^|,)\\s*(\\w+)\\s*:/g;\n for (const km of m[1].matchAll(keyRe)) keys.add(km[1]);\n }\n return keys;\n}\n\nexport function isMultiStepPrompt(prompt: string): boolean {\n if (!prompt) return false;\n const p = prompt.toLowerCase();\n return (\n /\\bstep\\s*[1-9]\\b/.test(p) ||\n /\\b[1-9][- ]step\\b/.test(p) ||\n /\\bmulti[- ]step\\b/.test(p) ||\n /\\bwizard\\b/.test(p) ||\n /\\bsteps?:\\s*\\n?/.test(p)\n );\n}\n\n// =============================================================================\n// Issue factory\n// =============================================================================\n\nexport function mkIssue(\n subcategory: string,\n description: string,\n fix: string,\n result: \"fail\" | \"warn\" = \"fail\",\n): EvalIssue {\n // mode-category issues are structural (missing hook wiring, bad merge-by-id,\n // hardcoded entity literals) — always P0. See ALIGNMENT.md R1.\n return { tier: 0, result, category: \"mode\", priority: \"P0\", subcategory, description, fix };\n}\n\nexport function cap(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n","// packages/ui-gen/src/evaluation/axis-checks/checks/universal.ts\n//\n// Checks that run regardless of axis value — they apply to any generated\n// component. Dispatched via a \"universal\" gate that matches every render\n// value.\n\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport {\n getRequiredPropNames,\n mkIssue,\n} from \"../helpers.js\";\n\nconst ALL_RENDER_VALUES = [\n \"static\", \"list\", \"grid\", \"spatial\", \"timeline\", \"chart\", \"master-detail\",\n] as const;\n\nfunction runPropCoverage(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const requiredProps = getRequiredPropNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of requiredProps) {\n const dotAccess = new RegExp(`\\\\bprops\\\\.${name}\\\\b`);\n const bracketAccess = new RegExp(`\\\\bprops\\\\[['\"\\`]${name}['\"\\`]\\\\]`);\n const destructured = new RegExp(\n `props[^;]{0,200}\\\\{[^}]*\\\\b${name}\\\\b[^}]*\\\\}|\\\\{[^}]*\\\\b${name}\\\\b[^}]*\\\\}[^;]{0,10}=\\\\s*props`,\n );\n if (dotAccess.test(src) || bracketAccess.test(src) || destructured.test(src))\n continue;\n issues.push(\n mkIssue(\n \"universal.prop_coverage\",\n `Required prop \"${name}\" is not referenced anywhere in the component.`,\n `Render props.${name} — the data contract marks it required.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runNoPropMirror(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const issues: EvalIssue[] = [];\n const re =\n /const\\s*\\[\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\]\\s*=\\s*useState(?:<[^>]*>)?\\s*\\(\\s*props\\??\\.(\\w+)/g;\n for (const m of src.matchAll(re)) {\n const [full, stateVar, setter, propName] = m;\n const idx = m.index ?? 0;\n const after = src.slice(idx + full.length);\n if (new RegExp(`\\\\b${setter}\\\\s*\\\\(`).test(after)) continue;\n issues.push(\n mkIssue(\n \"universal.no_prop_mirror\",\n `useState(props.${propName}) for \"${stateVar}\" has no \"${setter}\" call — this mirrors a prop without mutation.`,\n `Read props.${propName} directly in the render; remove the useState for ${stateVar}.`,\n \"warn\",\n ),\n );\n }\n return issues;\n}\n\nfunction runNoPhantomUseState(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const issues: EvalIssue[] = [];\n const re = /const\\s*\\[\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\]\\s*=\\s*useState/g;\n for (const m of src.matchAll(re)) {\n const [full, stateVar, setter] = m;\n const idx = m.index ?? 0;\n const after = src.slice(idx + full.length);\n const stateUsed = new RegExp(`\\\\b${stateVar}\\\\b`).test(after);\n const setterUsed = new RegExp(`\\\\b${setter}\\\\b`).test(after);\n if (stateUsed || setterUsed) continue;\n issues.push(\n mkIssue(\n \"universal.no_phantom_useState\",\n `useState for \"${stateVar}\" is declared but neither \"${stateVar}\" nor \"${setter}\" is referenced.`,\n `Remove the useState for ${stateVar} — it is dead state.`,\n \"warn\",\n ),\n );\n }\n return issues;\n}\n\nexport const UNIVERSAL_CHECKS: readonly AxisCheck[] = [\n {\n id: \"universal.prop_coverage\",\n axis: \"render\",\n values: ALL_RENDER_VALUES,\n run: runPropCoverage,\n },\n {\n id: \"universal.no_prop_mirror\",\n axis: \"render\",\n values: ALL_RENDER_VALUES,\n run: runNoPropMirror,\n },\n {\n id: \"universal.no_phantom_useState\",\n axis: \"render\",\n values: ALL_RENDER_VALUES,\n run: runNoPhantomUseState,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/checks/state-merge.ts\n//\n// Checks gated on state=merge: the component owns a live entity list\n// reconciled from stream/action updates. Ported from\n// mode-checks/collection.ts (§5a state-seeded, no-hardcoded-entities,\n// derived-view-memoized).\n\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport {\n cap,\n getEntityCollections,\n getMutatedEntityCollections,\n mkIssue,\n} from \"../helpers.js\";\n\nfunction runStateSeededFromProps(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const all = getEntityCollections(input.contract);\n const entities = getMutatedEntityCollections(input.contract, all);\n const issues: EvalIssue[] = [];\n for (const e of entities) {\n const re = new RegExp(\n `useState(?:<[^>]*>)?\\\\s*\\\\([\\\\s\\\\S]{0,400}?props\\\\.${e.name}\\\\b`,\n );\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"state.merge.seeded_from_props\",\n `Entity collection \"${e.name}\" is not seeded from props — no useState initializer reads props.${e.name}.`,\n `Add \\`const [${e.name}, set${cap(e.name)}] = useState(props.${e.name});\\` so stream/action updates can merge into live state.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runNoHardcodedEntities(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const all = getEntityCollections(input.contract);\n const entities = getMutatedEntityCollections(input.contract, all);\n if (entities.length === 0) return [];\n const uncommented = src\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/\\/\\/[^\\n]*/g, \"\");\n const issues: EvalIssue[] = [];\n const idFields = [...new Set(entities.map((e) => e.idField))];\n for (const idField of idFields) {\n const re = new RegExp(\n `\\\\[\\\\s*\\\\{[^}]*\\\\b${idField}\\\\s*:[^}]*\\\\}\\\\s*,\\\\s*\\\\{[^}]*\\\\b${idField}\\\\s*:`,\n \"g\",\n );\n if (!re.test(uncommented)) continue;\n issues.push(\n mkIssue(\n \"state.merge.no_hardcoded_entities\",\n `Hardcoded entity array literal (multiple objects with \"${idField}\") in the component — entity data should come from state/props.`,\n `Remove the literal array. Seed state from props.{entityProp} and merge updates via stream.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runDerivedViewMemoized(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const all = getEntityCollections(input.contract);\n const entities = getMutatedEntityCollections(input.contract, all);\n if (entities.length === 0) return [];\n const returnIdx = src.indexOf(\"return (\");\n if (returnIdx < 0) return [];\n const renderBody = src.slice(returnIdx);\n const issues: EvalIssue[] = [];\n for (const e of entities) {\n const re = new RegExp(`\\\\b${e.name}\\\\s*\\\\.(filter|reduce|sort)\\\\s*\\\\(`);\n if (re.test(renderBody)) {\n issues.push(\n mkIssue(\n \"state.merge.derived_view_memoized\",\n `Derived view (${e.name}.filter/reduce/sort) computed inside the render body — should be wrapped in useMemo.`,\n `Extract to \\`const ${e.name}Filtered = useMemo(() => ${e.name}.filter(...), [${e.name}, ...]);\\` before the return.`,\n \"warn\",\n ),\n );\n }\n }\n return issues;\n}\n\n/**\n * `.map()` keyed by index → reorders and merges break React reconciliation.\n * Gated on any render that iterates (list/grid/timeline/master-detail) OR\n * state=merge (mutating list).\n */\nfunction runMapKeyIsId(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const INDEX_NAMES = new Set([\"index\", \"idx\", \"i\", \"j\", \"k\", \"n\", \"ix\"]);\n const re = /key\\s*=\\s*\\{\\s*(\\w+)\\s*\\}/g;\n const issues: EvalIssue[] = [];\n for (const m of src.matchAll(re)) {\n const key = m[1];\n if (!INDEX_NAMES.has(key)) continue;\n issues.push(\n mkIssue(\n \"render.map_key_is_id\",\n `Array key uses index variable \"${key}\" — reorders and stream merges will break React reconciliation.`,\n `Replace key={${key}} with key={item.id} (or item.symbol / whatever the entity id field is).`,\n ),\n );\n }\n return issues;\n}\n\nexport const STATE_MERGE_CHECKS: readonly AxisCheck[] = [\n {\n id: \"state.merge.seeded_from_props\",\n axis: \"state\",\n values: [\"merge\"],\n run: runStateSeededFromProps,\n },\n {\n id: \"state.merge.no_hardcoded_entities\",\n axis: \"state\",\n values: [\"merge\"],\n run: runNoHardcodedEntities,\n },\n {\n id: \"state.merge.derived_view_memoized\",\n axis: \"state\",\n values: [\"merge\"],\n run: runDerivedViewMemoized,\n },\n // Map-key check: gated on any iterating render. state=merge always\n // implies iteration, so the render gate already covers it.\n {\n id: \"render.map_key_is_id\",\n axis: \"render\",\n values: [\"list\", \"grid\", \"timeline\", \"master-detail\"],\n run: runMapKeyIsId,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/checks/realtime.ts\n//\n// Checks gated on realtime != none. Ported from mode-checks/collection.ts\n// (stream-handler-per-event, stream-merges-by-id).\n\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport {\n getEntityCollections,\n getMutatedEntityCollections,\n getStreamEventNames,\n mkIssue,\n} from \"../helpers.js\";\n\nconst REALTIME_ACTIVE = [\"merge\", \"append\", \"status\", \"presence\", \"mixed\"] as const;\n\nfunction runStreamHandlerPerEvent(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const eventNames = getStreamEventNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of eventNames) {\n const re = new RegExp(`useStream(?:<[^>]*>)?\\\\s*\\\\(\\\\s*['\"\\`]${name}['\"\\`]`);\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"realtime.stream_handler_per_event\",\n `Stream event \"${name}\" declared in the contract has no useStream('${name}') call.`,\n `Add \\`const ${name} = useStream<...>('${name}');\\` and handle ${name}.latest in a useEffect.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runStreamMergesById(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const eventNames = getStreamEventNames(input.contract);\n const all = getEntityCollections(input.contract);\n const entities = getMutatedEntityCollections(input.contract, all);\n if (eventNames.length === 0 || entities.length === 0) return [];\n const issues: EvalIssue[] = [];\n const idFields = new Set(entities.map((e) => e.idField));\n for (const idField of idFields) {\n const re = new RegExp(`\\\\.${idField}\\\\b`);\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"realtime.merge.stream_merges_by_id\",\n `Entity id field \"${idField}\" is never referenced in the source — stream merge likely does not key by id.`,\n `In the stream handler, merge by id: setItems(prev => prev.map(x => x.${idField} === update.${idField} ? {...x, ...update} : x)).`,\n \"warn\",\n ),\n );\n }\n return issues;\n}\n\nexport const REALTIME_CHECKS: readonly AxisCheck[] = [\n {\n id: \"realtime.stream_handler_per_event\",\n axis: \"realtime\",\n values: REALTIME_ACTIVE,\n run: runStreamHandlerPerEvent,\n },\n {\n id: \"realtime.merge.stream_merges_by_id\",\n axis: \"realtime\",\n values: [\"merge\", \"mixed\"],\n run: runStreamMergesById,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/checks/writes.ts\n//\n// Checks gated on writes != none. Ported from display.ts (action-hook,\n// action-handler) + form.ts (submit-hook, submit-handler, submit-disabled)\n// + collection.ts (per-item action variants).\n\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport {\n getActionNames,\n getSubmitActions,\n mkIssue,\n} from \"../helpers.js\";\n\nconst ACTIVE_WRITES = [\n \"commit\", \"multi-commit\", \"per-item\", \"submit\", \"compose\",\n] as const;\n\nfunction runActionHookWired(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const actionNames = getActionNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of actionNames) {\n const re = new RegExp(`useAction(?:<[^>]*>)?\\\\s*\\\\(\\\\s*['\"\\`]${name}['\"\\`]`);\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"writes.action_hook_wired\",\n `Contract action \"${name}\" has no useAction('${name}') call.`,\n `Add \\`const ${name} = useAction<...>('${name}');\\` and wire it to the relevant control.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runActionHandlerAttached(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const actionNames = getActionNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of actionNames) {\n const declRe = new RegExp(\n `const\\\\s+(\\\\w+)\\\\s*=\\\\s*useAction(?:<[^>]*>)?\\\\s*\\\\(\\\\s*['\"\\`]${name}['\"\\`]`,\n );\n const m = src.match(declRe);\n if (!m) continue;\n const constName = m[1];\n const rest = src.replace(m[0], \"\");\n if (new RegExp(`\\\\b${constName}\\\\s*\\\\(`).test(rest)) continue;\n issues.push(\n mkIssue(\n \"writes.action_handler_attached\",\n `useAction result \"${constName}\" (for action \"${name}\") is declared but never invoked.`,\n `Call ${constName}({...}) from an interactive element (e.g., <Button onClick={() => ${constName}(payload)}>).`,\n ),\n );\n }\n return issues;\n}\n\nfunction runSubmitDisabledPath(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const submits = getSubmitActions(input.contract);\n if (submits.length === 0) return [];\n if (/disabled\\s*=\\s*\\{/.test(src)) return [];\n return [\n mkIssue(\n \"writes.submit.disabled_path\",\n `Form has no \\`disabled={...}\\` expression anywhere — submit is likely unconditional.`,\n `Gate submit on validation: e.g. \\`<Button disabled={!isValid} onClick={handleSubmit}>\\`.`,\n \"warn\",\n ),\n ];\n}\n\nexport const WRITES_CHECKS: readonly AxisCheck[] = [\n {\n id: \"writes.action_hook_wired\",\n axis: \"writes\",\n values: ACTIVE_WRITES,\n run: runActionHookWired,\n },\n {\n id: \"writes.action_handler_attached\",\n axis: \"writes\",\n values: ACTIVE_WRITES,\n run: runActionHandlerAttached,\n },\n {\n id: \"writes.submit.disabled_path\",\n axis: \"writes\",\n values: [\"submit\"],\n run: runSubmitDisabledPath,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/checks/state-payload.ts\n//\n// Checks gated on state=payload or writes=submit. Ported from\n// mode-checks/form.ts (submit-hook, submit-handler, state-covers-payload,\n// initial-values-seeded, option-lists-consumed, no-orphan-payload-key).\n\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport {\n collectStateKeys,\n getArrStrProps,\n getInitialValuePropNames,\n getSubmitActions,\n mkIssue,\n} from \"../helpers.js\";\n\nfunction runSubmitHookPresent(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const submits = getSubmitActions(input.contract);\n const issues: EvalIssue[] = [];\n for (const s of submits) {\n const re = new RegExp(`useAction(?:<[^>]*>)?\\\\s*\\\\(\\\\s*['\"\\`]${s.name}['\"\\`]`);\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"writes.submit.hook_present\",\n `Submit action \"${s.name}\" has no useAction('${s.name}') call.`,\n `Add \\`const ${s.name} = useAction<...>('${s.name}');\\` and invoke it from the submit button.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runSubmitHandlerAttached(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const submits = getSubmitActions(input.contract);\n const issues: EvalIssue[] = [];\n for (const s of submits) {\n const declRe = new RegExp(\n `const\\\\s+(\\\\w+)\\\\s*=\\\\s*useAction(?:<[^>]*>)?\\\\s*\\\\(\\\\s*['\"\\`]${s.name}['\"\\`]`,\n );\n const m = src.match(declRe);\n if (!m) continue;\n const constName = m[1];\n const rest = src.replace(m[0], \"\");\n if (new RegExp(`\\\\b${constName}\\\\s*\\\\(`).test(rest)) continue;\n issues.push(\n mkIssue(\n \"writes.submit.handler_attached\",\n `useAction result \"${constName}\" (for submit \"${s.name}\") is declared but never invoked.`,\n `Call ${constName}(payload) from the submit button's onClick handler, after validation.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runStateCoversPayload(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const submits = getSubmitActions(input.contract);\n if (submits.length === 0) return [];\n const stateKeys = collectStateKeys(src);\n const issues: EvalIssue[] = [];\n for (const s of submits) {\n const missing = s.payloadKeys.filter((k) => !stateKeys.has(k));\n if (missing.length === 0) continue;\n issues.push(\n mkIssue(\n \"state.payload.covers_submit\",\n `Submit action \"${s.name}\" expects payload keys [${s.payloadKeys.join(\", \")}] but state does not cover: ${missing.join(\", \")}.`,\n `Add a state slot for each missing key so the final payload can be assembled.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runInitialValuesSeeded(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const initialProps = getInitialValuePropNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of initialProps) {\n const re = new RegExp(\n `useState(?:<[^>]*>)?\\\\s*\\\\([\\\\s\\\\S]{0,400}?props\\\\.${name}\\\\b`,\n );\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"state.payload.initial_values_seeded\",\n `Prop \"${name}\" (pre-filled initial values) is never read in a useState initializer.`,\n `Seed form state from props.${name} so edit mode pre-fills.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runOptionListsConsumed(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const arrStrNames = getArrStrProps(input.contract);\n const hasAnyMap = /\\.map\\s*\\(/.test(src);\n const issues: EvalIssue[] = [];\n for (const name of arrStrNames) {\n const referenced = new RegExp(`\\\\bprops\\\\.${name}\\\\b`).test(src);\n if (referenced && hasAnyMap) continue;\n const reason = !referenced\n ? `Option list prop \"${name}\" (arr<str>) is never referenced — users cannot see the options.`\n : `Option list prop \"${name}\" (arr<str>) is referenced but the component has no .map() — options are not rendered as choices.`;\n issues.push(\n mkIssue(\n \"state.payload.option_lists_consumed\",\n reason,\n `Render options with \\`props.${name}.map(option => <RadioOption value={option} ... />)\\`.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runNoOrphanPayloadKey(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const submits = getSubmitActions(input.contract);\n if (submits.length === 0) return [];\n const body = src\n .replace(/interface\\s+Action\\w+[\\s\\S]*?\\n}/g, \"\")\n .replace(/type\\s+Action\\w+[\\s\\S]*?\\n;/g, \"\");\n const issues: EvalIssue[] = [];\n for (const s of submits) {\n const orphans: string[] = [];\n for (const key of s.payloadKeys) {\n const re = new RegExp(`\\\\b${key}\\\\b`);\n if (!re.test(body)) orphans.push(key);\n }\n if (orphans.length === 0) continue;\n issues.push(\n mkIssue(\n \"state.payload.no_orphan_key\",\n `Submit payload keys [${orphans.join(\", \")}] never appear in the component body — missing from the submitted payload.`,\n `Add UI and state for these keys, or remove them from the ActionEntry if not needed.`,\n \"warn\",\n ),\n );\n }\n return issues;\n}\n\nexport const STATE_PAYLOAD_CHECKS: readonly AxisCheck[] = [\n {\n id: \"writes.submit.hook_present\",\n axis: \"writes\",\n values: [\"submit\"],\n run: runSubmitHookPresent,\n },\n {\n id: \"writes.submit.handler_attached\",\n axis: \"writes\",\n values: [\"submit\"],\n run: runSubmitHandlerAttached,\n },\n {\n id: \"state.payload.covers_submit\",\n axis: \"state\",\n values: [\"payload\"],\n run: runStateCoversPayload,\n },\n {\n id: \"state.payload.initial_values_seeded\",\n axis: \"state\",\n values: [\"payload\", \"draft\"],\n run: runInitialValuesSeeded,\n },\n {\n id: \"state.payload.option_lists_consumed\",\n axis: \"state\",\n values: [\"payload\"],\n run: runOptionListsConsumed,\n },\n {\n id: \"state.payload.no_orphan_key\",\n axis: \"state\",\n values: [\"payload\"],\n run: runNoOrphanPayloadKey,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/checks/tooling.ts\n//\n// Checks gated on the tooling axis. Two surfaces:\n//\n// - `tooling.clientCapability.hook_called` — verifies every declared\n// `clientCapabilities.gadgets[name]` has a matching\n// `const <name> = …()` binding in source.\n// - `tooling.clientCapability.start_called` — verifies a bound\n// gadget hook also has a `.start(...)` invocation; without it\n// the capability stays in `idle` and never fires.\n// - `realtime.stream_source.no_direct_call` — the LLM must NOT\n// directly invoke a tool named on `streamSpec[*].source.tool`;\n// subscribe via `useStream(...)` instead.\n// - `universal.no_retired_identifiers` — fires on every contract.\n// The LLM's training data predates the current wire shape and\n// reaches for retired identifiers (component-side tool hooks,\n// dispatch.kind, intendedTool, broadcast field, retired catalog\n// names, retired package imports, retired wire-input fields).\n// The grep gate emits one issue per detected identifier so the\n// LLM rewrites toward the current shape before evaluation\n// completes.\n\nimport type { DataContract, StreamChannelEntry } from \"@ggui-ai/protocol\";\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport { getGadgetNames, getStdlibGadgetNames, mkIssue } from \"../helpers.js\";\n\nconst CLIENT_PRESENT = [\"client\", \"both\"] as const;\nconst ALL_TOOLING_VALUES = [\"none\", \"wired\", \"client\", \"both\"] as const;\nconst REALTIME_ACTIVE = [\n \"merge\",\n \"append\",\n \"status\",\n \"presence\",\n \"mixed\",\n] as const;\n\n// ── clientCapabilities ──────────────────────────────────────────────\n\nfunction runGadgetHookCalled(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const names = getGadgetNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of names) {\n // The boilerplate emits `const <name> = <hook>();` — match the const\n // binding to detect omission. We don't pin the hook identifier here\n // because the contract carries it via `entry.hook` and the LLM may\n // legitimately alias on import.\n const re = new RegExp(`const\\\\s+${name}\\\\s*=`);\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"tooling.clientCapability.hook_called\",\n `Contract clientCapability \"${name}\" has no \\`const ${name} = …()\\` hook call.`,\n `Import the declared hook (default package: @ggui-ai/gadgets) and bind its return value to \\`const ${name}\\` at the top of the component; surface \\`.value\\` / \\`.status\\` in JSX.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runClientCapabilityStartCalled(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n // Only the first-party `@ggui-ai/gadgets` browser capabilities have\n // the `idle → prompting → active` lifecycle that `.start()` drives.\n // Registered third-party gadget hooks (e.g. `useBoardState`) are\n // plain data hooks the runtime resolves on its own — exclude them.\n const names = getStdlibGadgetNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of names) {\n // Skip when the binding doesn't exist — the `hook_called` check\n // covers that case; we don't double-issue.\n const bindingRe = new RegExp(`const\\\\s+${name}\\\\s*=`);\n if (!bindingRe.test(src)) continue;\n\n // The capability lifecycle requires `.start()` invocation to\n // transition from `idle` → `prompting`. Without it the hook's\n // `.value` / `.status` stay frozen at the initial state and the\n // UI feature never fires. Match `<name>.start(`, allowing chained\n // member access or method aliasing.\n const startRe = new RegExp(`\\\\b${name}\\\\s*\\\\.\\\\s*start\\\\s*\\\\(`);\n if (startRe.test(src)) continue;\n issues.push(\n mkIssue(\n \"tooling.clientCapability.start_called\",\n `clientCapability \"${name}\" is bound but \\`${name}.start(…)\\` is never invoked — the capability stays in 'idle' and the feature won't fire.`,\n `Wire \\`${name}.start({...})\\` to a UI control (Button onClick, effect, etc.). Read \\`.status\\` to gate the UI between 'idle' / 'prompting' / 'active' / 'completed' / 'denied' / 'error'.`,\n ),\n );\n }\n return issues;\n}\n\n// ── streamSpec sources ──────────────────────────────────────────────\n\nfunction collectStreamSourceTools(\n contract: DataContract | undefined,\n): Map<string, string> {\n // Map<channelName, sourceToolName> for every channel that declares\n // a source. Excludes channels without `source` (agent-written).\n const result = new Map<string, string>();\n const streamSpec = contract?.streamSpec;\n if (!streamSpec || typeof streamSpec !== \"object\") return result;\n for (const [channelName, entryRaw] of Object.entries(streamSpec)) {\n const entry = entryRaw as StreamChannelEntry | undefined;\n if (!entry || typeof entry !== \"object\") continue;\n const tool = entry.source?.tool;\n if (typeof tool !== \"string\" || tool.length === 0) continue;\n result.set(channelName, tool);\n }\n return result;\n}\n\nfunction runStreamSourceNoDirectCall(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const map = collectStreamSourceTools(input.contract);\n if (map.size === 0) return [];\n\n const issues: EvalIssue[] = [];\n for (const [channelName, toolName] of map) {\n // Detect a direct call to the source tool. Matches identifier\n // followed by `(` — covers `foo()`, `foo(args)`, `foo.bar()`\n // (the dotted form indirectly catches `someObject.foo()` which\n // the contract doesn't expect to see, since the source tool is\n // an agent-side MCP tool, not a local function).\n const callRe = new RegExp(`\\\\b${toolName}\\\\s*\\\\(`);\n if (!callRe.test(src)) continue;\n\n // Don't false-fire when `toolName` happens to be the channel name\n // bound to useStream (e.g., `const messages = useStream(...)` then\n // `messages(...)` would be weird but we're matching the TOOL name,\n // not the binding). If toolName === channelName then the\n // `<channel>(` call would be the useStream binding being called\n // as a function — which is itself wrong, so still emit.\n issues.push(\n mkIssue(\n \"realtime.stream_source.no_direct_call\",\n `Source code calls \\`${toolName}(...)\\` directly but the contract declares it as the source tool for streamSpec.${channelName}. Source tools are agent-side / runtime-polled; the component MUST NOT invoke them.`,\n `Subscribe to the channel via \\`const ${channelName} = useStream('${channelName}');\\` and read \\`${channelName}.latest\\` / \\`${channelName}.all\\` — the runtime polls or subscribes to '${toolName}' on the component's behalf.`,\n ),\n );\n }\n return issues;\n}\n\n// ── Anti-pattern grep — retired identifiers a model may emit from\n// stale training data ──\n\ninterface RetiredIdentifier {\n /** Regex matching the retired surface in source. */\n readonly pattern: RegExp;\n /** Stable subcategory used for the EvalIssue. */\n readonly id: string;\n /** Human-readable description for the issue message. */\n readonly label: string;\n /** Replacement guidance for the fix message. */\n readonly replacement: string;\n}\n\nconst RETIRED_IDENTIFIERS: readonly RetiredIdentifier[] = [\n {\n pattern: /\\buseWiredTool\\b/,\n id: \"useWiredTool\",\n label: \"`useWiredTool(...)` hook\",\n replacement:\n \"Use `useAction(name)` for user gestures the agent should react to. `agentCapabilities.tools` entries are agent-side catalog declarations — the component never calls them directly.\",\n },\n {\n pattern: /\\buseAgentTool\\b/,\n id: \"useAgentTool\",\n label: \"`useAgentTool(...)` hook\",\n replacement:\n \"Agent-side tools are NEVER imported as component hooks. The contract declares them under `agentCapabilities.tools` for cross-ref (actionSpec.nextStep / streamSpec.source.tool); the component reacts via `useAction` / `useStream`.\",\n },\n {\n pattern: /\\bcallWiredTool\\b/,\n id: \"callWiredTool\",\n label: \"`callWiredTool(...)` call\",\n replacement:\n \"Component-side direct invocation of agent-side tools is retired. Fire a UI gesture via `useAction(name)`; the agent reacts on its next turn (`nextStep` hint optional).\",\n },\n {\n pattern: /\\buseClientTool\\b/,\n id: \"useClientTool\",\n label: \"`useClientTool(name, handler)` hook\",\n replacement:\n \"Use a gadget hook from `@ggui-ai/gadgets` (e.g., `useGeolocation`, `useClipboardWrite`) and thread the result into a contextSpec slot or actionSpec payload.\",\n },\n {\n pattern: /\\bdispatch\\s*:\\s*\\{\\s*kind\\s*:/,\n id: \"dispatch.kind\",\n label: \"`dispatch: { kind: '...' }` discriminated union\",\n replacement:\n \"ActionEntry.dispatch is retired. Use the flat `nextStep?: '<tool>'` field on the action entry instead.\",\n },\n {\n pattern: /\\bintendedTool\\b/,\n id: \"intendedTool\",\n label: \"`intendedTool` field\",\n replacement:\n \"Use the flat `nextStep` field — the hint surface is one optional advisory string, not a nested discriminator.\",\n },\n {\n pattern: /\\bmode\\s*:\\s*['\"`]host-routed['\"`]/,\n id: \"mode.host-routed\",\n label: \"`mode: 'host-routed'`\",\n replacement:\n \"The `mode` field on action entries is retired. All actions are agent-routed; use `nextStep` for the optional tool hint.\",\n },\n {\n pattern: /\\bbroadcast\\s*:\\s*\\{/,\n id: \"broadcast\",\n label: \"`broadcast: { … }` contract field\",\n replacement:\n \"Move the channel source declaration to `streamSpec[channel].source = { tool, args? }`.\",\n },\n {\n // Match `agentTools` only as a contract-shaped object key or\n // property access — not as a local variable name in unrelated\n // code. `\\bagentTools\\s*[:.]` catches `{ agentTools: {...} }` /\n // `contract.agentTools` while ignoring `const agentTools = ...`.\n pattern: /\\bagentTools\\s*[:.]/,\n id: \"contract.agentTools\",\n label: \"`agentTools` top-level contract field\",\n replacement:\n \"The top-level `agentTools` field is retired. Declare agent-side tools under `agentCapabilities.tools` (catalog nested under a capabilities parent for symmetry with `clientCapabilities`).\",\n },\n {\n pattern: /\\bclientCapabilities\\s*\\.\\s*capabilities\\b/,\n id: \"clientCapabilities.capabilities\",\n label: \"`clientCapabilities.capabilities` inner key\",\n replacement:\n \"The inner `capabilities` key is retired. Use `clientCapabilities.gadgets` — entries are library-hook declarations, not RPC capabilities.\",\n },\n {\n pattern: /['\"`]@ggui-ai\\/client-tools['\"`]/,\n id: \"package.@ggui-ai/client-tools\",\n label: \"`@ggui-ai/client-tools` package import\",\n replacement:\n \"The package was renamed to `@ggui-ai/gadgets`. Update the import string.\",\n },\n {\n pattern: /\\bPushStory\\b/,\n id: \"PushStory\",\n label: \"`PushStory` type / `pushStorySchema` schema\",\n replacement:\n \"`PushStory` was retired when the handshake input was flattened. The current wire is `ggui_handshake({intent, blueprintDraft: {contract, variance?, generator?}})` + `ggui_render({handshakeId, props, override?: {contract?, variance?}})` (omit `override` to accept the proposal as-is).\",\n },\n {\n pattern: /\\bpushStorySchema\\b/,\n id: \"pushStorySchema\",\n label: \"`pushStorySchema` zod schema\",\n replacement:\n \"`pushStorySchema` was retired alongside `PushStory`. Current schemas: `handshakeInputSchema` + `renderInputSchema` (with the optional `override` re-aim) in `@ggui-ai/protocol`.\",\n },\n {\n pattern: /\\bstory\\s*\\.\\s*adapters\\b/,\n id: \"story.adapters\",\n label: \"`story.adapters` field access\",\n replacement:\n \"The story.adapters gate was retired alongside `PushStory`. Per-app permission gates flow through `clientCapabilities.gadgets[*].permission` (Permissions-Policy derivation).\",\n },\n {\n pattern: /\\bdeclaredAdapters\\b/,\n id: \"declaredAdapters\",\n label: \"`declaredAdapters` field / runtime gate\",\n replacement:\n \"App-level `declaredAdapters` was retired. Per-app permission gates derive from `clientCapabilities.gadgets[*].permission` instead.\",\n },\n {\n pattern: /\\bassertAdaptersDeclared\\b/,\n id: \"assertAdaptersDeclared\",\n label: \"`assertAdaptersDeclared(...)` runtime call\",\n replacement:\n \"The runtime adapter-gate function is retired. Permissions-Policy is derived per-contract at render commit time and threaded through the bootstrap projection.\",\n },\n {\n pattern: /\\bHandshakeStoredStory\\b/,\n id: \"HandshakeStoredStory\",\n label: \"`HandshakeStoredStory` storage type\",\n replacement:\n \"The OSS handler's stored type is now `HandshakeStoredInput` with the MVB-5 `{intent, blueprintDraft, forceCreate?}` shape.\",\n },\n {\n pattern: /\\brecord\\s*\\.\\s*story\\b/,\n id: \"record.story\",\n label: \"`record.story.*` access on handshake storage\",\n replacement:\n \"Handshake storage was flattened. Read `record.input.*` (intent / blueprintDraft) — the nested `story` wrapper is gone. MVB-5 also adds `record.suggestion` + `record.effectiveContract`.\",\n },\n];\n\nfunction runNoRetiredIdentifiers(input: AxisCheckInput): EvalIssue[] {\n // Source-only scan; compiled code irrelevant for identifier detection.\n // Run even without compiled code so we surface early in the loop.\n const src = input.sourceCode;\n const issues: EvalIssue[] = [];\n for (const rule of RETIRED_IDENTIFIERS) {\n if (!rule.pattern.test(src)) continue;\n issues.push(\n mkIssue(\n `universal.no_retired_identifiers.${rule.id}`,\n `Source contains ${rule.label} — retired from the contract surface.`,\n rule.replacement,\n ),\n );\n }\n return issues;\n}\n\nexport const TOOLING_CHECKS: readonly AxisCheck[] = [\n {\n id: \"tooling.clientCapability.hook_called\",\n axis: \"tooling\",\n values: CLIENT_PRESENT,\n run: runGadgetHookCalled,\n },\n {\n id: \"tooling.clientCapability.start_called\",\n axis: \"tooling\",\n values: CLIENT_PRESENT,\n run: runClientCapabilityStartCalled,\n },\n {\n // Stream-source direct-call check. Gated on realtime axis (rather\n // than tooling) since stream sources are a realtime concern — but\n // logically lives in tooling.ts alongside the other tool-reference\n // checks since the issue class is about referenced agentTools.\n id: \"realtime.stream_source.no_direct_call\",\n axis: \"realtime\",\n values: REALTIME_ACTIVE,\n run: runStreamSourceNoDirectCall,\n },\n {\n // Universal — fires on every tooling-axis value. The check itself\n // is contract-agnostic; the axis gate is \"every contract\" via the\n // full ALL_TOOLING_VALUES list (rather than the universal-check\n // module's \"render\" gate convention) so the anti-pattern stays\n // co-located with the other tooling-related rules.\n id: \"universal.no_retired_identifiers\",\n axis: \"tooling\",\n values: ALL_TOOLING_VALUES,\n run: runNoRetiredIdentifiers,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/extras.ts\n//\n// Axis-specific checks that had no legacy home. These fire on axis values\n// the old 3-mode dispatch didn't route (drag, swipe, compose, multi-step,\n// mixed streams). Intentionally narrow — each catches a specific failure\n// mode the fragments' prompt text tells the LLM to avoid.\n\nimport type { AxisCheck, AxisCheckInput } from \"./types.js\";\nimport type { EvalIssue } from \"../types-public.js\";\n\nfunction mkIssue(\n subcategory: string,\n description: string,\n fix: string,\n result: \"fail\" | \"warn\" = \"warn\",\n): EvalIssue {\n return { tier: 0, result, category: \"mode\", subcategory, description, fix };\n}\n\n/**\n * writeTrigger=drag → must attach onDragStart + onDrop (or onDragOver)\n * somewhere. Otherwise the drag handler is decorative.\n */\nconst dragTriggerWired: AxisCheck = {\n id: \"writeTrigger.drag.handlers_wired\",\n axis: \"writeTrigger\",\n values: [\"drag\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const hasStart = /onDragStart\\s*=/.test(src);\n const hasDrop = /onDrop\\s*=/.test(src);\n if (hasStart && hasDrop) return [];\n return [\n mkIssue(\n \"writeTrigger.drag.handlers_wired\",\n `Classified as writeTrigger=drag but component lacks ${!hasStart ? \"onDragStart\" : \"\"}${!hasStart && !hasDrop ? \" + \" : \"\"}${!hasDrop ? \"onDrop\" : \"\"} handlers.`,\n \"Attach onDragStart to draggable items and onDrop (with onDragOver preventDefault) to drop zones.\",\n \"fail\",\n ),\n ];\n },\n};\n\n/**\n * writeTrigger=swipe → must wire onTouchStart + onTouchEnd. Also emit\n * a warn if no fallback click handlers exist (desktop users).\n */\nconst swipeTriggerWired: AxisCheck = {\n id: \"writeTrigger.swipe.handlers_wired\",\n axis: \"writeTrigger\",\n values: [\"swipe\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const hasTouch = /onTouchStart\\s*=/.test(src) && /onTouchEnd\\s*=/.test(src);\n if (!hasTouch) {\n return [\n mkIssue(\n \"writeTrigger.swipe.handlers_wired\",\n \"Classified as writeTrigger=swipe but component lacks onTouchStart + onTouchEnd handlers.\",\n \"Wire onTouchStart to record the start X/Y, onTouchEnd to classify direction and fire the action.\",\n \"fail\",\n ),\n ];\n }\n return [];\n },\n};\n\n/**\n * writes=compose → exactly one action should be called with ids sourced\n * from two different state slots. Heuristic: at least two useState or\n * props.id references should appear in the action invocation's argument\n * region.\n *\n * Light check: warn if only one id-bearing field appears near the useAction\n * invocation (hard to get false-positive free without AST).\n */\nconst composeCrossEntity: AxisCheck = {\n id: \"writes.compose.cross_entity_ids\",\n axis: \"writes\",\n values: [\"compose\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n // Look for an action invocation passing an object literal with >= 2\n // `*Id` or `id` keys. That's the compose signature.\n const re = /\\{\\s*[^}]*?\\b(\\w*Id|id)\\b[^}]*?,\\s*[^}]*?\\b(\\w*Id|id)\\b[^}]*?\\}/s;\n if (re.test(src)) return [];\n return [\n mkIssue(\n \"writes.compose.cross_entity_ids\",\n \"Classified as writes=compose but no action invocation passes two id-bearing keys together.\",\n \"The compose action must receive both entity ids in one payload, e.g. `schedule({ eventId, calendarId })`.\",\n \"warn\",\n ),\n ];\n },\n};\n\n/**\n * layout=multi-step → integer step state + a step-guard on Next. Re-uses\n * the form check's multi-step signal, but fires even when writes != submit\n * (e.g., multi-step wizards that never submit, like onboarding).\n */\nconst multiStepHasState: AxisCheck = {\n id: \"layout.multi_step.state_present\",\n axis: \"layout\",\n values: [\"multi-step\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const hasIntStep = /useState(?:<number>)?\\s*\\(\\s*[0-9]+\\s*\\)/.test(src);\n if (hasIntStep) return [];\n return [\n mkIssue(\n \"layout.multi_step.state_present\",\n \"Classified as layout=multi-step but no integer-typed useState tracks the current step.\",\n \"Add `const [step, setStep] = useState(0);` and branch rendering on it.\",\n \"fail\",\n ),\n ];\n },\n};\n\n/**\n * layout=multi-step → the design system's Stepper composite must be\n * ADOPTED (rendered). D8 (Exp 47) measured adoption at 17/18 from\n * fragment + JSDoc alone; this check gives the CHECK leg ownership of\n * the mandate so a regression surfaces as a fix turn instead of\n * silently shipping a wizard with no step affordance.\n *\n * Replaces the always-on `stepper-display-only` pitfall (deleted in the\n * same slice): with adoption carried by the WHAT leg, a 6th always-on\n * prompt rule was pure attention-dilution cost (the exp66 count-\n * sensitivity class, ~+9s blended), while this check prices at zero\n * outside multi-step cells. The pitfall's display-only guidance lives\n * on in the fix string below — delivered only when a cell actually\n * needs it.\n */\nconst stepperAdopted: AxisCheck = {\n id: \"layout.multi_step.stepper_adopted\",\n axis: \"layout\",\n values: [\"multi-step\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n if (/<Stepper[\\s/>]/.test(input.sourceCode)) return [];\n return [\n mkIssue(\n \"layout.multi_step.stepper_adopted\",\n \"Classified as layout=multi-step but the design system's Stepper composite is never rendered.\",\n \"Render <Stepper steps={STEPS} current={step} /> above the step body — STEPS is a top-level const array of step labels and `step` is your own useState index. Stepper is display-only: it never stores or advances the step itself.\",\n \"fail\",\n ),\n ];\n },\n};\n\n/**\n * realtime=mixed → the contract declares multiple events of different\n * kinds. Each must have its own useStream call. We approximate by\n * requiring ≥ 2 useStream calls when the vector is mixed.\n */\nconst mixedStreamsHaveHandlers: AxisCheck = {\n id: \"realtime.mixed.handlers_per_event\",\n axis: \"realtime\",\n values: [\"mixed\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n // Accept both `useStream('x')` and `useStream<T>('x')` (generic type arg).\n // The boilerplate pre-emits typed calls, so the `(` -only regex was a\n // 100%-false-positive on chat-interface + stock-ticker (Experiment 34).\n const matches = src.match(/useStream\\s*(?:<[^>]*>)?\\s*\\(/g);\n const count = matches?.length ?? 0;\n if (count >= 2) return [];\n return [\n mkIssue(\n \"realtime.mixed.handlers_per_event\",\n `Classified as realtime=mixed but only ${count} useStream call(s) found — mixed streams need one handler per event.`,\n \"Add a separate `useStream('eventName')` for each event in the contract.\",\n \"fail\",\n ),\n ];\n },\n};\n\nexport const EXTRA_CHECKS: readonly AxisCheck[] = [\n dragTriggerWired,\n swipeTriggerWired,\n composeCrossEntity,\n multiStepHasState,\n stepperAdopted,\n mixedStreamsHaveHandlers,\n];\n","// packages/ui-gen/src/evaluation/axis-checks/registry.ts\n//\n// Flat list of all axis-gated checks. The dispatcher iterates this and\n// runs every entry whose gate matches the classification's axis vector.\n\nimport type { AxisCheck } from \"./types.js\";\nimport { UNIVERSAL_CHECKS } from \"./checks/universal.js\";\nimport { STATE_MERGE_CHECKS } from \"./checks/state-merge.js\";\nimport { REALTIME_CHECKS } from \"./checks/realtime.js\";\nimport { WRITES_CHECKS } from \"./checks/writes.js\";\nimport { STATE_PAYLOAD_CHECKS } from \"./checks/state-payload.js\";\nimport { TOOLING_CHECKS } from \"./checks/tooling.js\";\nimport { EXTRA_CHECKS } from \"./extras.js\";\n\nexport const REGISTRY: readonly AxisCheck[] = [\n ...UNIVERSAL_CHECKS,\n ...STATE_MERGE_CHECKS,\n ...REALTIME_CHECKS,\n ...WRITES_CHECKS,\n ...STATE_PAYLOAD_CHECKS,\n ...TOOLING_CHECKS,\n ...EXTRA_CHECKS,\n];\n","// Axis-keyed dispatcher. Iterates the flat REGISTRY, runs each check\n// whose gate matches the classification's axis vector, and accumulates\n// issues.\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { Classification } from \"../../classifier/index.js\";\nimport type { EvalIssue } from \"../types-public.js\";\nimport { REGISTRY } from \"./registry.js\";\nimport { matches, type AxisCheckInput } from \"./types.js\";\n\nexport interface RunAxisChecksInput {\n sourceCode: string;\n compiledCode: string | null;\n contract?: DataContract;\n originalPrompt: string;\n}\n\nexport function runAxisChecks(\n classification: Classification,\n input: RunAxisChecksInput,\n): EvalIssue[] {\n if (input.compiledCode === null) return [];\n\n const axisInput: AxisCheckInput = {\n sourceCode: input.sourceCode,\n compiledCode: input.compiledCode,\n ...(input.contract !== undefined ? { contract: input.contract } : {}),\n originalPrompt: input.originalPrompt,\n classification,\n };\n\n const issues: EvalIssue[] = [];\n const firedIds = new Set<string>();\n for (const check of REGISTRY) {\n if (!matches(classification.vector, check)) continue;\n // Dedup by id — a check may be registered under multiple gates.\n if (firedIds.has(check.id)) continue;\n firedIds.add(check.id);\n issues.push(...check.run(axisInput));\n }\n return issues;\n}\n"]}
1
+ {"version":3,"sources":["../../src/adapters/openrouter/types.ts","../../src/adapters/openrouter/client.ts","../../src/evaluation/types-public.ts","../../src/adapters/claude/client.ts","../../src/adapters/provider-router.ts","../../src/adapters/tool-bridge.ts","../../src/harness/llm-trace-sink.ts","../../src/harness/llm-router.ts","../../src/evaluation/evaluator.ts","../../src/evaluation/message-parsing.ts","../../src/evaluation/prompts.ts","../../src/evaluation/types.ts","../../src/evaluation/loop.ts","../../src/evaluation/mcp-server.ts","../../src/evaluation/axis-checks/helpers.ts","../../src/evaluation/axis-checks/checks/universal.ts","../../src/evaluation/axis-checks/checks/state-merge.ts","../../src/evaluation/axis-checks/checks/realtime.ts","../../src/evaluation/axis-checks/checks/writes.ts","../../src/evaluation/axis-checks/checks/state-payload.ts","../../src/evaluation/axis-checks/checks/tooling.ts","../../src/evaluation/axis-checks/extras.ts","../../src/evaluation/axis-checks/registry.ts","../../src/evaluation/axis-checks/dispatch.ts"],"names":["tool","OpenRouterClient","z","REALTIME_ACTIVE","mkIssue","matches"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,IA4Ha,eAAA;AA5Hb,IAAA,UAAA,GAAA,KAAA,CAAA;AAAA,EAAA,kCAAA,GAAA;AA4HO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,MACzC,WAAA,CACE,OAAA,EACgB,MAAA,EACA,IAAA,EAChB;AACA,QAAA,KAAA,CAAM,OAAO,CAAA;AAHG,QAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,QAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,QAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AAAA,MACd;AAAA,MALkB,MAAA;AAAA,MACA,IAAA;AAAA,MAMlB,IAAI,WAAA,GAAuB;AACzB,QAAA,OAAO,IAAA,CAAK,MAAA,KAAW,GAAA,IAAO,IAAA,CAAK,MAAA,KAAW,OACzC,IAAA,CAAK,MAAA,KAAW,GAAA,IAAO,IAAA,CAAK,MAAA,KAAW,GAAA;AAAA,MAC9C;AAAA,KACF;AAAA,EAAA;AAAA,CAAA,CAAA;;;AC1IA,IAAA,cAAA,GAAA,EAAA;AAAA,QAAA,CAAA,cAAA,EAAA;AAAA,EAAA,gBAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAAA,IAmBM,gBAAA,EAEO,gBAAA;AArBb,IAAA,WAAA,GAAA,KAAA,CAAA;AAAA,EAAA,mCAAA,GAAA;AAUA,IAAA,UAAA,EAAA;AASA,IAAM,gBAAA,GAAmB,8BAAA;AAElB,IAAM,mBAAN,MAAuB;AAAA,MAI5B,YAA6B,MAAA,EAAgC;AAAhC,QAAA,IAAA,CAA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B,cAAc,KAAA,CAAM,YAAA;AAAA,IACpB,GAAI,MAAM,QAAA,KAAa,MAAA,GAAY,EAAE,QAAA,EAAU,KAAA,CAAM,QAAA,EAAS,GAAI,EAAC;AAAA,IACnE,gBAAgB,KAAA,CAAM,cAAA;AAAA,IACtB;AAAA,GACF;AAEA,EAAA,MAAM,SAAsB,EAAC;AAC7B,EAAA,MAAM,QAAA,uBAAe,GAAA,EAAY;AACjC,EAAA,KAAA,MAAW,SAAS,QAAA,EAAU;AAC5B,IAAA,IAAI,CAAC,OAAA,CAAQ,cAAA,CAAe,MAAA,EAAQ,KAAK,CAAA,EAAG;AAE5C,IAAA,IAAI,QAAA,CAAS,GAAA,CAAI,KAAA,CAAM,EAAE,CAAA,EAAG;AAC5B,IAAA,QAAA,CAAS,GAAA,CAAI,MAAM,EAAE,CAAA;AACrB,IAAA,MAAA,CAAO,IAAA,CAAK,GAAG,KAAA,CAAM,GAAA,CAAI,SAAS,CAAC,CAAA;AAAA,EACrC;AACA,EAAA,OAAO,MAAA;AACT","file":"index.js","sourcesContent":["// packages/ui-gen/src/adapters/openrouter/types.ts\n//\n// OpenRouter-specific types for the chat completion API.\n// Reference: https://openrouter.ai/docs/api-reference\n\nimport type { JsonObject } from '@ggui-ai/protocol';\n\n// =============================================================================\n// Model metadata (from GET /api/v1/models)\n// =============================================================================\n\n/** Model entry from OpenRouter's /api/v1/models endpoint */\nexport interface OpenRouterModelEntry {\n id: string;\n name: string;\n description: string;\n pricing: { prompt: string; completion: string; image?: string };\n context_length: number;\n architecture: {\n modality: string;\n tokenizer: string;\n instruct_type: string | null;\n };\n top_provider: {\n context_length: number;\n max_completion_tokens: number;\n is_moderated: boolean;\n };\n per_request_limits: Record<string, string> | null;\n}\n\n// =============================================================================\n// Chat Completion API\n// =============================================================================\n\nexport interface OpenRouterMessage {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string | OpenRouterContentBlock[] | null;\n tool_calls?: OpenRouterToolCall[];\n tool_call_id?: string;\n}\n\nexport interface OpenRouterContentBlock {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral' };\n}\n\nexport interface OpenRouterTool {\n type: 'function';\n function: {\n name: string;\n description: string;\n parameters: JsonObject;\n };\n}\n\nexport interface OpenRouterToolCall {\n id: string;\n type: 'function';\n function: { name: string; arguments: string };\n}\n\nexport interface OpenRouterChatRequest {\n model: string;\n messages: OpenRouterMessage[];\n tools?: OpenRouterTool[];\n tool_choice?: 'auto' | 'required' | 'none';\n max_tokens?: number;\n temperature?: number;\n stream?: boolean;\n thinking?: { type: 'enabled'; budget_tokens: number };\n}\n\nexport interface OpenRouterChatResponse {\n id: string;\n model: string;\n choices: Array<{\n index: number;\n message: {\n role: 'assistant';\n content: string | null;\n tool_calls?: OpenRouterToolCall[];\n thinking?: string;\n };\n finish_reason: string;\n }>;\n usage: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n };\n}\n\n// =============================================================================\n// SSE Streaming\n// =============================================================================\n\nexport interface OpenRouterStreamDelta {\n id: string;\n model: string;\n choices: Array<{\n index: number;\n delta: {\n role?: 'assistant';\n content?: string | null;\n tool_calls?: Array<{\n index: number;\n id?: string;\n type?: 'function';\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason: string | null;\n }>;\n usage?: OpenRouterChatResponse['usage'];\n}\n\n// =============================================================================\n// Error\n// =============================================================================\n\nexport class OpenRouterError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code?: string,\n ) {\n super(message);\n this.name = 'OpenRouterError';\n }\n\n get isTransient(): boolean {\n return this.status === 408 || this.status === 429\n || this.status === 502 || this.status === 503;\n }\n}\n","// packages/ui-gen/src/adapters/openrouter/client.ts\n//\n// Direct fetch()-based HTTP client for OpenRouter's API.\n// No OpenAI SDK dependency — independent implementation.\n\nimport type {\n OpenRouterChatRequest,\n OpenRouterChatResponse,\n OpenRouterStreamDelta,\n} from './types';\nimport { OpenRouterError } from './types';\n\nexport interface OpenRouterClientConfig {\n apiKey: string;\n baseUrl?: string;\n siteUrl?: string;\n siteName?: string;\n}\n\nconst DEFAULT_BASE_URL = 'https://openrouter.ai/api/v1';\n\nexport class OpenRouterClient {\n private readonly baseUrl: string;\n private readonly headers: Record<string, string>;\n\n constructor(private readonly config: OpenRouterClientConfig) {\n this.baseUrl = config.baseUrl ?? process.env.OPENROUTER_BASE_URL ?? DEFAULT_BASE_URL;\n this.headers = {\n 'Authorization': `Bearer ${config.apiKey}`,\n 'Content-Type': 'application/json',\n 'HTTP-Referer': config.siteUrl ?? process.env.OPENROUTER_SITE_URL ?? 'https://ggui.ai',\n 'X-Title': config.siteName ?? process.env.OPENROUTER_SITE_NAME ?? 'ggui',\n };\n }\n\n /**\n * Non-streaming chat completion.\n */\n async chatCompletion(\n params: Omit<OpenRouterChatRequest, 'stream'>,\n ): Promise<OpenRouterChatResponse> {\n const body: OpenRouterChatRequest = { ...params, stream: false };\n const response = await fetch(`${this.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: this.headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));\n const message = (errorBody as { error?: { message?: string } }).error?.message ?? response.statusText;\n throw new OpenRouterError(message, response.status);\n }\n\n return response.json() as Promise<OpenRouterChatResponse>;\n }\n\n /**\n * Streaming chat completion via SSE.\n * Yields delta chunks, accumulates the final usage from the last chunk.\n */\n async *chatCompletionStream(\n params: Omit<OpenRouterChatRequest, 'stream'>,\n ): AsyncGenerator<OpenRouterStreamDelta> {\n const body: OpenRouterChatRequest = { ...params, stream: true };\n const response = await fetch(`${this.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: this.headers,\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({ error: { message: response.statusText } }));\n const message = (errorBody as { error?: { message?: string } }).error?.message ?? response.statusText;\n throw new OpenRouterError(message, response.status);\n }\n\n if (!response.body) {\n throw new OpenRouterError('No response body for streaming request', 500);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(':')) continue;\n if (trimmed === 'data: [DONE]') return;\n if (!trimmed.startsWith('data: ')) continue;\n\n const json = trimmed.slice('data: '.length);\n try {\n yield JSON.parse(json) as OpenRouterStreamDelta;\n } catch {\n // Skip malformed chunks\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n","// Evaluation type vocabulary shared between the harness runtime and its\n// check/evaluator surfaces. This is the narrow contract layer — the\n// type language every harness leg is written against:\n//\n// - `EvalIssue` — the single issue shape everything produces.\n// - `EvalTier` / `EvalOutcome` / `EvalCategory` — the issue's axes.\n// - `Priority` — P0/P1/P2 ranking referenced by the retry formatter.\n// - `EvalResult` — aggregate shape a runner returns.\n// - `QualityMode` / `QualityConfig` / `DEFAULT_QUALITY_CONFIG` —\n// the quality-mode knob the adapter surface consumes.\n// - `priorityForIssue` / `isBlocked` / `getActionableIssues` — the\n// purely-typed helpers over the vocabulary.\n//\n// `EvalIssue` is referenced by `PatchFn`, `TierCheck`, `LLMEvaluator`,\n// and `RuntimeRenderCheck` in the harness types hub.\n\n// ─── Priority ──────────────────────────────────────────────────────────────\n// P0 = must (compile + complete), P1 = should (safety), P2 = nice (quality).\n// Single source of truth for the retry-formatter ranking.\n\nexport type Priority = \"P0\" | \"P1\" | \"P2\";\n\n// ─── Issue shape ───────────────────────────────────────────────────────────\n\nexport type EvalTier = 0 | 1 | 2;\nexport type EvalOutcome = \"fail\" | \"warn\" | \"pass\";\n\nexport type EvalCategory =\n | \"compile\"\n | \"security\"\n | \"contract\"\n | \"types\"\n | \"imports\"\n | \"tokens\" // tier 0\n | \"mode\" // tier 0 — per-mode deterministic\n | \"functionality\"\n | \"crash\" // tier 1\n | \"interactivity\"\n | \"accessibility\"\n | \"layout\"\n | \"loading\"\n | \"visual\"; // tier 2\n\nexport interface EvalIssue {\n tier: EvalTier;\n result: EvalOutcome;\n category: EvalCategory;\n /**\n * Priority tier — threaded through to the retry formatter so the LLM can\n * rank its next patch against the prompt's P0/P1/P2 priority schema.\n * Derived from (category, result) via {@link priorityForIssue} when not\n * explicitly set. Optional on construction; check-runners typically\n * populate it before returning.\n */\n priority?: Priority;\n subcategory?: string;\n severity?: \"critical\" | \"major\";\n description: string;\n fix: string;\n line?: number;\n}\n\n/**\n * Runtime-render probe execution status — three-valued so \"the probe\n * never ran\" is never conflated with \"the probe ran clean\".\n *\n * - `ran` — probe executed; its findings (possibly none) are\n * in the issue stream under `runtime:*` subcategories.\n * - `infra-skipped` — probe could NOT execute (environment failure:\n * happy-dom load, user-event document capture,\n * ESM/CJS interop). Carries ZERO probe evidence;\n * consumers MUST NOT count it as a pass.\n * - `not-applicable`— nothing to probe (no compiled code, no contract\n * surface, or no runtimeRender check configured).\n */\nexport type RuntimeProbeStatus = \"ran\" | \"infra-skipped\" | \"not-applicable\";\n\n/**\n * Probe execution meta stamped onto an `EvalResult` at the exit-decision\n * points that invoke the probe. Absence of this field means the eval\n * path never reached a probe invocation at all — consumers treat that\n * the same as not-run, never as a pass.\n */\nexport interface RuntimeProbeMeta {\n readonly status: RuntimeProbeStatus;\n /** Populated for `infra-skipped` / `not-applicable` — why the probe didn't run. */\n readonly reason?: string;\n}\n\nexport interface EvalResult {\n issues: EvalIssue[];\n pass: string[];\n /**\n * Runtime-render probe execution meta. Stamped by the exit-decision\n * probe runner; absent on eval paths that never invoke the probe.\n */\n runtimeProbe?: RuntimeProbeMeta;\n}\n\n// ─── Quality mode ──────────────────────────────────────────────────────────\n\nexport type QualityMode = \"fast\" | \"auto-improve\" | \"high-quality\";\n\nexport interface QualityConfig {\n quality: QualityMode;\n visualEval: boolean;\n maxCostPerGeneration: number;\n model?: { provider?: string; model?: string };\n}\n\nexport const DEFAULT_QUALITY_CONFIG: QualityConfig = {\n quality: \"fast\",\n visualEval: false,\n maxCostPerGeneration: 3,\n};\n\n// ─── Axis-check types ──────────────────────────────────────────────────────\n// The `AxisCheck` type vocabulary lives here. The check bodies\n// themselves (REGISTRY, per-axis implementations) live under\n// `./axis-checks/`.\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { AxisVector, Classification } from \"../classifier/axes.js\";\nimport type { AxisKey } from \"../fragments/index.js\";\n\nexport interface AxisCheckInput {\n sourceCode: string;\n compiledCode: string | null;\n contract?: DataContract;\n originalPrompt: string;\n /** Full classification — checks may read sibling axes. */\n classification: Classification;\n}\n\n/**\n * A gated check. Runs only when the classification's axis value matches\n * one of the gate's accepted values. Multiple gates (implicit AND) support\n * cross-axis combinations.\n */\nexport interface AxisCheck {\n /** Stable id used in issue subcategories. */\n id: string;\n /** Primary axis this check gates on. */\n axis: AxisKey;\n /** Which values of that axis activate the check. */\n values: readonly string[];\n /** Optional extra gate on a sibling axis (e.g., only when state=merge AND writes=per-item). */\n and?: { axis: AxisKey; values: readonly string[] };\n /** Execute the check and emit zero or more issues. */\n run(input: AxisCheckInput): EvalIssue[];\n}\n\n/**\n * Whether a check's gate(s) match the given axis vector. Pure function,\n * no issue emission.\n */\nexport function matches(vector: AxisVector, check: AxisCheck): boolean {\n const primary = vector[check.axis] as string;\n if (!check.values.includes(primary)) return false;\n if (check.and) {\n const sibling = vector[check.and.axis] as string;\n if (!check.and.values.includes(sibling)) return false;\n }\n return true;\n}\n\n// ─── Purely-typed helpers ──────────────────────────────────────────────────\n\n/**\n * Map a tier-0 issue category to the canonical P0/P1/P2 priority.\n *\n * Sourced from the criteria priority assignments:\n * - P0 (must): compile, security, imports, contract, types, mode\n * - P1 (safety): tokens, crash, functionality\n * - P2 (quality): interactivity, accessibility, layout, loading, visual\n */\nexport function priorityForIssue(category: EvalCategory): Priority {\n if (\n category === \"interactivity\" ||\n category === \"accessibility\" ||\n category === \"layout\" ||\n category === \"loading\" ||\n category === \"visual\"\n ) {\n return \"P2\";\n }\n if (category === \"tokens\" || category === \"crash\" || category === \"functionality\") {\n return \"P1\";\n }\n // compile, security, imports, contract, types, mode → P0.\n return \"P0\";\n}\n\n/** Whether any issue blocks shipping (has result = 'fail'). */\nexport function isBlocked(result: EvalResult): boolean {\n return result.issues.some((i) => i.result === \"fail\");\n}\n\n/**\n * Return the issues the agent should act on, depending on quality mode.\n * - fast: only fails (blocking issues)\n * - auto-improve / high-quality: fails + warns\n */\nexport function getActionableIssues(result: EvalResult, mode: QualityMode): EvalIssue[] {\n if (mode === \"fast\") {\n return result.issues.filter((i) => i.result === \"fail\");\n }\n return result.issues.filter((i) => i.result === \"fail\" || i.result === \"warn\");\n}\n\n// ─── Criteria (single source of truth for coding + eval sides) ─────────────\n//\n// Each criterion is defined ONCE with both sides of the contract:\n// - codingGuidance: what the coding agent should DO\n// - evalInstruction: what the eval agent should CHECK\n// They must be compatible — changing one means reviewing the other.\n//\n// This is *validated* shipping content: it's what the hosted runtime sends\n// to every generation today. External OSS implementers building their own\n// prompts should be able to use the same rubric — hence it's open.\n\nexport interface EvalCriterion {\n /** Unique identifier matching the eval tool name (e.g., 'functionality') */\n id: string;\n /** Human-readable name shown to both agents */\n name: string;\n /** Priority tier — P0 must, P1 should, P2 nice */\n priority: Priority;\n /** What the coding agent should DO to satisfy this criterion */\n codingGuidance: string;\n /** What the eval agent should CHECK — the evaluation prompt */\n evalInstruction: string;\n /** Tier 0 = programmatic, Tier 1 = LLM critical, Tier 2 = LLM quality */\n tier: 0 | 1 | 2;\n /** Eval outcome when this criterion fails */\n failOutcome: \"fail\" | \"warn\";\n}\n\nexport const CRITERIA: readonly EvalCriterion[] = [\n // ── P0: Correctness (must satisfy — failure = broken component) ──\n\n {\n id: \"compile\",\n name: \"Compile & type-check\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance:\n \"Code must compile. The typed Props and wire hook generics are enforced by the compiler.\",\n evalInstruction: \"Checked automatically by esbuild + TypeScript. No LLM evaluation needed.\",\n },\n {\n id: \"render-props\",\n name: \"Render all Props fields\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance: \"Render every Props field in JSX. Access via props.fieldName.\",\n evalInstruction:\n \"Check that every field from interface Props appears as props.fieldName in the function body.\",\n },\n {\n id: \"wire-hooks\",\n name: \"Wire all contract hooks\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Wire every useAction/useStream and every clientCapabilities.gadgets hook (e.g., useGeolocation) to a UI element. `agentCapabilities.tools` is a catalog the AGENT invokes — NOT a component hook surface.\",\n evalInstruction:\n \"Check that every hook variable from the boilerplate appears in the JSX or an effect.\",\n },\n {\n id: \"imports\",\n name: \"Valid imports only\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Only import from react, @ggui-ai/design/*, and @ggui-ai/wire.\",\n evalInstruction: \"Flag any import from a package not in the allowlist.\",\n },\n {\n id: \"security\",\n name: \"No eval/fetch/window\",\n priority: \"P0\",\n tier: 0,\n failOutcome: \"fail\",\n codingGuidance: \"Never use eval(), fetch(), or window. Data comes from props and hooks.\",\n evalInstruction: \"Flag any call to eval(), fetch(), or window access.\",\n },\n\n // ── P1: Safety (should satisfy — failure = crash or bad UX) ──\n\n {\n id: \"functionality\",\n name: \"All features implemented\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance: \"Implement ALL features from the request AND the data contract.\",\n evalInstruction: `Evaluate FUNCTIONALITY: Does this component implement ALL features from the request AND the data contract?\n\nCheck against BOTH sources:\n1. Original request — each feature must be coded AND rendered in JSX\n2. Data contract (if present) — verify:\n - Props fields are rendered in the UI. EXCEPTION: pure identifier fields (\\`id\\`, \\`*Id\\`, keys) that exist only to be echoed back inside an action payload do NOT need to be visibly rendered.\n - ALL useAction hooks are wired to clickable UI elements\n - ALL useStream hooks are consumed — the streamed data must reach the UI. Merging stream events into rendered state (a list, a counter, the displayed records) COUNTS as consuming the stream; it need not be a literal \\`.latest\\` render.\n - ALL clientCapabilities gadgets are used. \\`clientCapabilities.gadgets\\` is keyed by npm package: built-in browser capabilities (useGeolocation / useCamera / …) import from @ggui-ai/gadgets; registered third-party gadgets (e.g. useChartTheme) import from their OWN package. Any gadget the contract declares IS a contract feature — NEVER flag it as \"not part of the contract\".\n - \\`agentCapabilities.tools\\` is a catalog declaration only; do NOT flag missing component-side calls for it\n\nA contract hook that is declared but never used at all is a MISSING feature.\n\nCRITICAL: The \"issues\" array must ONLY contain features you are CERTAIN are missing or broken — never an implemented feature. (See \"Issue-array discipline\" above: no speculative, self-negating, or \"verify that…\" entries.)`,\n },\n {\n id: \"crash\",\n name: \"No crash scenarios\",\n priority: \"P1\",\n tier: 1,\n failOutcome: \"fail\",\n codingGuidance:\n \"Guard optional props (props.field?.x). stream.latest is T|null — always null-guard. .all is always an array.\",\n evalInstruction: `Evaluate CRASH SAFETY: Are there ACTUAL runtime crash scenarios?\n\nWILL crash (include in issues):\n- .map()/.filter()/.length on an uninitialized variable\n- Accessing property of undefined without guard\n- useStream().latest.field WITHOUT null guard — .latest is T | null\n- Optional Props field accessed as props.field.x without guard\n- Array item optional field: items.map(item => item.priority.toUpperCase()) when priority is optional\n\nSAFE (do NOT include):\n- Optional chaining: props.items?.map() — SAFE\n- Fallback: items || [] — SAFE\n- useState initializer: useState([]) — SAFE\n- Null check: items && items.map() — SAFE\n- stream.latest && stream.latest.field — SAFE, guarded\n- stream.all.map(...) — SAFE, .all is always an array\n- stream.all.length — SAFE, always a number\n\nThe \"issues\" array is ONLY for a specific line that WILL throw at runtime. NEVER put a line you have determined is safe into the issues array — not even to note that it is safe (\"…so this is safely guarded\", \"…so there is no crash\"). If you cannot name a concrete line that will throw, the answer is {\"pass\": true} — return that and an empty issues array.`,\n },\n {\n id: \"tokens\",\n name: \"Design system tokens\",\n priority: \"P1\",\n tier: 0,\n failOutcome: \"warn\",\n codingGuidance:\n \"Use CSS variables for colors (var(--ggui-color-*)); use the spacing scale for gap/padding/margin (gap=\\\"md\\\", padding=\\\"lg\\\").\",\n evalInstruction:\n \"Flag hardcoded hex colors, rgba/hsl functions, and numeric or raw-CSS-length spacing props. A t-shirt-scale spacing name (gap=\\\"md\\\") IS a token — never flag it.\",\n },\n\n // ── P2: Quality (nice to have — failure = lower score, not broken) ──\n\n {\n id: \"interactivity\",\n name: \"Sufficient interactive elements\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Add appropriate interactive elements for the component purpose.\",\n evalInstruction: `Evaluate INTERACTIVITY: Does this component have sufficient interactive elements?\n\nConsider: forms need submit buttons, lists need selection, editable content needs save/cancel.\nContract actions (if present): every useAction hook should be triggered by a visible UI element.\n\nOnly list MISSING interactive elements. Use 'fail' only for issues blocking core purpose.`,\n },\n {\n id: \"accessibility\",\n name: \"Accessible markup\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance:\n \"Add labels on form inputs, alt text on images, semantic HTML, and state ARIA (aria-checked/pressed/selected/expanded) on hand-rolled interactive controls.\",\n evalInstruction: `Evaluate ACCESSIBILITY: missing labels, alt text, semantic HTML, keyboard support, ARIA state.\n\nggui primitives bake in their own ARIA — see \"Primitive Accessibility\" in the Design System context above. NEVER flag a ggui primitive (Input/Select/TextArea, RadioGroup, Checkbox, Toggle, Progress, Slider, Spinner, Skeleton, Tabs, Accordion, Alert, Toast, Tooltip, Clickable, Icon) for a missing role / aria-* / label / keyboard handler — it is already there and not visible in the source you are reading.\n\nFlag ONLY real gaps: a raw div/span used as an interactive control; a hand-rolled control whose checked/selected/expanded/pressed state is conveyed only by styling (strikethrough, color, a check icon) with no \\`aria-checked\\` / \\`aria-pressed\\` / \\`aria-selected\\` / \\`aria-expanded\\`; an image with no alt text; an Input/Select/TextArea with no \\`label\\` prop; an icon-only Button with no aria-label; live/streaming data not wrapped in an aria-live region; inverted heading hierarchy.\n\nOnly list MISSING accessibility features. Use 'fail' only if it blocks delivery.`,\n },\n {\n id: \"layout\",\n name: \"Clean layout\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use proper spacing and visual grouping.\",\n evalInstruction: `Evaluate LAYOUT: Check spacing, alignment, visual grouping, and composition.\n\nOnly list ACTUAL layout problems. Use 'fail' only for fundamentally broken layouts.`,\n },\n {\n id: \"loading\",\n name: \"Loading/empty/error states\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Handle async data, empty collections, and error cases.\",\n evalInstruction: `Evaluate LOADING/EMPTY/ERROR STATES: Does the component handle async data and edge cases?\n\nContract-specific: useStream should handle pre-data state. clientCapabilities hooks may return undefined / permission-denied — defensive guards expected before threading values into JSX.\nProps-only components (no async, no streams, no client capabilities) do NOT need loading states — return pass.\n\nOnly list MISSING states.`,\n },\n {\n id: \"visual\",\n name: \"Design system consistency\",\n priority: \"P2\",\n tier: 2,\n failOutcome: \"warn\",\n codingGuidance: \"Use design system tokens consistently.\",\n evalInstruction: `Evaluate VISUAL CONSISTENCY: Is the component using the design system correctly?\n\nFlag: hardcoded colors instead of CSS variables, numeric or raw-CSS-length spacing instead of the t-shirt scale, style objects bypassing design system.\nA t-shirt-scale spacing name (gap=\"md\", padding=\"lg\") IS correct token usage — never flag it.\nIntentional custom colors (status indicators) are acceptable when no semantic token fits.\n\nOnly list ACTUAL violations. Use 'fail' only for pervasive violations.`,\n },\n] as const;\n\n/** Get all criteria for a specific priority level */\nexport function getCriteriaByPriority(priority: Priority): EvalCriterion[] {\n return CRITERIA.filter((c) => c.priority === priority);\n}\n\n/** Get a specific criterion by ID */\nexport function getCriterionById(id: string): EvalCriterion | undefined {\n return CRITERIA.find((c) => c.id === id);\n}\n\n/** Get all LLM-evaluated criteria (tier 1 + 2) */\nexport function getLLMCriteria(): EvalCriterion[] {\n return CRITERIA.filter((c) => c.tier > 0);\n}\n\n/**\n * Build the coding agent's criteria summary from the single source of truth.\n * Grouped by priority for the P0→P1→P2 hierarchy.\n */\nexport function buildCodingCriteriaSummary(): string {\n const lines: string[] = [\"## Priority (P0 first, then P1, then P2)\", \"\"];\n\n for (const priority of [\"P0\", \"P1\", \"P2\"] as Priority[]) {\n const label =\n priority === \"P0\"\n ? \"Must (compile + complete)\"\n : priority === \"P1\"\n ? \"Should (safety)\"\n : \"Nice (quality)\";\n const criteria = getCriteriaByPriority(priority);\n lines.push(`**${priority} — ${label}:**`);\n for (const c of criteria) {\n lines.push(`- ${c.codingGuidance}`);\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n","// packages/ui-gen/src/adapters/claude/client.ts\n//\n// SINGLE SOURCE OF TRUTH for Anthropic SDK construction.\n//\n// The BYOK resolver writes the raw credential string into\n// `process.env.ANTHROPIC_API_KEY`, which the Anthropic SDK auto-reads as\n// `x-api-key`. Adapters MUST go through `createAnthropicClient` (no\n// inline `new Anthropic(...)`) so future header / baseURL tweaks land\n// in one place.\n\nimport Anthropic from '@anthropic-ai/sdk';\n\n/**\n * Construct an Anthropic SDK client from a raw API key string.\n *\n * - `string` → standard `apiKey` path (sends `x-api-key`).\n * - `undefined` → still construct a client; SDK auto-reads\n * `process.env.ANTHROPIC_API_KEY` or throws on first call.\n *\n * **SINGLE SOURCE OF TRUTH for Anthropic client construction.** Every\n * adapter that constructs an Anthropic client MUST go through this\n * helper — no inline `new Anthropic(...)` allowed in adapter code.\n */\nexport function createAnthropicClient(\n rawKey: string | undefined,\n): Anthropic {\n if (rawKey === undefined) {\n return new Anthropic({\n baseURL: 'https://api.anthropic.com',\n });\n }\n return new Anthropic({\n apiKey: rawKey,\n baseURL: 'https://api.anthropic.com',\n });\n}\n","// packages/ui-gen/src/adapters/provider-router.ts\n//\n// Provider router for multi-provider BYOK support. Determines how to\n// route LLM requests based on the typed `LlmRoute` discriminator and\n// API-key availability.\n//\n// The previous `getUpstreamModelId` strip + `UPSTREAM_MAP` are gone:\n// the typed `LlmRoute` (slice #43) guarantees `route.model` is\n// wire-canonical at construction time, so there is no LiteLLM prefix\n// to strip at this boundary. `getBedrockModelId` stays — the\n// \"anthropic route + bedrock IAM\" mixed-mode escape hatch (cloud-pod\n// legacy) still needs the wire-canonical anthropic id → cross-region\n// profile id upcast.\n\nimport type { LlmRoute } from '@ggui-ai/protocol';\n\n/**\n * Map a wire-canonical Anthropic model id (or already-bedrock id) to\n * the AWS Bedrock cross-region inference profile id. Used by the\n * mixed-mode `anthropic` route + bedrock-IAM fallback path in\n * {@link resolveRoute} (cloud-pod legacy) and the analogous branch in\n * `harness/llm-router.ts::AnthropicAgent.resolveModel`.\n *\n * Operators picking the bedrock route explicitly (slice #43 Phase 4)\n * pass the cross-region id directly — this helper is purely the\n * fallback escape hatch.\n */\nexport function getBedrockModelId(model: string): string {\n const BEDROCK_MAP: Record<string, string> = {\n 'anthropic/claude-haiku-4-5': 'us.anthropic.claude-haiku-4-5-20251001-v1:0',\n 'anthropic/claude-sonnet-4-6': 'us.anthropic.claude-sonnet-4-6',\n 'anthropic/claude-opus-4-6': 'us.anthropic.claude-opus-4-6-v1:0',\n };\n // Normalize the Bedrock dot-form opt-in (e.g. `anthropic.claude-haiku-4-5`,\n // produced when cloud-pod's `resolvePoolRoute` strips a `bedrock/` opt-in\n // prefix) to the Anthropic slash form. Both spellings should resolve to\n // the same cross-region inference profile id — without this, the dot\n // form would skip the BEDROCK_MAP hit, fall through the `^anthropic\\/`\n // strip (which is a no-op for the dot form), and re-prepend\n // `us.anthropic.` to produce a double-`anthropic.` id that Bedrock\n // rejects with 400 (cloud e2e regression 2026-05-25, bedrock-iam.spec).\n const normalized = model.replace(/^anthropic\\./, 'anthropic/');\n if (BEDROCK_MAP[normalized]) return BEDROCK_MAP[normalized];\n if (normalized.startsWith('us.anthropic.') || normalized.startsWith('arn:')) {\n return normalized;\n }\n const stripped = normalized.replace(/^anthropic\\//, '');\n return `us.anthropic.${stripped}`;\n}\n\nexport interface RoutingDecision {\n /**\n * Upstream model id the dispatch adapter will pass to the provider\n * SDK. For most routes this is `route.model` verbatim — the typed\n * `LlmRoute` (slice #43) carries the wire-canonical id, so no\n * transformation is needed. The exception is the mixed-mode\n * \"anthropic route + bedrock IAM fallback\" branch, which upcasts\n * the wire-canonical Anthropic id to the corresponding Bedrock\n * cross-region inference profile id via {@link getBedrockModelId}.\n */\n readonly model: string;\n /**\n * Env-var mutations the caller MUST apply to `process.env` before\n * invoking the dispatch adapter. `undefined` values are deletions\n * (the wrong provider's stale key must be cleared so the dispatch\n * doesn't accidentally fire against it). See {@link applyRouteToEnv}.\n */\n readonly env: Record<string, string | undefined>;\n}\n\nexport interface RoutingInput {\n /** Typed `(provider, model)` route — model is wire-canonical. */\n readonly route: LlmRoute;\n /** API key for byok-capable providers; ignored for `bedrock`. */\n readonly apiKey?: string;\n /** Current env snapshot — feeds the anthropic mixed-mode branch. */\n readonly env: Record<string, string | undefined>;\n}\n\n/**\n * Sibling-provider env vars that MUST be cleared for every non-self\n * route. Centralized so the per-provider branches below stay\n * symmetric — a single missing entry would let a stale key leak into\n * the next render (e.g. an OpenRouter route inheriting a previous\n * call's `OPENAI_API_KEY` and firing the wrong adapter).\n */\nconst SIBLING_ENV_KEYS = [\n 'ANTHROPIC_API_KEY',\n 'ANTHROPIC_BASE_URL',\n 'CLAUDE_CODE_USE_BEDROCK',\n 'OPENAI_API_KEY',\n 'GEMINI_API_KEY',\n 'GOOGLE_API_KEY',\n 'OPENROUTER_API_KEY',\n] as const;\n\nfunction clearSiblings(\n keep: ReadonlySet<(typeof SIBLING_ENV_KEYS)[number]>,\n): Record<string, undefined> {\n const out: Record<string, undefined> = {};\n for (const k of SIBLING_ENV_KEYS) {\n if (!keep.has(k)) out[k] = undefined;\n }\n return out;\n}\n\n/**\n * Determine the routing strategy for a generation request. Pure\n * function over `(route, apiKey, env)` — returns the upstream model\n * id (usually `route.model` verbatim) and the env-var mutations the\n * caller must apply before dispatch.\n *\n * Dispatch is on `route.provider`:\n *\n * - `openai` — direct OpenAI API (sets `OPENAI_API_KEY`).\n * - `google` — direct Gemini API (sets `GEMINI_API_KEY` + `GOOGLE_API_KEY`).\n * - `openrouter` — direct OpenRouter API (sets `OPENROUTER_API_KEY`).\n * - `bedrock` — AWS Bedrock via host IAM (sets `CLAUDE_CODE_USE_BEDROCK=1`,\n * no API key in flight; model passes verbatim).\n * - `anthropic` — three-way fallback chain:\n * 1. With `apiKey` → direct Anthropic API.\n * 2. Without `apiKey` AND explicit `env.CLAUDE_CODE_USE_BEDROCK === '1'`\n * (or no `env.ANTHROPIC_API_KEY`) → mixed-mode bedrock fallback\n * (model upcast to cross-region profile via `getBedrockModelId`).\n * Cloud-pod legacy escape hatch; the OSS Phase 4 strict-fail\n * prevents end-users from reaching this branch implicitly.\n * 3. Otherwise → direct Anthropic API with whatever\n * `ANTHROPIC_API_KEY` is already in `env`.\n *\n * For non-Anthropic non-Bedrock providers, an `apiKey` is REQUIRED —\n * there's no IAM-style fallback. Callers that don't have a key MUST\n * surface a \"no API key\" envelope to their agent before reaching the\n * dispatch path; throwing here is defense in depth.\n */\nexport function resolveRoute(input: RoutingInput): RoutingDecision {\n const { route, apiKey, env } = input;\n\n switch (route.provider) {\n case 'openai': {\n if (!apiKey) {\n throw new Error(\n `openai:${route.model} requires an API key. ` +\n `Set 'apiKey' on the RoutingInput (BYOK) or supply your key ` +\n `via your dispatch layer.`,\n );\n }\n return {\n model: route.model,\n env: {\n OPENAI_API_KEY: apiKey,\n ...clearSiblings(new Set(['OPENAI_API_KEY'])),\n },\n };\n }\n\n case 'google': {\n if (!apiKey) {\n throw new Error(\n `google:${route.model} requires an API key. ` +\n `Set 'apiKey' on the RoutingInput (BYOK) or supply your key ` +\n `via your dispatch layer.`,\n );\n }\n return {\n model: route.model,\n env: {\n // `harness/llm-router.ts`'s GoogleAgent reads `GEMINI_API_KEY\n // || GOOGLE_API_KEY`. Set both so either slot wins;\n // unsetting one would leave a stale value behind.\n GEMINI_API_KEY: apiKey,\n GOOGLE_API_KEY: apiKey,\n ...clearSiblings(new Set(['GEMINI_API_KEY', 'GOOGLE_API_KEY'])),\n },\n };\n }\n\n case 'openrouter': {\n if (!apiKey) {\n throw new Error(\n `openrouter:${route.model} requires an API key. ` +\n `Set 'apiKey' on the RoutingInput (BYOK) or supply your key ` +\n `via your dispatch layer.`,\n );\n }\n return {\n model: route.model,\n env: {\n OPENROUTER_API_KEY: apiKey,\n ...clearSiblings(new Set(['OPENROUTER_API_KEY'])),\n },\n };\n }\n\n case 'bedrock': {\n // IAM auth — no apiKey in flight. The model is already a\n // cross-region profile id (e.g.\n // `us.anthropic.claude-haiku-4-5-20251001-v1:0`); pass it\n // verbatim.\n return {\n model: route.model,\n env: {\n CLAUDE_CODE_USE_BEDROCK: '1',\n ...clearSiblings(new Set(['CLAUDE_CODE_USE_BEDROCK'])),\n },\n };\n }\n\n case 'anthropic': {\n if (apiKey) {\n return {\n model: route.model,\n env: {\n ANTHROPIC_API_KEY: apiKey,\n ...clearSiblings(new Set(['ANTHROPIC_API_KEY'])),\n },\n };\n }\n // Mixed-mode legacy: anthropic route + bedrock IAM fallback.\n // Cloud-pod escape hatch when `ANTHROPIC_API_KEY` isn't seeded.\n const explicitBedrock = env.CLAUDE_CODE_USE_BEDROCK === '1';\n const noApiKey = !env.ANTHROPIC_API_KEY;\n if (explicitBedrock || noApiKey) {\n return {\n model: getBedrockModelId(route.model),\n env: {\n CLAUDE_CODE_USE_BEDROCK: '1',\n ...clearSiblings(new Set(['CLAUDE_CODE_USE_BEDROCK'])),\n },\n };\n }\n // Anthropic via process.env.ANTHROPIC_API_KEY (no in-call key).\n return {\n model: route.model,\n env: clearSiblings(new Set(['ANTHROPIC_API_KEY'])),\n };\n }\n }\n}\n\n/**\n * Apply routing decision to an environment object.\n */\nexport function applyRouteToEnv(\n baseEnv: Record<string, string>,\n route: RoutingDecision,\n): Record<string, string> {\n const result = { ...baseEnv };\n for (const [key, value] of Object.entries(route.env)) {\n if (value === undefined) {\n delete result[key];\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n","// packages/ui-gen/src/adapters/tool-bridge.ts\n//\n// Bridges between SDK tool wire formats and ggui's JSON types:\n// Zod → JSON Schema for tool declarations, and validated narrowing of\n// decoded tool-call arguments to `JsonObject`.\n\nimport { z } from 'zod';\nimport type { JsonObject, JsonValue } from '@ggui-ai/protocol';\n\n/**\n * Convert a Zod object schema to JSON Schema.\n * Uses Zod v4's built-in toJSONSchema() function.\n */\nexport function zodToJsonSchema(schema: z.ZodType): JsonObject {\n return z.toJSONSchema(schema) as JsonObject;\n}\n\n/**\n * Validate that a decoded tool-call `arguments` object is plain JSON data\n * and narrow it to {@link JsonObject}. Provider SDKs type tool-call\n * arguments as `{ [key: string]: unknown }`; values decoded from a JSON\n * wire payload are JSON by construction, so a failure here means the SDK\n * handed us something that never came from JSON — a bug worth surfacing,\n * not erasing with a cast.\n */\nexport function toolArgsToJsonObject(args: { [key: string]: unknown }): JsonObject {\n const out: JsonObject = {};\n for (const [key, value] of Object.entries(args)) {\n // `JsonObject` keys admit `undefined` (TS optional properties);\n // JSON.stringify omits them, so pass-through is JSON-safe.\n out[key] = value === undefined ? undefined : toJsonValue(value, key);\n }\n return out;\n}\n\nfunction toJsonValue(value: unknown, path: string): JsonValue {\n if (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((item, i) => toJsonValue(item, `${path}[${i}]`));\n }\n if (typeof value === 'object') {\n const out: JsonObject = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = entry === undefined ? undefined : toJsonValue(entry, `${path}.${key}`);\n }\n return out;\n }\n throw new Error(\n `Tool-call arguments contain a non-JSON value at '${path}' (${typeof value})`,\n );\n}\n","/**\n * Live LLM trace sink — devtools introspection of every LLM call the\n * generation harness makes.\n *\n * **Distinct from {@link TelemetrySink} and {@link AuditSink}.**\n * - **Telemetry** (mcp-server-core) = ops signals (`pair.completed`,\n * `render.duration_ms`). Sink may be lossy and drops on backpressure.\n * Attributes are flat scalars (`string | number | boolean`).\n * - **Audit** (mcp-server-core) = compliance log of privileged\n * mutations. Durable, async, may throw.\n * - **LLM trace** (this) = devtools-only, hostable in-memory ring\n * buffer of every LLM call's full payload (system prompt, user\n * prompt, tool defs, completion, token counts, cache hits, error).\n * Lossy by default. A hosted closed runtime may swap in a durable\n * sink for internal debugging; OSS ships an in-memory sink the\n * `/devtools/llm-trace` page reads.\n *\n * **Why module-level registry instead of constructor injection.** The\n * harness constructs LLM agents on every generation via\n * {@link createAgent}. Threading a sink through every call site\n * (createAgent → run-coding-turn → llm-evaluator → file-agent → …)\n * touches ~5 packages for a devtools-only surface. The OSS ggui server\n * is a single process per CLI invocation — global state has no\n * confusion-cost there. A hosted closed runtime isolates per request\n * via process-pool, so a global per-pool is also safe. If we ever\n * multi-tenant inside one process we'll thread it then.\n *\n * **Default = no sink.** When unset, the router emits nothing and\n * spends no CPU formatting events. Passing `null` removes a previously\n * registered sink.\n */\nimport type { LLMToolDef } from '../llm.js';\n\n/** Provider tag that produced the call. Mirrors {@link AgentConfig.provider}. */\nexport type LlmTraceProvider = 'anthropic' | 'openai' | 'google' | 'openrouter';\n\n/** Which `LLMAgent` method initiated the call. */\nexport type LlmTraceKind =\n | 'callText'\n | 'callTools'\n | 'callWithTools'\n | 'callStructured';\n\n/**\n * One LLM call. Emitted **after** the call completes (success or error)\n * — single event, not start/end split. Devtools UI is timeline-friendly\n * because each event carries `at` (start) + `endedAt` (end).\n */\nexport interface LlmTraceEvent {\n /** Random per-event ID. */\n readonly id: string;\n /** Epoch ms when the call was issued. */\n readonly at: number;\n /** Epoch ms when the call completed (success or error). */\n readonly endedAt: number;\n /** `endedAt - at` — convenience. */\n readonly durationMs: number;\n readonly provider: LlmTraceProvider;\n readonly model: string;\n readonly kind: LlmTraceKind;\n readonly systemPrompt?: string;\n readonly userPrompt?: string;\n /**\n * Tool defs sent on the call (if any). Stripped to `name + description`\n * — full JSON schema would balloon the trace and is rarely useful in\n * the operator UI.\n */\n readonly tools?: ReadonlyArray<{\n readonly name: string;\n readonly description: string;\n }>;\n /** Set on successful completion. */\n readonly result?: {\n readonly inputTokens: number;\n readonly outputTokens: number;\n /** Anthropic only. Bytes counted toward the cache write. */\n readonly cacheCreated?: number;\n /** Anthropic only. Bytes served from cache (90% discounted). */\n readonly cacheRead?: number;\n /** Set when the call returned text content. */\n readonly text?: string;\n /** Set when the call returned tool_use blocks. */\n readonly toolCalls?: ReadonlyArray<{\n readonly name: string;\n readonly input: unknown;\n }>;\n /** Set for `callWithTools` — number of agentic turns consumed. */\n readonly turnsUsed?: number;\n };\n /** Set on failure. `result` is undefined. */\n readonly error?: { readonly message: string };\n}\n\n/**\n * Sink that receives one event per LLM call. Implementations MUST be\n * sync + non-throwing — the harness fires events on the hot path and\n * cannot tolerate backpressure or rejected promises. Buffer + drop or\n * fan out to a queue inside the implementation.\n */\nexport interface LlmTraceSink {\n emit(event: LlmTraceEvent): void;\n}\n\nlet activeSink: LlmTraceSink | null = null;\n\n/**\n * Register the active sink. Pass `null` to remove. Subsequent\n * {@link emitLlmTraceEvent} calls dispatch to this sink.\n */\nexport function setLlmTraceSink(sink: LlmTraceSink | null): void {\n activeSink = sink;\n}\n\n/** Read the active sink. Mostly for tests. */\nexport function getLlmTraceSink(): LlmTraceSink | null {\n return activeSink;\n}\n\n/**\n * Internal — used by `LLMAgent` adapters. No-op when no sink is\n * registered. Swallows sink-thrown errors (a broken devtools sink must\n * not break generation).\n */\nexport function emitLlmTraceEvent(event: LlmTraceEvent): void {\n const sink = activeSink;\n if (!sink) return;\n try {\n sink.emit(event);\n } catch {\n // Devtools sink is allowed to be buggy — generation must not die.\n }\n}\n\n/** Strip `LLMToolDef[]` to the trace-friendly subset. */\nexport function summarizeTools(\n tools: ReadonlyArray<LLMToolDef>,\n): ReadonlyArray<{ readonly name: string; readonly description: string }> {\n return tools.map((t) => ({ name: t.name, description: t.description }));\n}\n\n/**\n * Crockford-style random ID. Crypto.randomUUID() would do, but we want\n * to keep this dep-free for non-Node runtimes the harness might run in.\n */\nexport function newLlmTraceId(): string {\n return (\n Date.now().toString(36) +\n Math.random().toString(36).slice(2, 10)\n );\n}\n","// packages/ui-gen/src/harness/llm-router.ts\n//\n// Provider-agnostic LLM routing via LLMAgent class hierarchy.\n// Each provider implements its own SDK interface with proper types.\n//\n// Key methods:\n// callText() — plain text response\n// callStructured() — JSON structured output (for coding agent)\n// callWithTools() — multi-turn agentic loop\n\nimport type Anthropic from '@anthropic-ai/sdk';\nimport type {\n TextBlock,\n TextBlockParam,\n ToolUseBlock,\n} from '@anthropic-ai/sdk/resources/messages';\nimport type OpenAI from 'openai';\nimport type {\n Response as OpenAIResponse,\n ResponseFunctionToolCall,\n} from 'openai/resources/responses/responses';\nimport type {\n GoogleGenAI,\n Interactions,\n} from '@google/genai';\nimport type { JsonObject } from '@ggui-ai/protocol';\nimport type { LLMToolDef } from '../llm.js';\nimport type { AnthropicBedrock } from '@anthropic-ai/bedrock-sdk';\nimport { createAnthropicClient } from '../adapters/claude/client.js';\nimport { getBedrockModelId } from '../adapters/provider-router.js';\nimport { toolArgsToJsonObject } from '../adapters/tool-bridge.js';\nimport {\n emitLlmTraceEvent,\n newLlmTraceId,\n summarizeTools,\n} from './llm-trace-sink.js';\n\n// `LLMToolDef` lives in `@ggui-ai/ui-gen/llm`. This file re-exports it\n// so `../harness/llm-router.js` importers (evaluator.ts,\n// llm-evaluator.ts, run-coding-turn.ts) can reach it here.\nexport type { LLMToolDef };\n\n// =============================================================================\n// Shared Types\n// =============================================================================\n\nexport interface AgentConfig {\n provider: 'anthropic' | 'openai' | 'google' | 'openrouter';\n model: string;\n /**\n * Sampling temperature. When defined it is threaded into the provider\n * request; when undefined the provider default is used (unchanged\n * behavior for all existing callers).\n */\n temperature?: number;\n}\n\nexport interface LLMResponse {\n text: string;\n inputTokens: number;\n outputTokens: number;\n}\n\nexport interface LLMTool {\n name: string;\n description: string;\n parameters: JsonObject;\n handler: (\n args: JsonObject,\n ) => Promise<{ content: Array<{ text: string }>; isError?: boolean }>;\n}\n\nexport interface LLMWithToolsResponse {\n text: string;\n inputTokens: number;\n outputTokens: number;\n turnsUsed: number;\n}\n\nexport interface LLMToolCall {\n /** Provider-specific call ID (for sendToolResult) */\n id?: string;\n name: string;\n input: JsonObject;\n}\n\nexport interface LLMToolCallResponse {\n toolCalls: LLMToolCall[];\n inputTokens: number;\n outputTokens: number;\n /**\n * Tokens read from / written to the prompt cache, when the provider\n * reports them. Optional because not every provider exposes\n * prompt-cache accounting — absent means \"unreported\", never zero.\n */\n cacheReadTokens?: number;\n cacheCreationTokens?: number;\n}\n\n// Backward compat alias\nexport type LLMSingleTurnResponse = LLMToolCallResponse;\n\n/** Result of executing a tool — passed to sendToolResult to close the API contract. */\nexport interface LLMToolResult {\n /** Tool call ID from the response (for providers that need it) */\n callId?: string;\n /** Tool name */\n name: string;\n /** Text result of executing the tool */\n result: string;\n /** Whether the tool execution failed */\n isError?: boolean;\n}\n\n// =============================================================================\n// Schema helpers\n// =============================================================================\n\n/**\n * Add `additionalProperties: false` to all object schemas and ensure all\n * properties are in `required`. Required by OpenAI strict mode.\n * Recursively processes nested objects and array items.\n */\nfunction addStrictSchemaConstraints(schema: JsonObject): JsonObject {\n const result = { ...schema };\n\n if (result.type === 'object' && result.properties) {\n result.additionalProperties = false;\n // All properties must be required for strict mode\n const propKeys = Object.keys(result.properties as JsonObject);\n if (!result.required || (result.required as string[]).length < propKeys.length) {\n result.required = propKeys;\n }\n // Recurse into nested properties\n const props = { ...(result.properties as JsonObject) };\n for (const [key, value] of Object.entries(props)) {\n if (typeof value === 'object' && value !== null) {\n props[key] = addStrictSchemaConstraints(value as JsonObject);\n }\n }\n result.properties = props;\n }\n\n // Recurse into array items\n if (result.type === 'array' && result.items && typeof result.items === 'object') {\n result.items = addStrictSchemaConstraints(result.items as JsonObject);\n }\n\n return result;\n}\n\n// =============================================================================\n// Error helpers\n// =============================================================================\n\n/** One-line error summary for logging — includes HTTP status, error code, and response body excerpt. */\nfunction errorSummary(e: unknown): string {\n if (!(e instanceof Error)) return String(e);\n const status = 'status' in e ? ` (${(e as { status: number }).status})` : '';\n const code = 'code' in e ? ` [${(e as { code: string }).code}]` : '';\n // Extract error body if available (Google/OpenAI SDKs attach it)\n let body = '';\n if ('error' in e && typeof (e as { error: unknown }).error === 'object') {\n const errObj = (e as { error: { message?: string } }).error;\n if (errObj?.message) body = ` body=\"${errObj.message.slice(0, 200)}\"`;\n }\n return `${e.constructor.name}${status}${code}: ${e.message.slice(0, 120)}${body}`;\n}\n\n// =============================================================================\n// LLMAgent — abstract base\n// =============================================================================\n\nexport abstract class LLMAgent {\n abstract readonly provider: AgentConfig['provider'];\n private client: unknown = null;\n\n // ── Session state for server-side chaining ──────────────\n // Google: previous_interaction_id, OpenAI: previous_response_id\n // Enables turn 2+ to skip re-sending system prompt + history.\n // Call resetSession() between independent generation runs.\n protected lastSessionId: string | undefined;\n\n\n protected abstract resolveModel(model: string): string;\n protected abstract createClient(): Promise<unknown>;\n\n protected async getClient<T>(): Promise<T> {\n if (!this.client) {\n this.client = await this.createClient();\n }\n return this.client as T;\n }\n\n /** Text-only call — no tools */\n abstract callText(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n temperature?: number,\n ): Promise<LLMResponse>;\n\n /**\n * Single-turn function calling — returns tool calls without executing them.\n * Each provider uses its native function/tool calling:\n * - Anthropic: tool_use blocks\n * - OpenAI: function_call output items\n * - Google: functionCall parts\n * SDK handles JSON escaping — safe for code, diffs, and other content.\n */\n abstract callTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMToolDef[],\n toolChoice?: 'required' | 'auto',\n /**\n * Optional scoped fallback tools. If the primary tools fail with a\n * transport-class error (e.g. `malformed_tool_call` on Gemini after\n * retry exhaustion), the provider may retry once with these narrower\n * tools before throwing. Universal signal — not provider-gated.\n */\n scopedTools?: LLMToolDef[],\n ): Promise<LLMToolCallResponse>;\n\n /** Multi-turn agentic loop — executes tools internally */\n abstract callWithTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number,\n ): Promise<LLMWithToolsResponse>;\n\n /**\n * Pre-warm cache for repeated callTools() calls with the same system prompt + tools.\n * Override in providers that support server-side context caching (e.g., Google).\n * No-op by default (Anthropic/OpenAI handle caching automatically per-request).\n */\n async warmCache(\n _model: string,\n _systemPrompt: string,\n _tools: LLMToolDef[],\n _toolChoice?: 'required' | 'auto',\n ): Promise<void> {}\n\n /** Cleanup any cached resources. Call after generation completes. No-op by default. */\n async cleanup(): Promise<void> {}\n\n /** Reset session state between independent generation runs. */\n resetSession(): void {\n this.lastSessionId = undefined;\n }\n\n /**\n * Send tool execution results back to the provider to close the API contract.\n * Call this after executing tools from callTools() and before the next callTools().\n *\n * For providers with server-side state (Google, OpenAI), this sends the\n * function results so the next callTools() can chain properly.\n * For stateless providers (Anthropic), this is a no-op.\n *\n * Override in providers that need it.\n */\n async sendToolResult(_results: LLMToolResult[]): Promise<void> {\n // No-op by default — Anthropic doesn't need this (stateless + auto prompt cache)\n }\n\n /**\n * Execute an API call. No retry — if it fails, it fails.\n * Logs the error with provider context and re-throws.\n */\n protected async apiCall<T>(fn: () => Promise<T>): Promise<T> {\n const start = Date.now();\n try {\n return await fn();\n } catch (e: unknown) {\n const ms = Date.now() - start;\n console.error(`[${this.provider}] API error after ${ms}ms: ${errorSummary(e)}`);\n throw e;\n }\n }\n\n}\n\n// =============================================================================\n// AnthropicAgent\n// =============================================================================\n\nexport class AnthropicAgent extends LLMAgent {\n readonly provider = 'anthropic' as const;\n\n protected resolveModel(model: string): string {\n // Bedrock IAM path — the upstream model id must be the cross-region\n // inference-profile form (`us.anthropic.*`), not the bare API id.\n if (process.env.CLAUDE_CODE_USE_BEDROCK === '1') {\n return getBedrockModelId(model);\n }\n return model.startsWith('anthropic/')\n ? model.slice('anthropic/'.length)\n : model;\n }\n\n protected async createClient(): Promise<Anthropic | AnthropicBedrock> {\n // Bedrock IAM path: `resolveRoute` (provider-router) sets\n // CLAUDE_CODE_USE_BEDROCK=1 and clears ANTHROPIC_API_KEY for the\n // pool-funded cloud pod. Auth is the pod's IRSA role — no API key.\n // `AnthropicBedrock` is wire-compatible with `Anthropic` for the\n // `.messages` API this agent uses.\n if (process.env.CLAUDE_CODE_USE_BEDROCK === '1') {\n const { AnthropicBedrock } = await import('@anthropic-ai/bedrock-sdk');\n return new AnthropicBedrock({\n awsRegion:\n process.env.AWS_REGION ??\n process.env.AWS_DEFAULT_REGION ??\n 'us-east-1',\n });\n }\n // SDK construction lives in `adapters/claude/client.ts`. The BYOK\n // resolver writes the raw key into `process.env.ANTHROPIC_API_KEY`\n // before this runs (see `applyRouteToEnv` in provider-router).\n return createAnthropicClient(process.env.ANTHROPIC_API_KEY);\n }\n\n async callText(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n temperature?: number,\n ): Promise<LLMResponse> {\n const client = await this.getClient<Anthropic>();\n const traceId = newLlmTraceId();\n const startedAt = Date.now();\n const resolvedModel = this.resolveModel(model);\n\n // Use prompt caching beta API (90% discount on cached reads)\n const system: TextBlockParam[] = [\n {\n type: 'text',\n text: systemPrompt,\n cache_control: { type: 'ephemeral' },\n },\n ];\n\n try {\n const response = await this.apiCall(() =>\n client.messages.create({\n model: resolvedModel,\n max_tokens: maxTokens ?? 4096,\n system,\n messages: [{ role: 'user', content: userPrompt }],\n ...(temperature !== undefined && { temperature }),\n }),\n );\n\n const usage = response.usage as typeof response.usage & {\n cache_creation_input_tokens?: number | null;\n cache_read_input_tokens?: number | null;\n };\n const cacheCreated = usage.cache_creation_input_tokens ?? 0;\n const cacheRead = usage.cache_read_input_tokens ?? 0;\n if (cacheCreated || cacheRead) {\n console.log(`[anthropic] callText cache: created=${cacheCreated} read=${cacheRead} input=${usage.input_tokens} output=${usage.output_tokens}`);\n }\n\n const text = response.content\n .filter((block): block is TextBlock => block.type === 'text')\n .map((block) => block.text)\n .join('');\n\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callText',\n systemPrompt,\n userPrompt,\n result: {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n cacheCreated,\n cacheRead,\n text,\n },\n });\n\n return {\n text,\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n };\n } catch (e) {\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callText',\n systemPrompt,\n userPrompt,\n error: { message: e instanceof Error ? e.message : String(e) },\n });\n throw e;\n }\n }\n\n async callTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMToolDef[],\n toolChoice: 'required' | 'auto' = 'required',\n _scopedTools?: LLMToolDef[],\n ): Promise<LLMToolCallResponse> {\n const client = await this.getClient<Anthropic>();\n const traceId = newLlmTraceId();\n const startedAt = Date.now();\n const resolvedModel = this.resolveModel(model);\n\n // Cache system prompt + tools via prompt caching beta (90% discount)\n const system: TextBlockParam[] = [\n {\n type: 'text',\n text: systemPrompt,\n cache_control: { type: 'ephemeral' },\n },\n ];\n\n const cachedTools: Anthropic.Tool[] = tools.map((t, i) => ({\n name: t.name,\n description: t.description,\n input_schema: t.parameters as Anthropic.Tool.InputSchema,\n // Mark last tool to cache the entire tool list\n ...(i === tools.length - 1\n ? { cache_control: { type: 'ephemeral' as const } }\n : {}),\n }));\n\n try {\n // `max_tokens >= 21_334` mandates streaming on the\n // @anthropic-ai/sdk >=0.40 path (the API rejects non-streamed\n // long-form generation with `Streaming is required for\n // operations that may take longer than 10 minutes`). We still\n // want the final-message shape downstream, so use the stream\n // helper's `finalMessage()` which folds the events back to the\n // same `Message` Type the non-streaming path returned.\n const response = await this.apiCall(() =>\n client.messages\n .stream({\n model: resolvedModel,\n max_tokens: 32768,\n system,\n messages: [{ role: 'user', content: userPrompt }],\n tools: cachedTools,\n tool_choice: { type: toolChoice === 'required' ? 'any' : 'auto' },\n })\n .finalMessage(),\n );\n\n const usage = response.usage as typeof response.usage & {\n cache_creation_input_tokens?: number | null;\n cache_read_input_tokens?: number | null;\n };\n const cacheCreated = usage.cache_creation_input_tokens ?? 0;\n const cacheRead = usage.cache_read_input_tokens ?? 0;\n if (cacheCreated || cacheRead) {\n console.log(`[anthropic] callTools cache: created=${cacheCreated} read=${cacheRead} input=${usage.input_tokens} output=${usage.output_tokens}`);\n }\n\n const toolUses = response.content.filter(\n (block): block is ToolUseBlock => block.type === 'tool_use',\n );\n\n const toolCalls = toolUses.map((tu) => ({\n id: tu.id,\n name: tu.name,\n input: (tu.input ?? {}) as JsonObject,\n }));\n\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callTools',\n systemPrompt,\n userPrompt,\n tools: summarizeTools(tools),\n result: {\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n cacheCreated,\n cacheRead,\n toolCalls: toolCalls.map((c) => ({ name: c.name, input: c.input })),\n },\n });\n\n return {\n toolCalls,\n inputTokens: response.usage.input_tokens,\n outputTokens: response.usage.output_tokens,\n cacheReadTokens: cacheRead,\n cacheCreationTokens: cacheCreated,\n };\n } catch (e) {\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callTools',\n systemPrompt,\n userPrompt,\n tools: summarizeTools(tools),\n error: { message: e instanceof Error ? e.message : String(e) },\n });\n throw e;\n }\n }\n\n async callWithTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number,\n ): Promise<LLMWithToolsResponse> {\n const client = await this.getClient<Anthropic>();\n const resolvedModel = this.resolveModel(model);\n const traceId = newLlmTraceId();\n const startedAt = Date.now();\n\n const anthropicTools: Anthropic.Tool[] = tools.map((t) => ({\n name: t.name,\n description: t.description,\n input_schema: t.parameters as Anthropic.Tool.InputSchema,\n }));\n\n const messages: Anthropic.MessageParam[] = [\n { role: 'user', content: userPrompt },\n ];\n let totalIn = 0;\n let totalOut = 0;\n let allText = '';\n\n try {\n for (let turn = 0; turn < maxTurns; turn++) {\n // Same streaming requirement as callTools — see comment there.\n const response = await this.apiCall(() =>\n client.messages\n .stream({\n model: resolvedModel,\n max_tokens: 32768,\n system: systemPrompt,\n messages,\n tools: anthropicTools,\n })\n .finalMessage(),\n );\n totalIn += response.usage.input_tokens;\n totalOut += response.usage.output_tokens;\n\n for (const block of response.content) {\n if (block.type === 'text') allText += block.text;\n }\n\n const toolUses = response.content.filter(\n (b): b is ToolUseBlock => b.type === 'tool_use',\n );\n if (toolUses.length === 0) break;\n\n messages.push({ role: 'assistant', content: response.content });\n\n const toolResults: Anthropic.ToolResultBlockParam[] = [];\n for (const tu of toolUses) {\n const tool = tools.find((t) => t.name === tu.name);\n if (!tool) {\n toolResults.push({\n type: 'tool_result',\n tool_use_id: tu.id,\n content: `Tool '${tu.name}' not found`,\n });\n continue;\n }\n const result = await tool.handler(\n (tu.input ?? {}) as JsonObject,\n );\n toolResults.push({\n type: 'tool_result',\n tool_use_id: tu.id,\n content: result.content[0]?.text ?? '',\n });\n }\n messages.push({ role: 'user', content: toolResults });\n }\n\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callWithTools',\n systemPrompt,\n userPrompt,\n tools: tools.map((t) => ({ name: t.name, description: t.description })),\n result: {\n inputTokens: totalIn,\n outputTokens: totalOut,\n text: allText,\n turnsUsed: messages.length,\n },\n });\n\n return {\n text: allText,\n inputTokens: totalIn,\n outputTokens: totalOut,\n turnsUsed: messages.length,\n };\n } catch (e) {\n const endedAt = Date.now();\n emitLlmTraceEvent({\n id: traceId,\n at: startedAt,\n endedAt,\n durationMs: endedAt - startedAt,\n provider: 'anthropic',\n model: resolvedModel,\n kind: 'callWithTools',\n systemPrompt,\n userPrompt,\n tools: tools.map((t) => ({ name: t.name, description: t.description })),\n error: { message: e instanceof Error ? e.message : String(e) },\n });\n throw e;\n }\n }\n}\n\n// =============================================================================\n// OpenAIAgent\n// =============================================================================\n\nexport class OpenAIAgent extends LLMAgent {\n readonly provider = 'openai' as const;\n\n protected resolveModel(model: string): string {\n return model.startsWith('openai/')\n ? model.slice('openai/'.length)\n : model;\n }\n\n protected async createClient(): Promise<OpenAI> {\n const { default: OpenAISDK } = await import('openai');\n return new OpenAISDK({ apiKey: process.env.OPENAI_API_KEY });\n }\n\n async callText(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n temperature?: number,\n ): Promise<LLMResponse> {\n const client = await this.getClient<OpenAI>();\n const response: OpenAIResponse = await this.apiCall(() =>\n client.responses.create({\n model: this.resolveModel(model),\n instructions: systemPrompt,\n input: [{ role: 'user', content: userPrompt }],\n ...(maxTokens && { max_output_tokens: maxTokens }),\n ...(temperature !== undefined && { temperature }),\n }),\n );\n\n let text = '';\n for (const item of response.output) {\n if (item.type === 'message') {\n for (const part of item.content) {\n if (part.type === 'output_text') text += part.text;\n }\n }\n }\n\n return {\n text,\n inputTokens: response.usage?.input_tokens ?? 0,\n outputTokens: response.usage?.output_tokens ?? 0,\n };\n }\n\n async callTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMToolDef[],\n toolChoice: 'required' | 'auto' = 'required',\n _scopedTools?: LLMToolDef[],\n ): Promise<LLMToolCallResponse> {\n const client = await this.getClient<OpenAI>();\n // strict: true enables constrained decoding — guarantees valid JSON matching the schema.\n // Requires additionalProperties: false on all objects and all fields in required.\n const openaiTools = tools.map((t) => ({\n type: 'function' as const,\n name: t.name,\n description: t.description,\n parameters: addStrictSchemaConstraints(t.parameters),\n strict: true,\n }));\n\n // Consume pending tool results — prepend to input for proper contract\n const pending = this.pendingToolResults;\n this.pendingToolResults = [];\n const input = pending.length > 0\n ? [...pending, { role: 'user' as const, content: userPrompt }]\n : [{ role: 'user' as const, content: userPrompt }];\n\n const response: OpenAIResponse = await this.apiCall(() =>\n client.responses.create({\n model: this.resolveModel(model),\n instructions: systemPrompt,\n input,\n tools: openaiTools,\n tool_choice: toolChoice,\n store: true, // Enable response storage + server-side chaining\n ...(this.lastSessionId && { previous_response_id: this.lastSessionId }),\n }),\n );\n\n // Save session ID for chaining subsequent calls\n this.lastSessionId = response.id;\n\n // Log cache utilization\n const usage = response.usage;\n if (usage) {\n // Typed in the SDK as required, but widened to optional here —\n // tolerate responses that omit the breakdown at runtime.\n const cached: { cached_tokens?: number } | undefined =\n usage.input_tokens_details;\n if (cached?.cached_tokens) {\n console.log(`[openai] session ${this.lastSessionId ? 'chained' : 'new'}: ${cached.cached_tokens} cached of ${usage.input_tokens} input`);\n }\n }\n\n const functionCalls = response.output.filter(\n (o): o is ResponseFunctionToolCall => o.type === 'function_call',\n );\n\n return {\n toolCalls: functionCalls.map((fc) => ({\n id: fc.call_id,\n name: fc.name,\n input: JSON.parse(fc.arguments ?? '{}') as JsonObject,\n })),\n inputTokens: response.usage?.input_tokens ?? 0,\n outputTokens: response.usage?.output_tokens ?? 0,\n };\n }\n\n // Pending tool results — stored by sendToolResult, consumed by next callTools\n private pendingToolResults: OpenAI.Responses.ResponseInputItem[] = [];\n\n override async sendToolResult(results: LLMToolResult[]): Promise<void> {\n // Store results locally — they'll be prepended to the next callTools input.\n // No API call here! Saves a round-trip.\n this.pendingToolResults = results.map((r) => ({\n type: 'function_call_output',\n call_id: r.callId ?? '',\n output: r.result,\n }));\n }\n\n async callWithTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number,\n ): Promise<LLMWithToolsResponse> {\n const client = await this.getClient<OpenAI>();\n const resolvedModel = this.resolveModel(model);\n const openaiTools = tools.map((t) => ({\n type: 'function' as const,\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n strict: false,\n }));\n\n let input: OpenAI.Responses.ResponseInputItem[] = [\n { role: 'user', content: userPrompt },\n ];\n let totalIn = 0;\n let totalOut = 0;\n let allText = '';\n\n for (let turn = 0; turn < maxTurns; turn++) {\n const response: OpenAIResponse = await this.apiCall(() =>\n client.responses.create({\n model: resolvedModel,\n instructions: systemPrompt,\n input,\n tools: openaiTools,\n }),\n );\n totalIn += response.usage?.input_tokens ?? 0;\n totalOut += response.usage?.output_tokens ?? 0;\n\n const functionCalls = response.output.filter(\n (o): o is ResponseFunctionToolCall => o.type === 'function_call',\n );\n for (const item of response.output) {\n if (item.type === 'message') {\n for (const part of item.content) {\n if (part.type === 'output_text') allText += part.text;\n }\n }\n }\n\n if (functionCalls.length === 0) break;\n\n input = [\n ...(response.output as OpenAI.Responses.ResponseInputItem[]),\n ];\n for (const fc of functionCalls) {\n const tool = tools.find((t) => t.name === fc.name);\n const result = tool\n ? await tool.handler(\n JSON.parse(fc.arguments ?? '{}') as JsonObject,\n )\n : { content: [{ text: `Tool '${fc.name}' not found` }] };\n input.push({\n type: 'function_call_output',\n call_id: fc.call_id,\n output: result.content[0]?.text ?? '',\n });\n }\n }\n\n return {\n text: allText,\n inputTokens: totalIn,\n outputTokens: totalOut,\n turnsUsed: input.length,\n };\n }\n}\n\n// =============================================================================\n// GoogleAgent — uses Interactions API (server-side state, automatic caching)\n// =============================================================================\n\n/**\n * Concatenate text across all `model_output` steps of an interaction\n * (@google/genai >= 2.0.0 'steps' schema). Steps form a discriminated\n * union — even at thinking_level 'minimal' a `thought` step is present,\n * so iterate by discriminant and skip step types we don't consume.\n */\nfunction interactionText(interaction: Interactions.Interaction): string {\n let text = '';\n for (const step of interaction.steps ?? []) {\n if (step.type === 'model_output') {\n for (const content of step.content ?? []) {\n if (content.type === 'text') {\n text += content.text;\n }\n }\n }\n }\n return text;\n}\n\n/** Collect the function-call steps of an interaction. */\nfunction functionCallSteps(\n interaction: Interactions.Interaction,\n): Interactions.FunctionCallStep[] {\n return (interaction.steps ?? []).filter(\n (s): s is Interactions.FunctionCallStep => s.type === 'function_call',\n );\n}\n\n/**\n * Wrap a user prompt as a `user_input` step. In the 2.x request union a\n * mixed input array is `Array<Step>` — bare `{type:'text'}` content is\n * not a Step, so prompts sent alongside function_result steps must be\n * wrapped.\n */\nfunction toUserInputStep(text: string): Interactions.UserInputStep {\n return { type: 'user_input', content: [{ type: 'text', text }] };\n}\n\nexport class GoogleAgent extends LLMAgent {\n readonly provider = 'google' as const;\n\n protected resolveModel(model: string): string {\n // Strip the LiteLLM transport prefix `gemini/` (Google AI Studio\n // route) so the GenAI SDK receives the bare model id it expects.\n // Pre-slice-#43 close-out this stripped `google/` instead — which\n // (a) doesn't match LiteLLM's `gemini/` convention and (b) silently\n // no-op'd against canonical `gemini/...` strings, then passed\n // them to the GenAI SDK which 4xx's on the prefixed form. Fixed\n // as part of the slice #43 audit. Bare ids pass through verbatim\n // (typed `LlmRoute` already guarantees wire-canonical at every\n // OSS call site).\n return model.startsWith('gemini/')\n ? model.slice('gemini/'.length)\n : model;\n }\n\n protected async createClient(): Promise<GoogleGenAI> {\n const { GoogleGenAI: GoogleGenAISDK } = await import('@google/genai');\n return new GoogleGenAISDK({\n apiKey: process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY,\n httpOptions: { timeout: 300_000 }, // 5 min — Pro models can be slow\n });\n }\n\n async callText(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n temperature?: number,\n ): Promise<LLMResponse> {\n const client = await this.getClient<GoogleGenAI>();\n\n const generationConfig: Interactions.GenerationConfig = {\n ...(maxTokens ? { max_output_tokens: maxTokens } : {}),\n ...(temperature !== undefined ? { temperature } : {}),\n };\n\n const interaction = await this.apiCall(() =>\n client.interactions.create({\n model: this.resolveModel(model),\n system_instruction: systemPrompt,\n input: userPrompt,\n generation_config:\n Object.keys(generationConfig).length > 0 ? generationConfig : undefined,\n }),\n );\n\n return {\n text: interactionText(interaction),\n inputTokens: interaction.usage?.total_input_tokens ?? 0,\n outputTokens: interaction.usage?.total_output_tokens ?? 0,\n };\n }\n\n async callTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMToolDef[],\n _toolChoice: 'required' | 'auto' = 'required',\n scopedTools?: LLMToolDef[],\n ): Promise<LLMToolCallResponse> {\n const client = await this.getClient<GoogleGenAI>();\n\n\n const interactionTools: Interactions.Function[] = tools.map((t) => ({\n type: 'function' as const,\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n }));\n const scopedInteractionTools: Interactions.Function[] | undefined = scopedTools?.map((t) => ({\n type: 'function' as const,\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n }));\n\n // Chain off previous interaction if available — server has system prompt + tools\n const resolvedModel = this.resolveModel(model);\n\n // Consume pending tool results — prepend them to the input so the API\n // sees function_result + the new prompt (as a user_input step) in one\n // call (saves a round-trip)\n const pending = this.pendingToolResults;\n this.pendingToolResults = [];\n const input: string | Interactions.Step[] = pending.length > 0\n ? [...pending, toUserInputStep(userPrompt)]\n : userPrompt;\n\n const createInteraction = () =>\n this.lastSessionId\n ? client.interactions.create({\n model: resolvedModel,\n previous_interaction_id: this.lastSessionId,\n input,\n tools: interactionTools,\n generation_config: { max_output_tokens: 16384 },\n })\n : client.interactions.create({\n model: resolvedModel,\n system_instruction: systemPrompt,\n tools: interactionTools,\n input: userPrompt,\n generation_config: { max_output_tokens: 16384 },\n });\n\n // Retry up to 3 attempts for malformed_tool_call (model generates invalid JSON).\n // If all 3 fail AND scopedTools were provided, one final attempt with the\n // narrower scoped tool schema. Universal runtime-signal fallback — the\n // signal is the transport error, not the provider identity.\n let interaction!: Interactions.Interaction;\n const MAX_MALFORMED_RETRIES = 3;\n let succeeded = false;\n for (let attempt = 0; attempt < MAX_MALFORMED_RETRIES; attempt++) {\n try {\n if (attempt === 0) {\n interaction = await this.apiCall(createInteraction);\n } else {\n const jsonHint = '\\n\\nIMPORTANT: Your previous response had invalid JSON. Produce valid JSON in your tool call arguments.';\n const retryPrompt = userPrompt + jsonHint;\n interaction = await this.apiCall(() =>\n this.lastSessionId\n ? client.interactions.create({\n model: resolvedModel,\n previous_interaction_id: this.lastSessionId,\n input: pending.length > 0\n ? [...pending, toUserInputStep(retryPrompt)]\n : retryPrompt,\n tools: interactionTools,\n generation_config: { max_output_tokens: 16384 },\n })\n : client.interactions.create({\n model: resolvedModel,\n system_instruction: systemPrompt,\n tools: interactionTools,\n input: retryPrompt,\n generation_config: { max_output_tokens: 16384 },\n }),\n );\n }\n succeeded = true;\n break;\n } catch (e: unknown) {\n const msg = e instanceof Error ? e.message : String(e);\n if (msg.includes('malformed_tool_call') && attempt < MAX_MALFORMED_RETRIES - 1) {\n console.warn(`[google] malformed_tool_call (attempt ${attempt + 1}/${MAX_MALFORMED_RETRIES}) — retrying`);\n continue;\n }\n if (msg.includes('malformed_tool_call') && scopedInteractionTools) {\n // Exhausted primary retries — try once more with the scoped\n // tool schema. The narrower tool forces a smaller payload\n // that's less likely to trip JSON emission.\n console.warn('[google] malformed_tool_call exhausted — retrying with scoped tool schema');\n const scopedHint = '\\n\\nYour previous response exceeded the tool-call payload budget. Produce a SINGLE small change (≤20 lines) using the narrowed tool schema.';\n const scopedPrompt = userPrompt + scopedHint;\n try {\n interaction = await this.apiCall(() =>\n this.lastSessionId\n ? client.interactions.create({\n model: resolvedModel,\n previous_interaction_id: this.lastSessionId,\n input: pending.length > 0\n ? [...pending, toUserInputStep(scopedPrompt)]\n : scopedPrompt,\n tools: scopedInteractionTools,\n generation_config: { max_output_tokens: 16384 },\n })\n : client.interactions.create({\n model: resolvedModel,\n system_instruction: systemPrompt,\n tools: scopedInteractionTools,\n input: scopedPrompt,\n generation_config: { max_output_tokens: 16384 },\n }),\n );\n succeeded = true;\n break;\n } catch (e2: unknown) {\n const msg2 = e2 instanceof Error ? e2.message : String(e2);\n console.error(`[google] scoped retry FAILED: ${msg2.slice(0, 300)}`);\n throw e2;\n }\n }\n console.error(`[google] callTools FAILED: ${msg.slice(0, 300)}`);\n throw e;\n }\n }\n if (!succeeded) throw new Error('[google] callTools: exhausted retries without success');\n\n // Save session ID for chaining subsequent calls\n this.lastSessionId = interaction.id;\n\n const toolCalls = functionCallSteps(interaction).map((fc) => ({\n id: fc.id,\n name: fc.name,\n input: toolArgsToJsonObject(fc.arguments),\n }));\n\n return {\n toolCalls,\n inputTokens: interaction.usage?.total_input_tokens ?? 0,\n outputTokens: interaction.usage?.total_output_tokens ?? 0,\n };\n }\n\n // Pending tool results — stored by sendToolResult, consumed by next callTools\n private pendingToolResults: Interactions.FunctionResultStep[] = [];\n\n override async sendToolResult(results: LLMToolResult[]): Promise<void> {\n // Store results locally — they'll be prepended to the next callTools input.\n // No API call here! Saves ~5.8s per turn.\n this.pendingToolResults = results.map((r) => ({\n type: 'function_result' as const,\n call_id: r.callId ?? '',\n name: r.name,\n result: r.result,\n is_error: r.isError,\n }));\n }\n\n async callWithTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number,\n ): Promise<LLMWithToolsResponse> {\n const client = await this.getClient<GoogleGenAI>();\n\n\n const interactionTools: Interactions.Function[] = tools.map((t) => ({\n type: 'function' as const,\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n }));\n\n let totalIn = 0;\n let totalOut = 0;\n let allText = '';\n let turnsUsed = 0;\n\n // Turn 1: system instruction + tools + user prompt\n let interaction = await this.apiCall(() =>\n client.interactions.create({\n model: this.resolveModel(model),\n system_instruction: systemPrompt,\n tools: interactionTools,\n input: userPrompt,\n }),\n );\n\n for (let turn = 0; turn < maxTurns; turn++) {\n turnsUsed = turn + 1;\n\n if (interaction.usage) {\n totalIn += interaction.usage.total_input_tokens ?? 0;\n totalOut += interaction.usage.total_output_tokens ?? 0;\n }\n\n // Collect text\n allText += interactionText(interaction);\n\n // Collect function calls\n const fnCalls = functionCallSteps(interaction);\n\n if (fnCalls.length === 0) break;\n\n // Execute tools and build function_result inputs\n const results: Interactions.FunctionResultStep[] = [];\n for (const fc of fnCalls) {\n const tool = tools.find((t) => t.name === fc.name);\n if (!tool) {\n results.push({\n type: 'function_result',\n call_id: fc.id,\n name: fc.name,\n result: JSON.stringify({ error: `Tool '${fc.name}' not found` }),\n is_error: true,\n });\n continue;\n }\n const result = await tool.handler(toolArgsToJsonObject(fc.arguments));\n results.push({\n type: 'function_result',\n call_id: fc.id,\n name: fc.name,\n result: result.content.map((c) => c.text).join('\\n'),\n });\n }\n\n // Next turn: only send function results — server has the history\n interaction = await this.apiCall(() =>\n client.interactions.create({\n model: this.resolveModel(model),\n previous_interaction_id: interaction.id,\n input: results,\n }),\n );\n }\n\n return {\n text: allText,\n inputTokens: totalIn,\n outputTokens: totalOut,\n turnsUsed,\n };\n }\n}\n\n// =============================================================================\n// OpenRouterAgent\n// =============================================================================\n\nexport class OpenRouterAgent extends LLMAgent {\n readonly provider = 'openrouter' as const;\n\n // Client-side session history — system prompt sent once, subsequent\n // callTools() calls append to the conversation without re-sending it.\n private sessionMessages: import('../adapters/openrouter/types').OpenRouterMessage[] = [];\n\n protected resolveModel(model: string): string {\n // Strip 'openrouter/' prefix — OpenRouter API expects 'provider/model'\n // e.g., 'openrouter/anthropic/claude-3.5-sonnet' → 'anthropic/claude-3.5-sonnet'\n return model.startsWith('openrouter/')\n ? model.slice('openrouter/'.length)\n : model;\n }\n\n override resetSession(): void {\n super.resetSession();\n this.sessionMessages = [];\n }\n\n protected async createClient(): Promise<unknown> {\n const { OpenRouterClient } = await import('../adapters/openrouter/client');\n return new OpenRouterClient({\n apiKey: process.env.OPENROUTER_API_KEY!,\n });\n }\n\n async callText(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n temperature?: number,\n ): Promise<LLMResponse> {\n type Client = import('../adapters/openrouter/client').OpenRouterClient;\n const client = await this.getClient<Client>();\n const resolved = this.resolveModel(model);\n\n const response = await this.apiCall(() =>\n client.chatCompletion({\n model: resolved,\n messages: [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userPrompt },\n ],\n max_tokens: maxTokens ?? 4096,\n ...(temperature !== undefined && { temperature }),\n }),\n );\n\n const text = response.choices[0]?.message.content ?? '';\n return {\n text,\n inputTokens: response.usage.prompt_tokens,\n outputTokens: response.usage.completion_tokens,\n };\n }\n\n async callTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMToolDef[],\n toolChoice?: 'required' | 'auto',\n _scopedTools?: LLMToolDef[],\n ): Promise<LLMToolCallResponse> {\n type Client = import('../adapters/openrouter/client').OpenRouterClient;\n const client = await this.getClient<Client>();\n const resolved = this.resolveModel(model);\n\n const orTools = tools.map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n }));\n\n // Build messages — first call sends system prompt, subsequent calls reuse session\n if (this.sessionMessages.length === 0) {\n this.sessionMessages.push({ role: 'system', content: systemPrompt });\n }\n this.sessionMessages.push({ role: 'user', content: userPrompt });\n\n const response = await this.apiCall(() =>\n client.chatCompletion({\n model: resolved,\n messages: this.sessionMessages,\n tools: orTools,\n tool_choice: toolChoice ?? 'auto',\n }),\n );\n\n // Append assistant response to session history\n const choice = response.choices[0];\n if (choice?.message) {\n this.sessionMessages.push({\n role: 'assistant',\n content: choice.message.content,\n tool_calls: choice.message.tool_calls,\n });\n }\n\n const toolCalls = (choice?.message.tool_calls ?? []).map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments || '{}') as JsonObject,\n }));\n\n return {\n toolCalls,\n inputTokens: response.usage.prompt_tokens,\n outputTokens: response.usage.completion_tokens,\n };\n }\n\n override async sendToolResult(results: LLMToolResult[]): Promise<void> {\n // Append tool results to session history — proper chat contract\n for (const r of results) {\n this.sessionMessages.push({\n role: 'tool',\n tool_call_id: r.callId,\n content: r.result,\n });\n }\n }\n\n async callWithTools(\n model: string,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number,\n ): Promise<LLMWithToolsResponse> {\n type Client = import('../adapters/openrouter/client').OpenRouterClient;\n const client = await this.getClient<Client>();\n const resolved = this.resolveModel(model);\n\n const orTools = tools.map((t) => ({\n type: 'function' as const,\n function: { name: t.name, description: t.description, parameters: t.parameters },\n }));\n\n type ORMessage = import('../adapters/openrouter/types').OpenRouterMessage;\n const messages: ORMessage[] = [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userPrompt },\n ];\n\n let totalInput = 0;\n let totalOutput = 0;\n let turnsUsed = 0;\n let finalText = '';\n\n for (let turn = 0; turn < maxTurns; turn++) {\n turnsUsed = turn + 1;\n\n const response = await this.apiCall(() =>\n client.chatCompletion({\n model: resolved,\n messages: messages as import('../adapters/openrouter/types').OpenRouterMessage[],\n tools: orTools,\n tool_choice: 'auto',\n }),\n );\n\n totalInput += response.usage.prompt_tokens;\n totalOutput += response.usage.completion_tokens;\n\n const choice = response.choices[0];\n if (!choice) break;\n\n if (choice.message.content) {\n finalText = choice.message.content;\n }\n\n const toolCalls = choice.message.tool_calls;\n if (!toolCalls || toolCalls.length === 0) break;\n\n messages.push({\n role: 'assistant',\n content: choice.message.content,\n tool_calls: toolCalls,\n });\n\n for (const tc of toolCalls) {\n const toolDef = tools.find((t) => t.name === tc.function.name);\n let resultText: string;\n if (!toolDef) {\n resultText = JSON.stringify({ error: `Tool '${tc.function.name}' not found` });\n } else {\n const args = JSON.parse(tc.function.arguments || '{}') as JsonObject;\n const result = await toolDef.handler(args);\n resultText = result.content.map((c) => c.text).join('\\n');\n }\n messages.push({ role: 'tool', tool_call_id: tc.id, content: resultText });\n }\n }\n\n return { text: finalText, inputTokens: totalInput, outputTokens: totalOutput, turnsUsed };\n }\n}\n\n// =============================================================================\n// Agent Registry\n// =============================================================================\n\n/**\n * Create a fresh agent instance for the given provider.\n * Each call returns a new instance — no shared state between callers.\n */\nexport function createAgent(provider: AgentConfig['provider']): LLMAgent {\n switch (provider) {\n case 'anthropic':\n return new AnthropicAgent();\n case 'openai':\n return new OpenAIAgent();\n case 'google':\n return new GoogleAgent();\n case 'openrouter':\n return new OpenRouterAgent();\n }\n}\n\n// =============================================================================\n// Backward-compatible free functions\n// =============================================================================\n\nexport async function callLLM(\n config: AgentConfig,\n systemPrompt: string,\n userPrompt: string,\n maxTokens?: number,\n): Promise<LLMResponse> {\n const start = Date.now();\n const agent = createAgent(config.provider);\n const result = await agent.callText(\n config.model,\n systemPrompt,\n userPrompt,\n maxTokens,\n config.temperature,\n );\n console.log(\n `[llm-router] ${config.provider}/${config.model} | ${Date.now() - start}ms | in=${result.inputTokens} out=${result.outputTokens}`,\n );\n return result;\n}\n\nexport async function callLLMWithTools(\n config: AgentConfig,\n systemPrompt: string,\n userPrompt: string,\n tools: LLMTool[],\n maxTurns: number = 10,\n): Promise<LLMWithToolsResponse> {\n const start = Date.now();\n const agent = createAgent(config.provider);\n const result = await agent.callWithTools(\n config.model,\n systemPrompt,\n userPrompt,\n tools,\n maxTurns,\n );\n console.log(\n `[llm-router] agentic ${config.provider}/${config.model} | ${Date.now() - start}ms | turns=${result.turnsUsed} | in=${result.inputTokens} out=${result.outputTokens}`,\n );\n return result;\n}\n\n","// packages/ui-gen/src/evaluation/evaluator.ts\n//\n// Unified, provider-agnostic UI evaluation.\n//\n// One evaluation function that works with Claude, OpenAI, and Google.\n// Routes to the correct API based on config.provider.\n//\n// Responsibilities (things self_check CANNOT verify):\n// - Visual design quality, hierarchy, composition\n// - Interaction polish (hover, transitions, animations)\n// - Prompt completeness (does it match what was requested?)\n// - Data rendering quality (not just present, but well-formatted)\n//\n// Does NOT re-check (already handled by self_check):\n// - Hardcoded hex colors (self_check catches these)\n// - Raw pixel values (self_check catches these)\n// - Wrong imports (self_check catches these)\n// - Missing Props interface (self_check catches these)\n// - Null safety (TypeChecker strictNullChecks catches these)\n\nimport type { EvaluationConfig, EvaluationContext, EvaluationResult, DimensionScores, EvaluationIssue } from './types';\nimport { createAgent } from '../harness/llm-router';\nimport type { LLMToolDef } from '../harness/llm-router';\n\n// ---------------------------------------------------------------------------\n// Evaluation tool (structured output via tool calling)\n// ---------------------------------------------------------------------------\n\nconst EVAL_TOOL: LLMToolDef = {\n name: \"submit_evaluation\",\n description: \"Submit the UI quality evaluation scores and feedback.\",\n parameters: {\n type: \"object\",\n properties: {\n completeness: { type: \"number\", description: \"0-100: Does the component implement ALL features from the prompt?\" },\n visualDesign: { type: \"number\", description: \"0-100: Layout, visual hierarchy, spacing, polished appearance\" },\n interactivity: { type: \"number\", description: \"0-100: Hover/focus states, transitions, form validation, loading states\" },\n accessibility: { type: \"number\", description: \"0-100: Semantic HTML, ARIA labels, keyboard navigation, contrast\" },\n codeQuality: { type: \"number\", description: \"0-100: Clean structure, state management, event handlers, defaults\" },\n issues: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n dimension: { type: \"string\" },\n severity: { type: \"string\", description: \"critical, major, or minor\" },\n description: { type: \"string\" },\n fix: { type: \"string\" },\n },\n required: [\"dimension\", \"severity\", \"description\", \"fix\"],\n },\n description: \"List of specific issues found\",\n },\n critique: { type: \"string\", description: \"2-3 sentences: what's good and what needs improvement\" },\n },\n required: [\"completeness\", \"visualDesign\", \"interactivity\", \"accessibility\", \"codeQuality\", \"issues\", \"critique\"],\n },\n};\n\n// ---------------------------------------------------------------------------\n// Unified evaluation prompt\n// ---------------------------------------------------------------------------\n\nconst EVAL_SYSTEM_PROMPT = `You are a UI quality evaluator for ggui-generated React components.\n\nThe code has ALREADY passed automated checks for:\n- Design token usage (no hardcoded colors/spacing)\n- Import constraints (only react + @ggui-ai/design)\n- TypeScript types (Props interface, null safety)\n- Compilation + render smoke test\n\nDo NOT penalize for things the automated checks already cover. Focus ONLY on quality aspects that require human judgment.\n\n## Dimensions (score each 0-100)\n\n1. **completeness** (25%): Does the component implement ALL features from the original prompt? Are all requested UI elements present? Does it use ALL props from the contract (especially nested fields in arrays)?\n\n2. **visualDesign** (25%): Is the layout well-composed? Clear visual hierarchy (headings > subheadings > body)? Good use of whitespace and spacing? Proper use of primitive variants (primary for CTAs, outline for secondary, ghost for tertiary)? Professional, polished appearance?\n\n3. **interactivity** (20%): Are interactive elements polished? Hover/focus states on buttons and links? Smooth transitions (200ms ease)? Form validation with inline errors? Disabled states during submission? Loading indicators? Keyboard navigation?\n\n4. **accessibility** (15%): Semantic HTML (headings, lists, landmarks)? ARIA labels on inputs and interactive elements? Keyboard-navigable? Focus management? Readable text contrast?\n\n5. **codeQuality** (15%): Clean component structure? Proper state management? Event handlers wired correctly? No unnecessary re-renders? Default prop values for all optional props?\n\n## Scoring Scale\n\n- 90-100: Production-ready. Polished layout, smooth interactions, full accessibility, clean code.\n- 80-89: Good. Minor improvements needed (a missing hover state, slightly tight spacing).\n- 70-79: Acceptable. Works correctly but lacks polish (no transitions, generic layout).\n- 60-69: Below standard. Missing features, poor layout, no interactive states.\n- Below 60: Broken or fundamentally incomplete.\n\nCall the \\`submit_evaluation\\` tool with your scores, issues, and critique.`;\n\n// ---------------------------------------------------------------------------\n// Provider-agnostic evaluation\n// ---------------------------------------------------------------------------\n\n/**\n * Run a single evaluation round using any LLM provider.\n *\n * Provider-agnostic: routes to Claude, OpenAI, or Google API based on config.provider.\n * Falls back to Claude if no provider is specified.\n */\nexport async function runEvaluation(\n context: EvaluationContext,\n config: EvaluationConfig,\n): Promise<EvaluationResult> {\n const providerName = config.provider ?? 'claude';\n const model = config.model || getDefaultEvalModel(providerName);\n const routerProvider = providerName === 'claude' ? 'anthropic' as const : providerName as 'openai' | 'google' | 'openrouter';\n\n const userPrompt = buildEvalUserPrompt(context);\n const agent = createAgent(routerProvider);\n\n // Use tool calling for structured output — no JSON parsing needed\n const response = await agent.callTools(\n model,\n EVAL_SYSTEM_PROMPT,\n userPrompt,\n [EVAL_TOOL],\n 'required',\n );\n\n const call = response.toolCalls[0];\n if (!call) {\n throw new Error('Evaluator did not return a tool call');\n }\n\n const raw = call.input as Record<string, unknown>;\n return buildEvalResult(raw, config.passThreshold, response.inputTokens, response.outputTokens);\n}\n\n// ---------------------------------------------------------------------------\n// (Provider routing removed — uses LLM router via createAgent/callTools)\n// ---------------------------------------------------------------------------\n\n\n\n// ---------------------------------------------------------------------------\n// User prompt builder\n// ---------------------------------------------------------------------------\n\nfunction buildEvalUserPrompt(context: EvaluationContext): string {\n const parts: string[] = [];\n\n parts.push(`## Original Request\\n${context.originalPrompt}`);\n\n if (context.designContext) {\n parts.push(`## App Design Context\\n${context.designContext}`);\n }\n\n parts.push(`## Source Code\\n\\`\\`\\`tsx\\n${context.sourceCode.slice(0, 10000)}\\n\\`\\`\\``);\n\n return parts.join('\\n\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Response parsing\n// ---------------------------------------------------------------------------\n\n/**\n * Build EvaluationResult from tool call input (structured data, no JSON parsing).\n */\nfunction buildEvalResult(\n raw: Record<string, unknown>,\n passThreshold: number,\n inputTokens: number,\n outputTokens: number,\n): EvaluationResult {\n const dimensions: DimensionScores = {\n completeness: (raw.completeness as number) ?? 0,\n visualPolish: (raw.visualDesign as number) ?? (raw.visualPolish as number) ?? 0,\n interactivity: (raw.interactivity as number) ?? 0,\n accessibility: (raw.accessibility as number) ?? 0,\n codeQuality: (raw.codeQuality as number) ?? 0,\n };\n\n const weights = {\n completeness: 0.25,\n visualPolish: 0.25,\n interactivity: 0.20,\n accessibility: 0.15,\n codeQuality: 0.15,\n };\n\n const finalScore = Math.round(\n dimensions.completeness * weights.completeness +\n dimensions.visualPolish * weights.visualPolish +\n dimensions.interactivity * weights.interactivity +\n dimensions.accessibility * weights.accessibility +\n dimensions.codeQuality * weights.codeQuality,\n );\n\n const rawIssues = (raw.issues ?? []) as Array<Record<string, string>>;\n const issues: EvaluationIssue[] = rawIssues.map((i) => ({\n dimension: i.dimension || 'unknown',\n severity: (i.severity as 'critical' | 'major' | 'minor') || 'minor',\n description: i.description || '',\n fix: i.fix || '',\n }));\n\n return {\n passed: finalScore >= passThreshold,\n finalScore,\n dimensions,\n issues,\n critique: raw.critique as string,\n inputTokens,\n outputTokens,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Default models per provider (cheapest/fastest)\n// ---------------------------------------------------------------------------\n\nfunction getDefaultEvalModel(provider: string): string {\n switch (provider) {\n case 'claude': return 'claude-haiku-4-5-20251001';\n case 'openai': return 'gpt-5.6-luna';\n case 'google': return 'gemini-3.5-flash-lite';\n default: return 'claude-haiku-4-5-20251001';\n }\n}\n","// packages/ui-gen/src/evaluation/message-parsing.ts\n\n/**\n * Shared message parsing utilities for extracting structured data from\n * Claude Agent SDK `query()` messages.\n *\n * These functions are used by evaluator.ts, loop.ts, and generator.ts\n * to capture tool results, source code, and session state from the\n * SDK message stream.\n */\n\nimport type { EvaluationResult } from './types';\n\n// ── SDK message type aliases ────────────────────────────────────────\n\n/** A single SDK message from the `query()` async iterator. */\nexport type SdkMessage = Record<string, unknown>;\n\n/** Content block inside a user or assistant message. */\ntype ContentBlock = Record<string, unknown>;\n\n/** A text item inside a tool_result content array. */\ninterface TextItem {\n type?: string;\n text?: string;\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────\n\n/**\n * Extract tool_result text items from a user-type SDK message.\n * Returns an empty array if the message isn't a user message or has no tool results.\n */\nexport function extractToolResultTexts(message: SdkMessage): string[] {\n if ((message.type as string) !== 'user') return [];\n\n const texts: string[] = [];\n const innerMessage = message.message as SdkMessage | undefined;\n const messageContent = innerMessage?.content as ContentBlock[] | undefined;\n\n if (!Array.isArray(messageContent)) return texts;\n\n for (const contentItem of messageContent) {\n if (contentItem.type === 'tool_result') {\n const toolResultContent = contentItem.content as TextItem[] | undefined;\n if (Array.isArray(toolResultContent)) {\n for (const textItem of toolResultContent) {\n if (textItem.type === 'text' && textItem.text) {\n texts.push(textItem.text);\n }\n }\n }\n }\n }\n\n return texts;\n}\n\n// ── EvaluationResult extraction ─────────────────────────────────────\n\n/**\n * Extract an `EvaluationResult` from an array of SDK messages.\n *\n * Scans for user messages containing a tool_result with JSON that has\n * `finalScore` (number) and `dimensions` fields. Returns the last\n * matching result, or `undefined` if none found.\n *\n * Used by: evaluator.ts\n */\nexport function extractEvalResult(messages: SdkMessage[]): EvaluationResult | undefined {\n let evalResult: EvaluationResult | undefined;\n\n for (const message of messages) {\n const msgStr = JSON.stringify(message);\n if (!msgStr.includes('finalScore') || !msgStr.includes('dimensions')) continue;\n\n for (const text of extractToolResultTexts(message)) {\n if (!text.includes('finalScore')) continue;\n try {\n const parsed = JSON.parse(text) as EvaluationResult;\n if (typeof parsed.finalScore === 'number' && parsed.dimensions) {\n evalResult = parsed;\n }\n } catch {\n // Not valid JSON\n }\n }\n }\n\n return evalResult;\n}\n\n// ── compiledCode extraction ─────────────────────────────────────────\n\n/**\n * Extract `compiledCode` from a single SDK message.\n *\n * Tries two strategies:\n * 1. Regex extraction from the full serialized message (fallback)\n * 2. Structured extraction from user/tool_result content\n *\n * Returns the extracted code or `undefined`.\n *\n * Used by: loop.ts, generator.ts\n */\nexport function extractCompiledCodeFromMessage(message: SdkMessage): string | undefined {\n const msgStr = JSON.stringify(message);\n if (!msgStr.includes('compiledCode')) return undefined;\n\n // Strategy 1: Regex fallback (catches compiledCode in any position)\n let regexCode: string | undefined;\n const match = msgStr.match(/\"compiledCode\"\\s*:\\s*\"([^\"\\\\]*(\\\\.[^\"\\\\]*)*)\"/);\n if (match) {\n try {\n regexCode = JSON.parse(`\"${match[1]}\"`);\n } catch {\n // Not parseable\n }\n }\n\n // Strategy 2: Structured extraction from tool_result\n for (const text of extractToolResultTexts(message)) {\n if (!text.includes('compiledCode')) continue;\n try {\n const parsed = JSON.parse(text);\n if (parsed.success && parsed.compiledCode) {\n return parsed.compiledCode; // Prefer structured over regex\n }\n } catch {\n // Not JSON\n }\n }\n\n return regexCode;\n}\n\n// ── sourceCode extraction ───────────────────────────────────────────\n\n/**\n * Extract source code from an assistant's Write tool_use message.\n *\n * Looks for `tool_use` blocks with `name === 'Write'` and returns\n * the `input.content` string. If multiple Write calls exist, returns\n * the last one (the final version).\n *\n * Used by: loop.ts, generator.ts\n */\nexport function extractSourceCodeFromMessage(message: SdkMessage): string | undefined {\n if ((message.type as string) !== 'assistant') return undefined;\n\n let sourceCode: string | undefined;\n const betaMessage = message.message as SdkMessage | undefined;\n const content = betaMessage?.content as ContentBlock[] | undefined;\n\n if (!Array.isArray(content)) return undefined;\n\n for (const block of content) {\n if (block.type === 'tool_use' && block.name === 'Write') {\n const input = block.input as { content?: string } | undefined;\n if (input?.content) {\n sourceCode = input.content;\n }\n }\n }\n\n return sourceCode;\n}\n\n// ── Batch helpers ───────────────────────────────────────────────────\n\n/**\n * Scan all messages for the last compiledCode value.\n *\n * Convenience wrapper for tests and one-shot extraction.\n */\nexport function extractCompiledCode(messages: SdkMessage[]): string | undefined {\n let compiledCode: string | undefined;\n for (const message of messages) {\n const code = extractCompiledCodeFromMessage(message);\n if (code) compiledCode = code;\n }\n return compiledCode;\n}\n\n/**\n * Scan all messages for the last sourceCode from Write tool_use.\n *\n * Convenience wrapper for tests and one-shot extraction.\n */\nexport function extractSourceCode(messages: SdkMessage[]): string | undefined {\n let sourceCode: string | undefined;\n for (const message of messages) {\n const code = extractSourceCodeFromMessage(message);\n if (code) sourceCode = code;\n }\n return sourceCode;\n}\n","// packages/ui-gen/src/evaluation/prompts.ts\n\nimport type { EvaluationResult } from './types';\n\n/**\n * System prompt for the evaluator agent.\n * Static/cacheable — defines rubric, dimensions, and workflow.\n */\nexport function getEvaluatorSystemPrompt(): string {\n return `# UI Component Evaluator\n\nYou evaluate ggui-generated React components. You MUST call the \\`evaluate_score\\` tool — this is your only task. Do NOT write any text before calling the tool. Analyze the code silently, then immediately call \\`evaluate_score\\` with your scores and issues.\n\n## Dimensions (score each 0-100)\n\n- **Completeness**: All requested features present and functional\n- **Visual Polish**: Layout, spacing, design token usage, DESIGN.md compliance\n- **Interactivity**: Event handlers, state management, callbacks working\n- **Accessibility**: ARIA labels, keyboard nav, semantic HTML, contrast\n- **Code Quality**: Clean structure, proper primitives, no dead code, single default export GeneratedComponent\n\n## Scoring Scale\n\n- 90-100: Excellent, production-ready\n- 70-89: Good, minor improvements possible\n- 50-69: Needs work\n- 30-49: Poor\n- 0-29: Fundamentally broken\n\n## Issue Severities\n\n- **critical**: Missing core features, broken functionality, security problems\n- **major**: Poor accessibility, layout bugs, missing error handling\n- **minor**: Style inconsistencies, naming conventions\n\nIMPORTANT: Call the \\`evaluate_score\\` tool immediately. Do not write analysis text first.`;\n}\n\n/**\n * Build the fix prompt to resume the generator session with evaluation feedback.\n * Issues are grouped by severity (critical first) so the generator prioritizes correctly.\n */\nexport function buildFixPrompt(evalResult: EvaluationResult, originalPrompt: string): string {\n let prompt = `## Evaluation Feedback — Fix Required\n\nYour generated component was evaluated and scored **${evalResult.finalScore}/100** (threshold: 70).\n\n### Scores\n| Dimension | Score |\n|-----------|-------|\n| Completeness | ${evalResult.dimensions.completeness} |\n| Visual Polish | ${evalResult.dimensions.visualPolish} |\n| Interactivity | ${evalResult.dimensions.interactivity} |\n| Accessibility | ${evalResult.dimensions.accessibility} |\n| Code Quality | ${evalResult.dimensions.codeQuality} |\n`;\n\n if (evalResult.critique) {\n prompt += `\n### Overall Critique\n${evalResult.critique}\n`;\n }\n\n // Group issues by severity\n const critical = evalResult.issues.filter((i) => i.severity === 'critical');\n const major = evalResult.issues.filter((i) => i.severity === 'major');\n const minor = evalResult.issues.filter((i) => i.severity === 'minor');\n\n if (critical.length > 0) {\n prompt += `\n### Critical Issues (must fix)\n${critical.map((i) => `- **[${i.dimension}]** ${i.description}\\n Fix: ${i.fix}`).join('\\n')}\n`;\n }\n\n if (major.length > 0) {\n prompt += `\n### Major Issues (should fix)\n${major.map((i) => `- **[${i.dimension}]** ${i.description}\\n Fix: ${i.fix}`).join('\\n')}\n`;\n }\n\n if (minor.length > 0) {\n prompt += `\n### Minor Issues (nice to fix)\n${minor.map((i) => `- **[${i.dimension}]** ${i.description}\\n Fix: ${i.fix}`).join('\\n')}\n`;\n }\n\n prompt += `\n### Instructions\n\nFix the issues above, prioritizing critical and major issues. The original request was:\n\n> ${originalPrompt}\n\nAfter fixing, re-validate and re-compile the component. Write the updated code to Component.tsx, validate it, and compile it.`;\n\n return prompt;\n}\n","// packages/ui-gen/src/evaluation/types.ts\n\n/**\n * Per-dimension quality scores from the evaluator (0-100 each).\n */\nexport interface DimensionScores {\n /** How well the component fulfills the original prompt requirements */\n completeness: number;\n /** Visual quality: layout, typography, spacing, color usage */\n visualPolish: number;\n /** Interaction quality: hover states, transitions, form validation */\n interactivity: number;\n /** Accessibility: ARIA labels, keyboard navigation, contrast ratios */\n accessibility: number;\n /** Code quality: TypeScript types, clean structure, no anti-patterns */\n codeQuality: number;\n}\n\n/**\n * A specific issue found during evaluation.\n */\nexport interface EvaluationIssue {\n /** Which quality dimension this issue belongs to */\n dimension: string;\n /** Human-readable description of what is wrong */\n description: string;\n /** Severity level: critical blocks shipping, major degrades quality, minor is a polish issue */\n severity: 'critical' | 'major' | 'minor';\n /** Suggested fix for the agent to apply */\n fix: string;\n}\n\n/**\n * Result of a single evaluation round.\n */\nexport interface EvaluationResult {\n /** Whether the component passed the quality threshold */\n passed: boolean;\n /** Weighted average score across all dimensions (0-100) */\n finalScore: number;\n /** Per-dimension score breakdown */\n dimensions: DimensionScores;\n /** Specific issues identified in this round */\n issues: EvaluationIssue[];\n /** Free-form critique text from the evaluator LLM */\n critique?: string;\n /** Input tokens consumed by the evaluation LLM call */\n inputTokens?: number;\n /** Output tokens consumed by the evaluation LLM call */\n outputTokens?: number;\n}\n\n/**\n * Quality metadata attached to every generated component\n */\nexport interface QualityMetadata {\n /** Number of evaluation rounds run (0 = strict/no eval) */\n evaluationRounds: number;\n /** Final average score 0-100 */\n finalScore: number;\n /** Per-dimension breakdown */\n dimensions: DimensionScores;\n /** Whether the component passed (score >= threshold) */\n passed: boolean;\n /** Model used for evaluation */\n evaluatorModel: string;\n /** Total evaluation loop time in ms */\n evaluationTimeMs: number;\n /** S3 keys for screenshots (creative only) */\n screenshots?: string[];\n}\n\n/** Hard ceiling for evaluation rounds — never exceed this regardless of config */\nexport const MAX_EVAL_ROUNDS_HARD_LIMIT = 10;\n\n/** Default (soft) max rounds for the balanced strategy */\nexport const DEFAULT_EVAL_MAX_ROUNDS = 10;\n\n/**\n * Configuration for the evaluation loop\n */\nexport interface EvaluationConfig {\n /** Whether evaluation is enabled */\n enabled: boolean;\n /** Model to use for evaluation (default: provider's default) */\n model?: string;\n /** LLM provider for evaluation (default: same as generation provider) */\n provider?: 'claude' | 'openai' | 'google' | 'openrouter';\n /** Minimum average score to pass (default: 70) */\n passThreshold: number;\n /** Maximum evaluation rounds (soft max: 3, hard limit: 5) */\n maxRounds?: number;\n /** Budget cap per evaluation round in USD */\n maxBudgetPerEval?: number;\n /** Budget cap per fix round in USD */\n maxBudgetPerFix?: number;\n}\n\n/**\n * Context passed to the evaluator\n */\nexport interface EvaluationContext {\n /** TSX source code written by the generator */\n sourceCode: string;\n /** Compiled JavaScript output */\n compiledCode: string;\n /** Original user prompt */\n originalPrompt: string;\n /** DESIGN.md content (if present) */\n designContext?: string;\n /** CSS variable tokens for the app theme */\n themeTokens: string;\n}\n","// packages/ui-gen/src/evaluation/loop.ts\n\nimport { query, type McpServerConfig } from '@anthropic-ai/claude-agent-sdk';\nimport { runEvaluation } from './evaluator';\nimport {\n extractCompiledCodeFromMessage,\n extractSourceCodeFromMessage,\n} from './message-parsing';\nimport { buildFixPrompt } from './prompts';\nimport {\n MAX_EVAL_ROUNDS_HARD_LIMIT,\n} from './types';\nimport type {\n EvaluationConfig,\n EvaluationContext,\n EvaluationResult,\n QualityMetadata,\n} from './types';\nimport type { SdkMessage } from './message-parsing';\n\n/**\n * Options for running the evaluation loop.\n *\n * Controls the evaluate-fix-re-evaluate cycle that improves generated\n * component quality until it passes or the round limit is reached.\n */\nexport interface EvaluationLoopOptions {\n /** Session ID of the generator to resume for fixes */\n generatorSessionId: string;\n /** Evaluation context (code, prompt, design, theme) */\n context: EvaluationContext;\n /** Evaluation configuration (thresholds, budgets, round limits) */\n config: EvaluationConfig;\n /** Progress callback for evaluating/fixing status updates */\n onProgress?: (event: { type: 'evaluating' | 'fixing'; round: number }) => void;\n /** Generator context to pass when resuming the session for fixes */\n generatorOptions?: {\n /** Working directory for the generator session */\n cwd?: string;\n /** MCP servers available to the fix agent */\n mcpServers?: Record<string, McpServerConfig>;\n /** Tools the fix agent is allowed to call */\n allowedTools?: string[];\n /** LLM model for fix rounds */\n model?: string;\n /** Environment variables (includes BYOK credentials) */\n env?: Record<string, string>;\n /** Stderr capture callback for debugging */\n stderr?: (data: string) => void;\n };\n}\n\n/**\n * Result of the evaluation loop.\n *\n * Contains the final (possibly fixed) code, quality scores, and\n * the evaluation history from each round.\n */\nexport interface EvaluationLoopResult {\n /** Final compiled code (may be updated by fix rounds) */\n finalCode: string;\n /** Final source code (may be updated by fix rounds) */\n finalSourceCode?: string;\n /** Quality metadata for the generation result */\n qualityMetadata: QualityMetadata;\n /** All evaluation results from each round */\n evaluationResults: EvaluationResult[];\n}\n\n/**\n * Run the evaluation loop: evaluate -> fix -> re-evaluate (up to maxRounds).\n *\n * If the first evaluation passes, returns immediately.\n * If it fails, resumes the generator session with critique feedback,\n * captures the fixed code, and re-evaluates. Repeats until the score\n * passes or the round limit is reached.\n *\n * @param options - Evaluation loop configuration and callbacks\n * @returns The final code, quality metadata, and evaluation history\n */\nexport async function runEvaluationLoop(\n options: EvaluationLoopOptions\n): Promise<EvaluationLoopResult> {\n const { generatorSessionId, context, config, onProgress, generatorOptions } = options;\n const startTime = Date.now();\n const evaluationResults: EvaluationResult[] = [];\n\n let currentCode = context.compiledCode;\n let currentSourceCode: string | undefined = context.sourceCode;\n let round = 0;\n const maxRounds = Math.min(config.maxRounds ?? 3, MAX_EVAL_ROUNDS_HARD_LIMIT);\n\n while (round < maxRounds) {\n round++;\n\n // --- Evaluate ---\n onProgress?.({ type: 'evaluating', round });\n console.log(`[eval] Round ${round}: evaluating...`);\n\n const evalContext: EvaluationContext = {\n ...context,\n compiledCode: currentCode,\n sourceCode: currentSourceCode || context.sourceCode,\n };\n const evalResult = await runEvaluation(evalContext, config);\n evaluationResults.push(evalResult);\n\n console.log(\n `[eval] Round ${round}: score=${evalResult.finalScore}, passed=${evalResult.passed}, issues=${evalResult.issues.length}`\n );\n\n // If passed or last round, we're done\n if (evalResult.passed || round >= maxRounds) {\n break;\n }\n\n // --- Fix ---\n onProgress?.({ type: 'fixing', round });\n console.log(`[eval] Round ${round}: fixing...`);\n\n const fixPrompt = buildFixPrompt(evalResult, context.originalPrompt);\n\n // Get custom CLI path from environment (for Docker deployments)\n const cliPath = process.env.CLAUDE_WRAPPER_PATH;\n\n // Build environment — use BYOK-enriched env from generator if provided\n const env: Record<string, string> = {};\n if (generatorOptions?.env) {\n Object.assign(env, generatorOptions.env);\n } else {\n for (const [key, value] of Object.entries(process.env)) {\n if (value !== undefined) {\n env[key] = value;\n }\n }\n }\n\n let fixedCompiledCode: string | undefined;\n let fixedSourceCode: string | undefined;\n\n for await (const message of query({\n prompt: fixPrompt,\n options: {\n resume: generatorSessionId,\n maxTurns: 15,\n maxBudgetUsd: config.maxBudgetPerFix,\n env,\n permissionMode: 'bypassPermissions',\n allowDangerouslySkipPermissions: true,\n ...(cliPath && { pathToClaudeCodeExecutable: cliPath }),\n ...(generatorOptions?.cwd && { cwd: generatorOptions.cwd }),\n ...(generatorOptions?.mcpServers && { mcpServers: generatorOptions.mcpServers }),\n ...(generatorOptions?.allowedTools && { allowedTools: generatorOptions.allowedTools }),\n ...(generatorOptions?.model && { model: generatorOptions.model }),\n ...(generatorOptions?.stderr && { stderr: generatorOptions.stderr }),\n },\n })) {\n const msg = message as SdkMessage;\n\n // Capture fixed compiledCode\n const compiled = extractCompiledCodeFromMessage(msg);\n if (compiled) fixedCompiledCode = compiled;\n\n // Capture source code from Write tool\n const source = extractSourceCodeFromMessage(msg);\n if (source) fixedSourceCode = source;\n }\n\n // Update current code if fix produced new output\n if (fixedCompiledCode) {\n currentCode = fixedCompiledCode;\n console.log(`[eval] Round ${round}: fixed code captured (${currentCode.length} bytes)`);\n }\n if (fixedSourceCode) {\n currentSourceCode = fixedSourceCode;\n }\n }\n\n const lastResult = evaluationResults[evaluationResults.length - 1];\n const evaluationTimeMs = Date.now() - startTime;\n\n const qualityMetadata: QualityMetadata = {\n evaluationRounds: evaluationResults.length,\n finalScore: lastResult.finalScore,\n dimensions: lastResult.dimensions,\n passed: lastResult.passed,\n evaluatorModel: config.model ?? 'default',\n evaluationTimeMs,\n };\n\n return {\n finalCode: currentCode,\n finalSourceCode: currentSourceCode,\n qualityMetadata,\n evaluationResults,\n };\n}\n","// packages/ui-gen/src/evaluation/mcp-server.ts\n\nimport { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';\nimport { z } from 'zod';\nimport type { EvaluationIssue, EvaluationResult } from './types';\n\n/**\n * Input args for the evaluate_score computation.\n * Extracted so unit tests can call the real logic directly.\n */\nexport interface EvaluateScoreInput {\n completeness: number;\n visualPolish: number;\n interactivity: number;\n accessibility: number;\n codeQuality: number;\n issues: EvaluationIssue[];\n critique?: string;\n}\n\n/**\n * Core scoring logic — extracted from the tool handler so it can be\n * unit-tested directly without going through MCP protocol.\n */\nexport function computeEvaluationScore(\n args: EvaluateScoreInput,\n passThreshold: number\n): EvaluationResult {\n const scores = [\n args.completeness,\n args.visualPolish,\n args.interactivity,\n args.accessibility,\n args.codeQuality,\n ];\n const average = scores.reduce((a, b) => a + b, 0) / scores.length;\n const finalScore = Math.round(average * 10) / 10;\n const passed = finalScore >= passThreshold;\n\n return {\n passed,\n finalScore,\n dimensions: {\n completeness: args.completeness,\n visualPolish: args.visualPolish,\n interactivity: args.interactivity,\n accessibility: args.accessibility,\n codeQuality: args.codeQuality,\n },\n issues: args.issues,\n ...(args.critique && { critique: args.critique }),\n };\n}\n\n/**\n * Create the evaluation MCP server with the evaluate_score tool.\n *\n * The evaluator LLM provides qualitative scores per dimension.\n * This tool handles the arithmetic (average, pass/fail) so the LLM\n * doesn't need to do math.\n */\nexport function createEvaluationToolsServer(passThreshold = 70) {\n return createSdkMcpServer({\n name: 'eval-tools',\n version: '1.0.0',\n tools: [\n tool(\n 'evaluate_score',\n 'Compute evaluation score from dimension ratings. Call this after analyzing the component code against all 5 dimensions.',\n {\n completeness: z.number().min(0).max(100).describe('Score for feature completeness (0-100)'),\n visualPolish: z.number().min(0).max(100).describe('Score for visual polish and design (0-100)'),\n interactivity: z.number().min(0).max(100).describe('Score for interactivity and state management (0-100)'),\n accessibility: z.number().min(0).max(100).describe('Score for accessibility (ARIA, keyboard nav, contrast) (0-100)'),\n codeQuality: z.number().min(0).max(100).describe('Score for code quality and structure (0-100)'),\n issues: z.array(\n z.object({\n dimension: z.string().describe('Which dimension this issue affects'),\n description: z.string().describe('What the issue is'),\n severity: z.enum(['critical', 'major', 'minor']).describe('Issue severity'),\n fix: z.string().describe('How to fix this issue'),\n })\n ).describe('List of specific issues found'),\n critique: z.string().optional().describe('Optional overall critique summary'),\n },\n async (args) => {\n const result = computeEvaluationScore(args, passThreshold);\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(result, null, 2),\n },\n ],\n };\n }\n ),\n ],\n });\n}\n","// packages/ui-gen/src/evaluation/axis-checks/helpers.ts\n//\n// Shared contract inspection + source-scan helpers used by axis checks.\n// Ported from the retired mode-checks/ modules.\n\nimport type { ActionEntry, DataContract, JsonObject, JsonValue } from \"@ggui-ai/protocol\";\nimport {\n HOOK_NAME_RE,\n listContractGadgets,\n STDLIB_GADGETS_PACKAGE,\n} from \"@ggui-ai/protocol\";\nimport type { EvalIssue } from \"../types-public.js\";\n\n// =============================================================================\n// Contract shape helpers\n// =============================================================================\n\nexport interface PropShape {\n type?: string;\n required?: boolean;\n items?: { type?: string; properties?: Record<string, unknown> };\n schema?: {\n type?: string;\n items?: { type?: string; properties?: Record<string, unknown> };\n };\n}\n\nexport interface EntityCollection {\n name: string;\n idField: string;\n}\n\nexport interface SubmitAction {\n name: string;\n payloadKeys: string[];\n}\n\nconst ID_FIELD_CANDIDATES = [\"id\", \"uuid\", \"symbol\", \"key\", \"slug\", \"code\"];\n\nfunction getItemsProperties(p: PropShape): Record<string, unknown> | undefined {\n return p.items?.properties ?? p.schema?.items?.properties;\n}\n\nfunction inferIdField(itemProps: Record<string, unknown> | undefined): string {\n if (!itemProps) return \"id\";\n for (const cand of ID_FIELD_CANDIDATES) {\n if (cand in itemProps) return cand;\n }\n for (const [k, v] of Object.entries(itemProps)) {\n const vv = v as { type?: string; schema?: { type?: string } } | undefined;\n if (vv?.type === \"string\" || vv?.schema?.type === \"string\") return k;\n }\n return \"id\";\n}\n\nexport function getRequiredPropNames(contract?: DataContract): string[] {\n const propsField = contract?.propsSpec as\n | { properties?: Record<string, PropShape> }\n | undefined;\n const properties = propsField?.properties ?? {};\n return Object.entries(properties)\n .filter(([, p]) => p && typeof p === \"object\" && p.required === true)\n .map(([name]) => name);\n}\n\nexport function getActionNames(contract?: DataContract): string[] {\n return Object.keys(contract?.actionSpec ?? {});\n}\n\nexport function getStreamEventNames(contract?: DataContract): string[] {\n return Object.keys(contract?.streamSpec ?? {});\n}\n\n/**\n * Returns the local BINDING names the boilerplate emits for every\n * HOOK gadget the contract declares — `useGeolocation` → `geolocation`\n * (strip the `use` prefix, lowercase the first char). The wire\n * `clientCapabilities.gadgets` is package-keyed and carries only the\n * export NAME, not a separate binding name, so the binding is derived\n * here exactly as the boilerplate generator derives it.\n *\n * Component gadgets are excluded — they are rendered as JSX, not bound\n * to a `const`, so the `const <name> = …()` axis checks don't apply.\n *\n * The agentCapabilities.tools catalog has no parallel helper —\n * agent-side tools aren't component-side, so the axis checks don't\n * scan source for agent-tool bindings.\n */\nexport function getGadgetNames(contract?: DataContract): string[] {\n if (!contract) return [];\n return listContractGadgets(contract)\n .filter((use) => HOOK_NAME_RE.test(use.name))\n .map((use) =>\n use.name.length > 3\n ? use.name.charAt(3).toLowerCase() + use.name.slice(4)\n : use.name,\n );\n}\n\n/**\n * Like {@link getGadgetNames} but restricted to the first-party\n * `@ggui-ai/gadgets` stdlib package — the built-in browser capabilities\n * (`useGeolocation`, `useCamera`, …) that carry the `idle → prompting →\n * active` lifecycle and therefore need a `.start()` invocation.\n *\n * Registered third-party gadgets (e.g. `useBoardState` from\n * `@example/gadget-board`) are plain data hooks: the runtime resolves\n * them without a user gesture, so the `.start()` axis check must NOT\n * fire on them.\n */\nexport function getStdlibGadgetNames(contract?: DataContract): string[] {\n if (!contract) return [];\n return listContractGadgets(contract)\n .filter(\n (use) =>\n use.package === STDLIB_GADGETS_PACKAGE && HOOK_NAME_RE.test(use.name),\n )\n .map((use) =>\n use.name.length > 3\n ? use.name.charAt(3).toLowerCase() + use.name.slice(4)\n : use.name,\n );\n}\n\nexport function getEntityCollections(contract?: DataContract): EntityCollection[] {\n const propsField = contract?.propsSpec as\n | { properties?: Record<string, unknown> }\n | undefined;\n const properties = propsField?.properties ?? {};\n const entities: EntityCollection[] = [];\n for (const [name, p] of Object.entries(properties)) {\n if (!p || typeof p !== \"object\") continue;\n const pp = p as PropShape;\n const type = pp.type ?? pp.schema?.type;\n const items = pp.items ?? pp.schema?.items;\n if (type === \"array\" && items?.type === \"object\") {\n entities.push({ name, idField: inferIdField(getItemsProperties(pp)) });\n }\n }\n return entities;\n}\n\nfunction singularize(name: string): string {\n if (name.endsWith(\"ies\")) return name.slice(0, -3) + \"y\";\n if (name.endsWith(\"ses\")) return name.slice(0, -2);\n if (name.endsWith(\"s\") && !name.endsWith(\"ss\")) return name.slice(0, -1);\n return name;\n}\n\n/**\n * Entity collections that are actually mutated (referenced by a stream\n * event or by an action payload's entity-id key). Static reference lists\n * (e.g., kanban's `columns`) are excluded so they don't trigger\n * \"must be in useState\" false positives.\n */\nexport function getMutatedEntityCollections(\n contract: DataContract | undefined,\n allEntities: EntityCollection[],\n): EntityCollection[] {\n if (!contract) return allEntities;\n\n const actionSpec = contract.actionSpec ?? {};\n const streamSpec = contract.streamSpec ?? {};\n\n const hasStreams = Object.keys(streamSpec).length > 0;\n\n const referencedIdKeys = new Set<string>();\n for (const action of Object.values(actionSpec) as ActionEntry[]) {\n const ex = action.example;\n if (!ex || typeof ex !== \"object\" || Array.isArray(ex)) continue;\n for (const key of Object.keys(ex as JsonObject)) {\n if (key === \"id\" || key === \"key\" || key === \"index\") {\n referencedIdKeys.add(\"id\");\n referencedIdKeys.add(\"key\");\n referencedIdKeys.add(\"index\");\n } else if (/Id$/.test(key)) {\n referencedIdKeys.add(key.slice(0, -2).toLowerCase());\n }\n }\n }\n\n const mutated = allEntities.filter((e) =>\n referencedIdKeys.has(singularize(e.name).toLowerCase()),\n );\n\n if (mutated.length === 0 && hasStreams && allEntities.length > 0) {\n return [allEntities[0]];\n }\n return mutated.length > 0 ? mutated : allEntities;\n}\n\nfunction countScalarKeys(example: unknown): string[] {\n if (!example || typeof example !== \"object\" || Array.isArray(example)) return [];\n const keys: string[] = [];\n for (const [k, v] of Object.entries(example as Record<string, unknown>)) {\n const t = typeof v;\n if (t === \"string\" || t === \"number\" || t === \"boolean\") keys.push(k);\n }\n return keys;\n}\n\nexport function getSubmitActions(contract?: DataContract): SubmitAction[] {\n const actionSpec = contract?.actionSpec ?? {};\n const result: SubmitAction[] = [];\n for (const [name, action] of Object.entries(actionSpec) as Array<[string, ActionEntry]>) {\n const ex: JsonValue | undefined = action.example;\n const scalarKeys = countScalarKeys(ex);\n if (scalarKeys.length < 3) continue;\n const allKeys = ex && typeof ex === \"object\" && !Array.isArray(ex)\n ? Object.keys(ex as JsonObject)\n : scalarKeys;\n result.push({ name, payloadKeys: allKeys });\n }\n return result;\n}\n\nexport function getArrStrProps(contract?: DataContract): string[] {\n const propsField = contract?.propsSpec as\n | { properties?: Record<string, unknown> }\n | undefined;\n const properties = propsField?.properties ?? {};\n const names: string[] = [];\n for (const [name, p] of Object.entries(properties)) {\n if (!p || typeof p !== \"object\") continue;\n const pp = p as PropShape;\n const type = pp.type ?? pp.schema?.type;\n const items = pp.items ?? pp.schema?.items;\n if (type === \"array\" && items?.type === \"string\") names.push(name);\n }\n return names;\n}\n\nexport function getInitialValuePropNames(contract?: DataContract): string[] {\n const propsField = contract?.propsSpec as\n | { properties?: Record<string, unknown> }\n | undefined;\n const properties = propsField?.properties ?? {};\n const names: string[] = [];\n for (const [name, p] of Object.entries(properties)) {\n if (!p || typeof p !== \"object\") continue;\n const pp = p as PropShape;\n const type = pp.type ?? pp.schema?.type;\n if (type === \"object\" && /^initial/i.test(name)) names.push(name);\n }\n return names;\n}\n\n// =============================================================================\n// Source scanning helpers\n// =============================================================================\n\n/**\n * Collect all key names that appear as state slots — either keys inside a\n * `useState({ ... })` object literal, or standalone state variables.\n */\nexport function collectStateKeys(src: string): Set<string> {\n const keys = new Set<string>();\n const varRe = /const\\s*\\[\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\]\\s*=\\s*useState/g;\n for (const m of src.matchAll(varRe)) keys.add(m[1]);\n const objRe = /useState(?:<[^>]*>)?\\s*\\(\\s*\\{([\\s\\S]*?)\\}\\s*\\)/g;\n for (const m of src.matchAll(objRe)) {\n const keyRe = /(?:^|,)\\s*(\\w+)\\s*:/g;\n for (const km of m[1].matchAll(keyRe)) keys.add(km[1]);\n }\n const defaultObjRe = /useState(?:<[^>]*>)?\\s*\\([^)]*\\|\\|\\s*\\{([^}]*)\\}/g;\n for (const m of src.matchAll(defaultObjRe)) {\n const keyRe = /(?:^|,)\\s*(\\w+)\\s*:/g;\n for (const km of m[1].matchAll(keyRe)) keys.add(km[1]);\n }\n return keys;\n}\n\nexport function isMultiStepPrompt(prompt: string): boolean {\n if (!prompt) return false;\n const p = prompt.toLowerCase();\n return (\n /\\bstep\\s*[1-9]\\b/.test(p) ||\n /\\b[1-9][- ]step\\b/.test(p) ||\n /\\bmulti[- ]step\\b/.test(p) ||\n /\\bwizard\\b/.test(p) ||\n /\\bsteps?:\\s*\\n?/.test(p)\n );\n}\n\n// =============================================================================\n// Issue factory\n// =============================================================================\n\nexport function mkIssue(\n subcategory: string,\n description: string,\n fix: string,\n result: \"fail\" | \"warn\" = \"fail\",\n): EvalIssue {\n // mode-category issues are structural (missing hook wiring, bad merge-by-id,\n // hardcoded entity literals) — always P0. See ALIGNMENT.md R1.\n return { tier: 0, result, category: \"mode\", priority: \"P0\", subcategory, description, fix };\n}\n\nexport function cap(s: string): string {\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n","// packages/ui-gen/src/evaluation/axis-checks/checks/universal.ts\n//\n// Checks that run regardless of axis value — they apply to any generated\n// component. Dispatched via a \"universal\" gate that matches every render\n// value.\n\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport {\n getRequiredPropNames,\n mkIssue,\n} from \"../helpers.js\";\n\nconst ALL_RENDER_VALUES = [\n \"static\", \"list\", \"grid\", \"spatial\", \"timeline\", \"chart\", \"master-detail\",\n] as const;\n\nfunction runPropCoverage(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const requiredProps = getRequiredPropNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of requiredProps) {\n const dotAccess = new RegExp(`\\\\bprops\\\\.${name}\\\\b`);\n const bracketAccess = new RegExp(`\\\\bprops\\\\[['\"\\`]${name}['\"\\`]\\\\]`);\n const destructured = new RegExp(\n `props[^;]{0,200}\\\\{[^}]*\\\\b${name}\\\\b[^}]*\\\\}|\\\\{[^}]*\\\\b${name}\\\\b[^}]*\\\\}[^;]{0,10}=\\\\s*props`,\n );\n if (dotAccess.test(src) || bracketAccess.test(src) || destructured.test(src))\n continue;\n issues.push(\n mkIssue(\n \"universal.prop_coverage\",\n `Required prop \"${name}\" is not referenced anywhere in the component.`,\n `Render props.${name} — the data contract marks it required.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runNoPropMirror(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const issues: EvalIssue[] = [];\n const re =\n /const\\s*\\[\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\]\\s*=\\s*useState(?:<[^>]*>)?\\s*\\(\\s*props\\??\\.(\\w+)/g;\n for (const m of src.matchAll(re)) {\n const [full, stateVar, setter, propName] = m;\n const idx = m.index ?? 0;\n const after = src.slice(idx + full.length);\n if (new RegExp(`\\\\b${setter}\\\\s*\\\\(`).test(after)) continue;\n issues.push(\n mkIssue(\n \"universal.no_prop_mirror\",\n `useState(props.${propName}) for \"${stateVar}\" has no \"${setter}\" call — this mirrors a prop without mutation.`,\n `Read props.${propName} directly in the render; remove the useState for ${stateVar}.`,\n \"warn\",\n ),\n );\n }\n return issues;\n}\n\nfunction runNoPhantomUseState(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const issues: EvalIssue[] = [];\n const re = /const\\s*\\[\\s*(\\w+)\\s*,\\s*(\\w+)\\s*\\]\\s*=\\s*useState/g;\n for (const m of src.matchAll(re)) {\n const [full, stateVar, setter] = m;\n const idx = m.index ?? 0;\n const after = src.slice(idx + full.length);\n const stateUsed = new RegExp(`\\\\b${stateVar}\\\\b`).test(after);\n const setterUsed = new RegExp(`\\\\b${setter}\\\\b`).test(after);\n if (stateUsed || setterUsed) continue;\n issues.push(\n mkIssue(\n \"universal.no_phantom_useState\",\n `useState for \"${stateVar}\" is declared but neither \"${stateVar}\" nor \"${setter}\" is referenced.`,\n `Remove the useState for ${stateVar} — it is dead state.`,\n \"warn\",\n ),\n );\n }\n return issues;\n}\n\nexport const UNIVERSAL_CHECKS: readonly AxisCheck[] = [\n {\n id: \"universal.prop_coverage\",\n axis: \"render\",\n values: ALL_RENDER_VALUES,\n run: runPropCoverage,\n },\n {\n id: \"universal.no_prop_mirror\",\n axis: \"render\",\n values: ALL_RENDER_VALUES,\n run: runNoPropMirror,\n },\n {\n id: \"universal.no_phantom_useState\",\n axis: \"render\",\n values: ALL_RENDER_VALUES,\n run: runNoPhantomUseState,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/checks/state-merge.ts\n//\n// Checks gated on state=merge: the component owns a live entity list\n// reconciled from stream/action updates. Ported from\n// mode-checks/collection.ts (§5a state-seeded, no-hardcoded-entities,\n// derived-view-memoized).\n\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport {\n cap,\n getEntityCollections,\n getMutatedEntityCollections,\n mkIssue,\n} from \"../helpers.js\";\n\nfunction runStateSeededFromProps(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const all = getEntityCollections(input.contract);\n const entities = getMutatedEntityCollections(input.contract, all);\n const issues: EvalIssue[] = [];\n for (const e of entities) {\n const re = new RegExp(\n `useState(?:<[^>]*>)?\\\\s*\\\\([\\\\s\\\\S]{0,400}?props\\\\.${e.name}\\\\b`,\n );\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"state.merge.seeded_from_props\",\n `Entity collection \"${e.name}\" is not seeded from props — no useState initializer reads props.${e.name}.`,\n `Add \\`const [${e.name}, set${cap(e.name)}] = useState(props.${e.name});\\` so stream/action updates can merge into live state.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runNoHardcodedEntities(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const all = getEntityCollections(input.contract);\n const entities = getMutatedEntityCollections(input.contract, all);\n if (entities.length === 0) return [];\n const uncommented = src\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/\\/\\/[^\\n]*/g, \"\");\n const issues: EvalIssue[] = [];\n const idFields = [...new Set(entities.map((e) => e.idField))];\n for (const idField of idFields) {\n const re = new RegExp(\n `\\\\[\\\\s*\\\\{[^}]*\\\\b${idField}\\\\s*:[^}]*\\\\}\\\\s*,\\\\s*\\\\{[^}]*\\\\b${idField}\\\\s*:`,\n \"g\",\n );\n if (!re.test(uncommented)) continue;\n issues.push(\n mkIssue(\n \"state.merge.no_hardcoded_entities\",\n `Hardcoded entity array literal (multiple objects with \"${idField}\") in the component — entity data should come from state/props.`,\n `Remove the literal array. Seed state from props.{entityProp} and merge updates via stream.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runDerivedViewMemoized(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const all = getEntityCollections(input.contract);\n const entities = getMutatedEntityCollections(input.contract, all);\n if (entities.length === 0) return [];\n const returnIdx = src.indexOf(\"return (\");\n if (returnIdx < 0) return [];\n const renderBody = src.slice(returnIdx);\n const issues: EvalIssue[] = [];\n for (const e of entities) {\n const re = new RegExp(`\\\\b${e.name}\\\\s*\\\\.(filter|reduce|sort)\\\\s*\\\\(`);\n if (re.test(renderBody)) {\n issues.push(\n mkIssue(\n \"state.merge.derived_view_memoized\",\n `Derived view (${e.name}.filter/reduce/sort) computed inside the render body — should be wrapped in useMemo.`,\n `Extract to \\`const ${e.name}Filtered = useMemo(() => ${e.name}.filter(...), [${e.name}, ...]);\\` before the return.`,\n \"warn\",\n ),\n );\n }\n }\n return issues;\n}\n\n/**\n * `.map()` keyed by index → reorders and merges break React reconciliation.\n * Gated on any render that iterates (list/grid/timeline/master-detail) OR\n * state=merge (mutating list).\n */\nfunction runMapKeyIsId(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const INDEX_NAMES = new Set([\"index\", \"idx\", \"i\", \"j\", \"k\", \"n\", \"ix\"]);\n const re = /key\\s*=\\s*\\{\\s*(\\w+)\\s*\\}/g;\n const issues: EvalIssue[] = [];\n for (const m of src.matchAll(re)) {\n const key = m[1];\n if (!INDEX_NAMES.has(key)) continue;\n issues.push(\n mkIssue(\n \"render.map_key_is_id\",\n `Array key uses index variable \"${key}\" — reorders and stream merges will break React reconciliation.`,\n `Replace key={${key}} with key={item.id} (or item.symbol / whatever the entity id field is).`,\n ),\n );\n }\n return issues;\n}\n\nexport const STATE_MERGE_CHECKS: readonly AxisCheck[] = [\n {\n id: \"state.merge.seeded_from_props\",\n axis: \"state\",\n values: [\"merge\"],\n run: runStateSeededFromProps,\n },\n {\n id: \"state.merge.no_hardcoded_entities\",\n axis: \"state\",\n values: [\"merge\"],\n run: runNoHardcodedEntities,\n },\n {\n id: \"state.merge.derived_view_memoized\",\n axis: \"state\",\n values: [\"merge\"],\n run: runDerivedViewMemoized,\n },\n // Map-key check: gated on any iterating render. state=merge always\n // implies iteration, so the render gate already covers it.\n {\n id: \"render.map_key_is_id\",\n axis: \"render\",\n values: [\"list\", \"grid\", \"timeline\", \"master-detail\"],\n run: runMapKeyIsId,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/checks/realtime.ts\n//\n// Checks gated on realtime != none. Ported from mode-checks/collection.ts\n// (stream-handler-per-event, stream-merges-by-id).\n\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport {\n getEntityCollections,\n getMutatedEntityCollections,\n getStreamEventNames,\n mkIssue,\n} from \"../helpers.js\";\n\nconst REALTIME_ACTIVE = [\"merge\", \"append\", \"status\", \"presence\", \"mixed\"] as const;\n\nfunction runStreamHandlerPerEvent(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const eventNames = getStreamEventNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of eventNames) {\n const re = new RegExp(`useStream(?:<[^>]*>)?\\\\s*\\\\(\\\\s*['\"\\`]${name}['\"\\`]`);\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"realtime.stream_handler_per_event\",\n `Stream event \"${name}\" declared in the contract has no useStream('${name}') call.`,\n `Add \\`const ${name} = useStream<...>('${name}');\\` and handle ${name}.latest in a useEffect.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runStreamMergesById(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const eventNames = getStreamEventNames(input.contract);\n const all = getEntityCollections(input.contract);\n const entities = getMutatedEntityCollections(input.contract, all);\n if (eventNames.length === 0 || entities.length === 0) return [];\n const issues: EvalIssue[] = [];\n const idFields = new Set(entities.map((e) => e.idField));\n for (const idField of idFields) {\n const re = new RegExp(`\\\\.${idField}\\\\b`);\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"realtime.merge.stream_merges_by_id\",\n `Entity id field \"${idField}\" is never referenced in the source — stream merge likely does not key by id.`,\n `In the stream handler, merge by id: setItems(prev => prev.map(x => x.${idField} === update.${idField} ? {...x, ...update} : x)).`,\n \"warn\",\n ),\n );\n }\n return issues;\n}\n\nexport const REALTIME_CHECKS: readonly AxisCheck[] = [\n {\n id: \"realtime.stream_handler_per_event\",\n axis: \"realtime\",\n values: REALTIME_ACTIVE,\n run: runStreamHandlerPerEvent,\n },\n {\n id: \"realtime.merge.stream_merges_by_id\",\n axis: \"realtime\",\n values: [\"merge\", \"mixed\"],\n run: runStreamMergesById,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/checks/writes.ts\n//\n// Checks gated on writes != none. Ported from display.ts (action-hook,\n// action-handler) + form.ts (submit-hook, submit-handler, submit-disabled)\n// + collection.ts (per-item action variants).\n\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport {\n getActionNames,\n getSubmitActions,\n mkIssue,\n} from \"../helpers.js\";\n\nconst ACTIVE_WRITES = [\n \"commit\", \"multi-commit\", \"per-item\", \"submit\", \"compose\",\n] as const;\n\nfunction runActionHookWired(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const actionNames = getActionNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of actionNames) {\n const re = new RegExp(`useAction(?:<[^>]*>)?\\\\s*\\\\(\\\\s*['\"\\`]${name}['\"\\`]`);\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"writes.action_hook_wired\",\n `Contract action \"${name}\" has no useAction('${name}') call.`,\n `Add \\`const ${name} = useAction<...>('${name}');\\` and wire it to the relevant control.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runActionHandlerAttached(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const actionNames = getActionNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of actionNames) {\n const declRe = new RegExp(\n `const\\\\s+(\\\\w+)\\\\s*=\\\\s*useAction(?:<[^>]*>)?\\\\s*\\\\(\\\\s*['\"\\`]${name}['\"\\`]`,\n );\n const m = src.match(declRe);\n if (!m) continue;\n const constName = m[1];\n const rest = src.replace(m[0], \"\");\n if (new RegExp(`\\\\b${constName}\\\\s*\\\\(`).test(rest)) continue;\n issues.push(\n mkIssue(\n \"writes.action_handler_attached\",\n `useAction result \"${constName}\" (for action \"${name}\") is declared but never invoked.`,\n `Call ${constName}({...}) from an interactive element (e.g., <Button onClick={() => ${constName}(payload)}>).`,\n ),\n );\n }\n return issues;\n}\n\nfunction runSubmitDisabledPath(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const submits = getSubmitActions(input.contract);\n if (submits.length === 0) return [];\n if (/disabled\\s*=\\s*\\{/.test(src)) return [];\n return [\n mkIssue(\n \"writes.submit.disabled_path\",\n `Form has no \\`disabled={...}\\` expression anywhere — submit is likely unconditional.`,\n `Gate submit on validation: e.g. \\`<Button disabled={!isValid} onClick={handleSubmit}>\\`.`,\n \"warn\",\n ),\n ];\n}\n\nexport const WRITES_CHECKS: readonly AxisCheck[] = [\n {\n id: \"writes.action_hook_wired\",\n axis: \"writes\",\n values: ACTIVE_WRITES,\n run: runActionHookWired,\n },\n {\n id: \"writes.action_handler_attached\",\n axis: \"writes\",\n values: ACTIVE_WRITES,\n run: runActionHandlerAttached,\n },\n {\n id: \"writes.submit.disabled_path\",\n axis: \"writes\",\n values: [\"submit\"],\n run: runSubmitDisabledPath,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/checks/state-payload.ts\n//\n// Checks gated on state=payload or writes=submit. Ported from\n// mode-checks/form.ts (submit-hook, submit-handler, state-covers-payload,\n// initial-values-seeded, option-lists-consumed, no-orphan-payload-key).\n\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport {\n collectStateKeys,\n getArrStrProps,\n getInitialValuePropNames,\n getSubmitActions,\n mkIssue,\n} from \"../helpers.js\";\n\nfunction runSubmitHookPresent(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const submits = getSubmitActions(input.contract);\n const issues: EvalIssue[] = [];\n for (const s of submits) {\n const re = new RegExp(`useAction(?:<[^>]*>)?\\\\s*\\\\(\\\\s*['\"\\`]${s.name}['\"\\`]`);\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"writes.submit.hook_present\",\n `Submit action \"${s.name}\" has no useAction('${s.name}') call.`,\n `Add \\`const ${s.name} = useAction<...>('${s.name}');\\` and invoke it from the submit button.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runSubmitHandlerAttached(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const submits = getSubmitActions(input.contract);\n const issues: EvalIssue[] = [];\n for (const s of submits) {\n const declRe = new RegExp(\n `const\\\\s+(\\\\w+)\\\\s*=\\\\s*useAction(?:<[^>]*>)?\\\\s*\\\\(\\\\s*['\"\\`]${s.name}['\"\\`]`,\n );\n const m = src.match(declRe);\n if (!m) continue;\n const constName = m[1];\n const rest = src.replace(m[0], \"\");\n if (new RegExp(`\\\\b${constName}\\\\s*\\\\(`).test(rest)) continue;\n issues.push(\n mkIssue(\n \"writes.submit.handler_attached\",\n `useAction result \"${constName}\" (for submit \"${s.name}\") is declared but never invoked.`,\n `Call ${constName}(payload) from the submit button's onClick handler, after validation.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runStateCoversPayload(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const submits = getSubmitActions(input.contract);\n if (submits.length === 0) return [];\n const stateKeys = collectStateKeys(src);\n const issues: EvalIssue[] = [];\n for (const s of submits) {\n const missing = s.payloadKeys.filter((k) => !stateKeys.has(k));\n if (missing.length === 0) continue;\n issues.push(\n mkIssue(\n \"state.payload.covers_submit\",\n `Submit action \"${s.name}\" expects payload keys [${s.payloadKeys.join(\", \")}] but state does not cover: ${missing.join(\", \")}.`,\n `Add a state slot for each missing key so the final payload can be assembled.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runInitialValuesSeeded(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const initialProps = getInitialValuePropNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of initialProps) {\n const re = new RegExp(\n `useState(?:<[^>]*>)?\\\\s*\\\\([\\\\s\\\\S]{0,400}?props\\\\.${name}\\\\b`,\n );\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"state.payload.initial_values_seeded\",\n `Prop \"${name}\" (pre-filled initial values) is never read in a useState initializer.`,\n `Seed form state from props.${name} so edit mode pre-fills.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runOptionListsConsumed(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const arrStrNames = getArrStrProps(input.contract);\n const hasAnyMap = /\\.map\\s*\\(/.test(src);\n const issues: EvalIssue[] = [];\n for (const name of arrStrNames) {\n const referenced = new RegExp(`\\\\bprops\\\\.${name}\\\\b`).test(src);\n if (referenced && hasAnyMap) continue;\n const reason = !referenced\n ? `Option list prop \"${name}\" (arr<str>) is never referenced — users cannot see the options.`\n : `Option list prop \"${name}\" (arr<str>) is referenced but the component has no .map() — options are not rendered as choices.`;\n issues.push(\n mkIssue(\n \"state.payload.option_lists_consumed\",\n reason,\n `Render options with \\`props.${name}.map(option => <RadioOption value={option} ... />)\\`.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runNoOrphanPayloadKey(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const submits = getSubmitActions(input.contract);\n if (submits.length === 0) return [];\n const body = src\n .replace(/interface\\s+Action\\w+[\\s\\S]*?\\n}/g, \"\")\n .replace(/type\\s+Action\\w+[\\s\\S]*?\\n;/g, \"\");\n const issues: EvalIssue[] = [];\n for (const s of submits) {\n const orphans: string[] = [];\n for (const key of s.payloadKeys) {\n const re = new RegExp(`\\\\b${key}\\\\b`);\n if (!re.test(body)) orphans.push(key);\n }\n if (orphans.length === 0) continue;\n issues.push(\n mkIssue(\n \"state.payload.no_orphan_key\",\n `Submit payload keys [${orphans.join(\", \")}] never appear in the component body — missing from the submitted payload.`,\n `Add UI and state for these keys, or remove them from the ActionEntry if not needed.`,\n \"warn\",\n ),\n );\n }\n return issues;\n}\n\nexport const STATE_PAYLOAD_CHECKS: readonly AxisCheck[] = [\n {\n id: \"writes.submit.hook_present\",\n axis: \"writes\",\n values: [\"submit\"],\n run: runSubmitHookPresent,\n },\n {\n id: \"writes.submit.handler_attached\",\n axis: \"writes\",\n values: [\"submit\"],\n run: runSubmitHandlerAttached,\n },\n {\n id: \"state.payload.covers_submit\",\n axis: \"state\",\n values: [\"payload\"],\n run: runStateCoversPayload,\n },\n {\n id: \"state.payload.initial_values_seeded\",\n axis: \"state\",\n values: [\"payload\", \"draft\"],\n run: runInitialValuesSeeded,\n },\n {\n id: \"state.payload.option_lists_consumed\",\n axis: \"state\",\n values: [\"payload\"],\n run: runOptionListsConsumed,\n },\n {\n id: \"state.payload.no_orphan_key\",\n axis: \"state\",\n values: [\"payload\"],\n run: runNoOrphanPayloadKey,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/checks/tooling.ts\n//\n// Checks gated on the tooling axis. Two surfaces:\n//\n// - `tooling.clientCapability.hook_called` — verifies every declared\n// `clientCapabilities.gadgets[name]` has a matching\n// `const <name> = …()` binding in source.\n// - `tooling.clientCapability.start_called` — verifies a bound\n// gadget hook also has a `.start(...)` invocation; without it\n// the capability stays in `idle` and never fires.\n// - `realtime.stream_source.no_direct_call` — the LLM must NOT\n// directly invoke a tool named on `streamSpec[*].source.tool`;\n// subscribe via `useStream(...)` instead.\n// - `universal.no_retired_identifiers` — fires on every contract.\n// The LLM's training data predates the current wire shape and\n// reaches for retired identifiers (component-side tool hooks,\n// dispatch.kind, intendedTool, broadcast field, retired catalog\n// names, retired package imports, retired wire-input fields).\n// The grep gate emits one issue per detected identifier so the\n// LLM rewrites toward the current shape before evaluation\n// completes.\n\nimport type { DataContract, StreamChannelEntry } from \"@ggui-ai/protocol\";\nimport type { EvalIssue } from \"../../types-public.js\";\nimport type { AxisCheck, AxisCheckInput } from \"../types.js\";\nimport { getGadgetNames, getStdlibGadgetNames, mkIssue } from \"../helpers.js\";\n\nconst CLIENT_PRESENT = [\"client\", \"both\"] as const;\nconst ALL_TOOLING_VALUES = [\"none\", \"wired\", \"client\", \"both\"] as const;\nconst REALTIME_ACTIVE = [\n \"merge\",\n \"append\",\n \"status\",\n \"presence\",\n \"mixed\",\n] as const;\n\n// ── clientCapabilities ──────────────────────────────────────────────\n\nfunction runGadgetHookCalled(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const names = getGadgetNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of names) {\n // The boilerplate emits `const <name> = <hook>();` — match the const\n // binding to detect omission. We don't pin the hook identifier here\n // because the contract carries it via `entry.hook` and the LLM may\n // legitimately alias on import.\n const re = new RegExp(`const\\\\s+${name}\\\\s*=`);\n if (re.test(src)) continue;\n issues.push(\n mkIssue(\n \"tooling.clientCapability.hook_called\",\n `Contract clientCapability \"${name}\" has no \\`const ${name} = …()\\` hook call.`,\n `Import the declared hook (default package: @ggui-ai/gadgets) and bind its return value to \\`const ${name}\\` at the top of the component; surface \\`.value\\` / \\`.status\\` in JSX.`,\n ),\n );\n }\n return issues;\n}\n\nfunction runClientCapabilityStartCalled(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n // Only the first-party `@ggui-ai/gadgets` browser capabilities have\n // the `idle → prompting → active` lifecycle that `.start()` drives.\n // Registered third-party gadget hooks (e.g. `useBoardState`) are\n // plain data hooks the runtime resolves on its own — exclude them.\n const names = getStdlibGadgetNames(input.contract);\n const issues: EvalIssue[] = [];\n for (const name of names) {\n // Skip when the binding doesn't exist — the `hook_called` check\n // covers that case; we don't double-issue.\n const bindingRe = new RegExp(`const\\\\s+${name}\\\\s*=`);\n if (!bindingRe.test(src)) continue;\n\n // The capability lifecycle requires `.start()` invocation to\n // transition from `idle` → `prompting`. Without it the hook's\n // `.value` / `.status` stay frozen at the initial state and the\n // UI feature never fires. Match `<name>.start(`, allowing chained\n // member access or method aliasing.\n const startRe = new RegExp(`\\\\b${name}\\\\s*\\\\.\\\\s*start\\\\s*\\\\(`);\n if (startRe.test(src)) continue;\n issues.push(\n mkIssue(\n \"tooling.clientCapability.start_called\",\n `clientCapability \"${name}\" is bound but \\`${name}.start(…)\\` is never invoked — the capability stays in 'idle' and the feature won't fire.`,\n `Wire \\`${name}.start({...})\\` to a UI control (Button onClick, effect, etc.). Read \\`.status\\` to gate the UI between 'idle' / 'prompting' / 'active' / 'completed' / 'denied' / 'error'.`,\n ),\n );\n }\n return issues;\n}\n\n// ── streamSpec sources ──────────────────────────────────────────────\n\nfunction collectStreamSourceTools(\n contract: DataContract | undefined,\n): Map<string, string> {\n // Map<channelName, sourceToolName> for every channel that declares\n // a source. Excludes channels without `source` (agent-written).\n const result = new Map<string, string>();\n const streamSpec = contract?.streamSpec;\n if (!streamSpec || typeof streamSpec !== \"object\") return result;\n for (const [channelName, entryRaw] of Object.entries(streamSpec)) {\n const entry = entryRaw as StreamChannelEntry | undefined;\n if (!entry || typeof entry !== \"object\") continue;\n const tool = entry.source?.tool;\n if (typeof tool !== \"string\" || tool.length === 0) continue;\n result.set(channelName, tool);\n }\n return result;\n}\n\nfunction runStreamSourceNoDirectCall(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const map = collectStreamSourceTools(input.contract);\n if (map.size === 0) return [];\n\n const issues: EvalIssue[] = [];\n for (const [channelName, toolName] of map) {\n // Detect a direct call to the source tool. Matches identifier\n // followed by `(` — covers `foo()`, `foo(args)`, `foo.bar()`\n // (the dotted form indirectly catches `someObject.foo()` which\n // the contract doesn't expect to see, since the source tool is\n // an agent-side MCP tool, not a local function).\n const callRe = new RegExp(`\\\\b${toolName}\\\\s*\\\\(`);\n if (!callRe.test(src)) continue;\n\n // Don't false-fire when `toolName` happens to be the channel name\n // bound to useStream (e.g., `const messages = useStream(...)` then\n // `messages(...)` would be weird but we're matching the TOOL name,\n // not the binding). If toolName === channelName then the\n // `<channel>(` call would be the useStream binding being called\n // as a function — which is itself wrong, so still emit.\n issues.push(\n mkIssue(\n \"realtime.stream_source.no_direct_call\",\n `Source code calls \\`${toolName}(...)\\` directly but the contract declares it as the source tool for streamSpec.${channelName}. Source tools are agent-side / runtime-polled; the component MUST NOT invoke them.`,\n `Subscribe to the channel via \\`const ${channelName} = useStream('${channelName}');\\` and read \\`${channelName}.latest\\` / \\`${channelName}.all\\` — the runtime polls or subscribes to '${toolName}' on the component's behalf.`,\n ),\n );\n }\n return issues;\n}\n\n// ── Anti-pattern grep — retired identifiers a model may emit from\n// stale training data ──\n\ninterface RetiredIdentifier {\n /** Regex matching the retired surface in source. */\n readonly pattern: RegExp;\n /** Stable subcategory used for the EvalIssue. */\n readonly id: string;\n /** Human-readable description for the issue message. */\n readonly label: string;\n /** Replacement guidance for the fix message. */\n readonly replacement: string;\n}\n\nconst RETIRED_IDENTIFIERS: readonly RetiredIdentifier[] = [\n {\n pattern: /\\buseWiredTool\\b/,\n id: \"useWiredTool\",\n label: \"`useWiredTool(...)` hook\",\n replacement:\n \"Use `useAction(name)` for user gestures the agent should react to. `agentCapabilities.tools` entries are agent-side catalog declarations — the component never calls them directly.\",\n },\n {\n pattern: /\\buseAgentTool\\b/,\n id: \"useAgentTool\",\n label: \"`useAgentTool(...)` hook\",\n replacement:\n \"Agent-side tools are NEVER imported as component hooks. The contract declares them under `agentCapabilities.tools` for cross-ref (actionSpec.nextStep / streamSpec.source.tool); the component reacts via `useAction` / `useStream`.\",\n },\n {\n pattern: /\\bcallWiredTool\\b/,\n id: \"callWiredTool\",\n label: \"`callWiredTool(...)` call\",\n replacement:\n \"Component-side direct invocation of agent-side tools is retired. Fire a UI gesture via `useAction(name)`; the agent reacts on its next turn (`nextStep` hint optional).\",\n },\n {\n pattern: /\\buseClientTool\\b/,\n id: \"useClientTool\",\n label: \"`useClientTool(name, handler)` hook\",\n replacement:\n \"Use a gadget hook from `@ggui-ai/gadgets` (e.g., `useGeolocation`, `useClipboardWrite`) and thread the result into a contextSpec slot or actionSpec payload.\",\n },\n {\n pattern: /\\bdispatch\\s*:\\s*\\{\\s*kind\\s*:/,\n id: \"dispatch.kind\",\n label: \"`dispatch: { kind: '...' }` discriminated union\",\n replacement:\n \"ActionEntry.dispatch is retired. Use the flat `nextStep?: '<tool>'` field on the action entry instead.\",\n },\n {\n pattern: /\\bintendedTool\\b/,\n id: \"intendedTool\",\n label: \"`intendedTool` field\",\n replacement:\n \"Use the flat `nextStep` field — the hint surface is one optional advisory string, not a nested discriminator.\",\n },\n {\n pattern: /\\bmode\\s*:\\s*['\"`]host-routed['\"`]/,\n id: \"mode.host-routed\",\n label: \"`mode: 'host-routed'`\",\n replacement:\n \"The `mode` field on action entries is retired. All actions are agent-routed; use `nextStep` for the optional tool hint.\",\n },\n {\n pattern: /\\bbroadcast\\s*:\\s*\\{/,\n id: \"broadcast\",\n label: \"`broadcast: { … }` contract field\",\n replacement:\n \"Move the channel source declaration to `streamSpec[channel].source = { tool, args? }`.\",\n },\n {\n // Match `agentTools` only as a contract-shaped object key or\n // property access — not as a local variable name in unrelated\n // code. `\\bagentTools\\s*[:.]` catches `{ agentTools: {...} }` /\n // `contract.agentTools` while ignoring `const agentTools = ...`.\n pattern: /\\bagentTools\\s*[:.]/,\n id: \"contract.agentTools\",\n label: \"`agentTools` top-level contract field\",\n replacement:\n \"The top-level `agentTools` field is retired. Declare agent-side tools under `agentCapabilities.tools` (catalog nested under a capabilities parent for symmetry with `clientCapabilities`).\",\n },\n {\n pattern: /\\bclientCapabilities\\s*\\.\\s*capabilities\\b/,\n id: \"clientCapabilities.capabilities\",\n label: \"`clientCapabilities.capabilities` inner key\",\n replacement:\n \"The inner `capabilities` key is retired. Use `clientCapabilities.gadgets` — entries are library-hook declarations, not RPC capabilities.\",\n },\n {\n pattern: /['\"`]@ggui-ai\\/client-tools['\"`]/,\n id: \"package.@ggui-ai/client-tools\",\n label: \"`@ggui-ai/client-tools` package import\",\n replacement:\n \"The package was renamed to `@ggui-ai/gadgets`. Update the import string.\",\n },\n {\n pattern: /\\bPushStory\\b/,\n id: \"PushStory\",\n label: \"`PushStory` type / `pushStorySchema` schema\",\n replacement:\n \"`PushStory` was retired when the handshake input was flattened. The current wire is `ggui_handshake({intent, blueprintDraft: {contract, variance?, generator?}})` + `ggui_render({handshakeId, props, override?: {contract?, variance?}})` (omit `override` to accept the proposal as-is).\",\n },\n {\n pattern: /\\bpushStorySchema\\b/,\n id: \"pushStorySchema\",\n label: \"`pushStorySchema` zod schema\",\n replacement:\n \"`pushStorySchema` was retired alongside `PushStory`. Current schemas: `handshakeInputSchema` + `renderInputSchema` (with the optional `override` re-aim) in `@ggui-ai/protocol`.\",\n },\n {\n pattern: /\\bstory\\s*\\.\\s*adapters\\b/,\n id: \"story.adapters\",\n label: \"`story.adapters` field access\",\n replacement:\n \"The story.adapters gate was retired alongside `PushStory`. Per-app permission gates flow through `clientCapabilities.gadgets[*].permission` (Permissions-Policy derivation).\",\n },\n {\n pattern: /\\bdeclaredAdapters\\b/,\n id: \"declaredAdapters\",\n label: \"`declaredAdapters` field / runtime gate\",\n replacement:\n \"App-level `declaredAdapters` was retired. Per-app permission gates derive from `clientCapabilities.gadgets[*].permission` instead.\",\n },\n {\n pattern: /\\bassertAdaptersDeclared\\b/,\n id: \"assertAdaptersDeclared\",\n label: \"`assertAdaptersDeclared(...)` runtime call\",\n replacement:\n \"The runtime adapter-gate function is retired. Permissions-Policy is derived per-contract at render commit time and threaded through the bootstrap projection.\",\n },\n {\n pattern: /\\bHandshakeStoredStory\\b/,\n id: \"HandshakeStoredStory\",\n label: \"`HandshakeStoredStory` storage type\",\n replacement:\n \"The OSS handler's stored type is now `HandshakeStoredInput` with the MVB-5 `{intent, blueprintDraft, forceCreate?}` shape.\",\n },\n {\n pattern: /\\brecord\\s*\\.\\s*story\\b/,\n id: \"record.story\",\n label: \"`record.story.*` access on handshake storage\",\n replacement:\n \"Handshake storage was flattened. Read `record.input.*` (intent / blueprintDraft) — the nested `story` wrapper is gone. MVB-5 also adds `record.suggestion` + `record.effectiveContract`.\",\n },\n];\n\nfunction runNoRetiredIdentifiers(input: AxisCheckInput): EvalIssue[] {\n // Source-only scan; compiled code irrelevant for identifier detection.\n // Run even without compiled code so we surface early in the loop.\n const src = input.sourceCode;\n const issues: EvalIssue[] = [];\n for (const rule of RETIRED_IDENTIFIERS) {\n if (!rule.pattern.test(src)) continue;\n issues.push(\n mkIssue(\n `universal.no_retired_identifiers.${rule.id}`,\n `Source contains ${rule.label} — retired from the contract surface.`,\n rule.replacement,\n ),\n );\n }\n return issues;\n}\n\nexport const TOOLING_CHECKS: readonly AxisCheck[] = [\n {\n id: \"tooling.clientCapability.hook_called\",\n axis: \"tooling\",\n values: CLIENT_PRESENT,\n run: runGadgetHookCalled,\n },\n {\n id: \"tooling.clientCapability.start_called\",\n axis: \"tooling\",\n values: CLIENT_PRESENT,\n run: runClientCapabilityStartCalled,\n },\n {\n // Stream-source direct-call check. Gated on realtime axis (rather\n // than tooling) since stream sources are a realtime concern — but\n // logically lives in tooling.ts alongside the other tool-reference\n // checks since the issue class is about referenced agentTools.\n id: \"realtime.stream_source.no_direct_call\",\n axis: \"realtime\",\n values: REALTIME_ACTIVE,\n run: runStreamSourceNoDirectCall,\n },\n {\n // Universal — fires on every tooling-axis value. The check itself\n // is contract-agnostic; the axis gate is \"every contract\" via the\n // full ALL_TOOLING_VALUES list (rather than the universal-check\n // module's \"render\" gate convention) so the anti-pattern stays\n // co-located with the other tooling-related rules.\n id: \"universal.no_retired_identifiers\",\n axis: \"tooling\",\n values: ALL_TOOLING_VALUES,\n run: runNoRetiredIdentifiers,\n },\n];\n","// packages/ui-gen/src/evaluation/axis-checks/extras.ts\n//\n// Axis-specific checks that had no legacy home. These fire on axis values\n// the old 3-mode dispatch didn't route (drag, swipe, compose, multi-step,\n// mixed streams). Intentionally narrow — each catches a specific failure\n// mode the fragments' prompt text tells the LLM to avoid.\n\nimport type { AxisCheck, AxisCheckInput } from \"./types.js\";\nimport type { EvalIssue } from \"../types-public.js\";\n\nfunction mkIssue(\n subcategory: string,\n description: string,\n fix: string,\n result: \"fail\" | \"warn\" = \"warn\",\n): EvalIssue {\n return { tier: 0, result, category: \"mode\", subcategory, description, fix };\n}\n\n/**\n * writeTrigger=drag → must attach onDragStart + onDrop (or onDragOver)\n * somewhere. Otherwise the drag handler is decorative.\n */\nconst dragTriggerWired: AxisCheck = {\n id: \"writeTrigger.drag.handlers_wired\",\n axis: \"writeTrigger\",\n values: [\"drag\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const hasStart = /onDragStart\\s*=/.test(src);\n const hasDrop = /onDrop\\s*=/.test(src);\n if (hasStart && hasDrop) return [];\n return [\n mkIssue(\n \"writeTrigger.drag.handlers_wired\",\n `Classified as writeTrigger=drag but component lacks ${!hasStart ? \"onDragStart\" : \"\"}${!hasStart && !hasDrop ? \" + \" : \"\"}${!hasDrop ? \"onDrop\" : \"\"} handlers.`,\n \"Attach onDragStart to draggable items and onDrop (with onDragOver preventDefault) to drop zones.\",\n \"fail\",\n ),\n ];\n },\n};\n\n/**\n * writeTrigger=swipe → must wire onTouchStart + onTouchEnd. Also emit\n * a warn if no fallback click handlers exist (desktop users).\n */\nconst swipeTriggerWired: AxisCheck = {\n id: \"writeTrigger.swipe.handlers_wired\",\n axis: \"writeTrigger\",\n values: [\"swipe\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const hasTouch = /onTouchStart\\s*=/.test(src) && /onTouchEnd\\s*=/.test(src);\n if (!hasTouch) {\n return [\n mkIssue(\n \"writeTrigger.swipe.handlers_wired\",\n \"Classified as writeTrigger=swipe but component lacks onTouchStart + onTouchEnd handlers.\",\n \"Wire onTouchStart to record the start X/Y, onTouchEnd to classify direction and fire the action.\",\n \"fail\",\n ),\n ];\n }\n return [];\n },\n};\n\n/**\n * writes=compose → exactly one action should be called with ids sourced\n * from two different state slots. Heuristic: at least two useState or\n * props.id references should appear in the action invocation's argument\n * region.\n *\n * Light check: warn if only one id-bearing field appears near the useAction\n * invocation (hard to get false-positive free without AST).\n */\nconst composeCrossEntity: AxisCheck = {\n id: \"writes.compose.cross_entity_ids\",\n axis: \"writes\",\n values: [\"compose\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n // Look for an action invocation passing an object literal with >= 2\n // `*Id` or `id` keys. That's the compose signature.\n const re = /\\{\\s*[^}]*?\\b(\\w*Id|id)\\b[^}]*?,\\s*[^}]*?\\b(\\w*Id|id)\\b[^}]*?\\}/s;\n if (re.test(src)) return [];\n return [\n mkIssue(\n \"writes.compose.cross_entity_ids\",\n \"Classified as writes=compose but no action invocation passes two id-bearing keys together.\",\n \"The compose action must receive both entity ids in one payload, e.g. `schedule({ eventId, calendarId })`.\",\n \"warn\",\n ),\n ];\n },\n};\n\n/**\n * layout=multi-step → integer step state + a step-guard on Next. Re-uses\n * the form check's multi-step signal, but fires even when writes != submit\n * (e.g., multi-step wizards that never submit, like onboarding).\n */\nconst multiStepHasState: AxisCheck = {\n id: \"layout.multi_step.state_present\",\n axis: \"layout\",\n values: [\"multi-step\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n const hasIntStep = /useState(?:<number>)?\\s*\\(\\s*[0-9]+\\s*\\)/.test(src);\n if (hasIntStep) return [];\n return [\n mkIssue(\n \"layout.multi_step.state_present\",\n \"Classified as layout=multi-step but no integer-typed useState tracks the current step.\",\n \"Add `const [step, setStep] = useState(0);` and branch rendering on it.\",\n \"fail\",\n ),\n ];\n },\n};\n\n/**\n * layout=multi-step → the design system's Stepper composite must be\n * ADOPTED (rendered). D8 (Exp 47) measured adoption at 17/18 from\n * fragment + JSDoc alone; this check gives the CHECK leg ownership of\n * the mandate so a regression surfaces as a fix turn instead of\n * silently shipping a wizard with no step affordance.\n *\n * Replaces the always-on `stepper-display-only` pitfall (deleted in the\n * same slice): with adoption carried by the WHAT leg, a 6th always-on\n * prompt rule was pure attention-dilution cost (the exp66 count-\n * sensitivity class, ~+9s blended), while this check prices at zero\n * outside multi-step cells. The pitfall's display-only guidance lives\n * on in the fix string below — delivered only when a cell actually\n * needs it.\n */\nconst stepperAdopted: AxisCheck = {\n id: \"layout.multi_step.stepper_adopted\",\n axis: \"layout\",\n values: [\"multi-step\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n if (/<Stepper[\\s/>]/.test(input.sourceCode)) return [];\n return [\n mkIssue(\n \"layout.multi_step.stepper_adopted\",\n \"Classified as layout=multi-step but the design system's Stepper composite is never rendered.\",\n \"Render <Stepper steps={STEPS} current={step} /> above the step body — STEPS is a top-level const array of step labels and `step` is your own useState index. Stepper is display-only: it never stores or advances the step itself.\",\n \"fail\",\n ),\n ];\n },\n};\n\n/**\n * realtime=mixed → the contract declares multiple events of different\n * kinds. Each must have its own useStream call. We approximate by\n * requiring ≥ 2 useStream calls when the vector is mixed.\n */\nconst mixedStreamsHaveHandlers: AxisCheck = {\n id: \"realtime.mixed.handlers_per_event\",\n axis: \"realtime\",\n values: [\"mixed\"],\n run(input: AxisCheckInput): EvalIssue[] {\n if (input.compiledCode === null) return [];\n const src = input.sourceCode;\n // Accept both `useStream('x')` and `useStream<T>('x')` (generic type arg).\n // The boilerplate pre-emits typed calls, so the `(` -only regex was a\n // 100%-false-positive on chat-interface + stock-ticker (Experiment 34).\n const matches = src.match(/useStream\\s*(?:<[^>]*>)?\\s*\\(/g);\n const count = matches?.length ?? 0;\n if (count >= 2) return [];\n return [\n mkIssue(\n \"realtime.mixed.handlers_per_event\",\n `Classified as realtime=mixed but only ${count} useStream call(s) found — mixed streams need one handler per event.`,\n \"Add a separate `useStream('eventName')` for each event in the contract.\",\n \"fail\",\n ),\n ];\n },\n};\n\nexport const EXTRA_CHECKS: readonly AxisCheck[] = [\n dragTriggerWired,\n swipeTriggerWired,\n composeCrossEntity,\n multiStepHasState,\n stepperAdopted,\n mixedStreamsHaveHandlers,\n];\n","// packages/ui-gen/src/evaluation/axis-checks/registry.ts\n//\n// Flat list of all axis-gated checks. The dispatcher iterates this and\n// runs every entry whose gate matches the classification's axis vector.\n\nimport type { AxisCheck } from \"./types.js\";\nimport { UNIVERSAL_CHECKS } from \"./checks/universal.js\";\nimport { STATE_MERGE_CHECKS } from \"./checks/state-merge.js\";\nimport { REALTIME_CHECKS } from \"./checks/realtime.js\";\nimport { WRITES_CHECKS } from \"./checks/writes.js\";\nimport { STATE_PAYLOAD_CHECKS } from \"./checks/state-payload.js\";\nimport { TOOLING_CHECKS } from \"./checks/tooling.js\";\nimport { EXTRA_CHECKS } from \"./extras.js\";\n\nexport const REGISTRY: readonly AxisCheck[] = [\n ...UNIVERSAL_CHECKS,\n ...STATE_MERGE_CHECKS,\n ...REALTIME_CHECKS,\n ...WRITES_CHECKS,\n ...STATE_PAYLOAD_CHECKS,\n ...TOOLING_CHECKS,\n ...EXTRA_CHECKS,\n];\n","// Axis-keyed dispatcher. Iterates the flat REGISTRY, runs each check\n// whose gate matches the classification's axis vector, and accumulates\n// issues.\n\nimport type { DataContract } from \"@ggui-ai/protocol\";\nimport type { Classification } from \"../../classifier/index.js\";\nimport type { EvalIssue } from \"../types-public.js\";\nimport { REGISTRY } from \"./registry.js\";\nimport { matches, type AxisCheckInput } from \"./types.js\";\n\nexport interface RunAxisChecksInput {\n sourceCode: string;\n compiledCode: string | null;\n contract?: DataContract;\n originalPrompt: string;\n}\n\nexport function runAxisChecks(\n classification: Classification,\n input: RunAxisChecksInput,\n): EvalIssue[] {\n if (input.compiledCode === null) return [];\n\n const axisInput: AxisCheckInput = {\n sourceCode: input.sourceCode,\n compiledCode: input.compiledCode,\n ...(input.contract !== undefined ? { contract: input.contract } : {}),\n originalPrompt: input.originalPrompt,\n classification,\n };\n\n const issues: EvalIssue[] = [];\n const firedIds = new Set<string>();\n for (const check of REGISTRY) {\n if (!matches(classification.vector, check)) continue;\n // Dedup by id — a check may be registered under multiple gates.\n if (firedIds.has(check.id)) continue;\n firedIds.add(check.id);\n issues.push(...check.run(axisInput));\n }\n return issues;\n}\n"]}