{"version":3,"file":"index.mjs","names":[],"sources":["../src/validate.ts","../src/recovery.ts","../src/index.ts"],"sourcesContent":["/**\n * Semantic validation of A2UI v0.9 component trees (OSS-162).\n *\n * The middleware's streaming path only checks *structural* completeness (array\n * closed, each item has a `component` string). This module adds the *semantic*\n * checks whose failures otherwise blow up at render time in `@a2ui/web_core`\n * (\"Component not found\", \"Catalog not found\", unresolved bindings) — turning\n * them into machine-readable errors the recovery loop can feed back to the\n * sub-agent.\n *\n * Used by BOTH the adapter (to decide whether to retry) and the middleware (to\n * decide whether to paint) so the two never disagree on what \"valid\" means.\n */\n\n/** A single, machine-readable validation failure. */\nexport interface A2UIValidationError {\n  code:\n    | \"empty_components\"\n    | \"missing_id\"\n    | \"missing_component_type\"\n    | \"duplicate_id\"\n    | \"no_root\"\n    | \"unknown_component\"\n    | \"missing_required_prop\"\n    | \"unresolved_child\"\n    | \"child_cycle\"\n    | \"unresolved_binding\";\n  /** A JSON-pointer-ish locator, e.g. `components[2].component`. */\n  path: string;\n  /** Human/LLM-readable description (fed back to the sub-agent on retry). */\n  message: string;\n}\n\nexport interface ValidateA2UIResult {\n  valid: boolean;\n  errors: A2UIValidationError[];\n}\n\n/**\n * Inline JSON-Schema catalog (mirrors the middleware's `A2UIInlineCatalogSchema`):\n * component name → JSON Schema whose `required` lists mandatory props.\n */\nexport interface A2UIValidationCatalog {\n  components: Record<string, { required?: string[]; properties?: Record<string, unknown>; [k: string]: unknown }>;\n}\n\nexport interface ValidateA2UIInput {\n  components: Array<Record<string, unknown>>;\n  /** The surface's data model; used to resolve absolute binding paths. */\n  data?: Record<string, unknown>;\n  /** When omitted, catalog-dependent checks (membership, required props) are skipped. */\n  catalog?: A2UIValidationCatalog;\n  /**\n   * Resolve absolute binding paths against `data`. Default `true`. Set `false`\n   * at the streaming component-close boundary, where the component tree has\n   * closed but the data model has not streamed yet — resolving bindings there\n   * would false-positive (and trigger spurious retries). The adapter re-runs\n   * full validation (bindings included) once the complete args arrive.\n   */\n  validateBindings?: boolean;\n}\n\n/** Does `path` (absolute, e.g. `/items/0/name`) resolve in `data`? */\nfunction absolutePathResolves(path: string, data: unknown): boolean {\n  const segments = path.split(\"/\").filter((s) => s.length > 0);\n  let cursor: unknown = data;\n  for (const seg of segments) {\n    if (cursor == null || typeof cursor !== \"object\") return false;\n    if (Array.isArray(cursor)) {\n      const idx = Number(seg);\n      if (!Number.isInteger(idx) || idx < 0 || idx >= cursor.length) return false;\n      cursor = cursor[idx];\n    } else {\n      if (!(seg in (cursor as Record<string, unknown>))) return false;\n      cursor = (cursor as Record<string, unknown>)[seg];\n    }\n  }\n  return true;\n}\n\n/** True for a plain (non-array) object. */\nfunction isObject(v: unknown): v is Record<string, unknown> {\n  return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/**\n * Validate a flat A2UI v0.9 component array.\n *\n * Structural checks always run. Catalog membership + required-prop checks run\n * only when `catalog` is supplied. Absolute binding paths (`/foo`) are resolved\n * against `data`; relative template paths (`name`) are left alone — they resolve\n * per-item inside a repeated template and flagging them would produce false\n * positives (and spurious retries).\n */\nexport function validateA2UIComponents(input: ValidateA2UIInput): ValidateA2UIResult {\n  const { components, data, catalog } = input;\n  const validateBindings = input.validateBindings ?? true;\n  const errors: A2UIValidationError[] = [];\n\n  // Fail loud on a non-array / empty payload — there is nothing to render and\n  // nothing meaningful to feed back, so the caller must not treat it as a\n  // recoverable surface silently.\n  if (!Array.isArray(components) || components.length === 0) {\n    return {\n      valid: false,\n      errors: [{ code: \"empty_components\", path: \"components\", message: \"A2UI components must be a non-empty array\" }],\n    };\n  }\n\n  const ids = new Set<string>();\n  const seen = new Set<string>();\n  for (const comp of components) {\n    const id = isObject(comp) ? comp.id : undefined;\n    if (typeof id === \"string\") {\n      if (seen.has(id)) {\n        errors.push({ code: \"duplicate_id\", path: `components[id=${id}]`, message: `Duplicate component id '${id}'` });\n      }\n      seen.add(id);\n      ids.add(id);\n    }\n  }\n\n  components.forEach((comp, i) => {\n    const id = isObject(comp) ? comp.id : undefined;\n    const type = isObject(comp) ? comp.component : undefined;\n\n    if (typeof id !== \"string\" || id.length === 0) {\n      errors.push({ code: \"missing_id\", path: `components[${i}].id`, message: `Component at index ${i} is missing a string 'id'` });\n    }\n    if (typeof type !== \"string\" || type.length === 0) {\n      errors.push({\n        code: \"missing_component_type\",\n        path: `components[${i}].component`,\n        message: `Component at index ${i} is missing a string 'component' type`,\n      });\n    }\n\n    // Catalog membership + required props (only when a catalog is supplied).\n    if (catalog && typeof type === \"string\") {\n      const schema = catalog.components[type];\n      if (!schema) {\n        errors.push({\n          code: \"unknown_component\",\n          path: `components[${i}].component`,\n          message: `Component type '${type}' is not in the catalog`,\n        });\n      } else {\n        for (const req of schema.required ?? []) {\n          if (!isObject(comp) || !(req in comp)) {\n            errors.push({\n              code: \"missing_required_prop\",\n              path: `components[${i}].${req}`,\n              message: `Component '${type}' (index ${i}) is missing required prop '${req}'`,\n            });\n          }\n        }\n      }\n    }\n\n    // Child references must resolve to existing component ids. The implicit\n    // `child`/`children` fields are always checked; catalog-marked ref-fields\n    // (Modal `trigger`/`content`, Tabs `tabItems[].child`, …) are checked too\n    // when a catalog is supplied. A dangling reference in any of them is fed\n    // back to the recovery loop. See `collectComponentRefEdges`.\n    if (isObject(comp)) {\n      const schema = catalog && typeof type === \"string\" ? catalog.components[type] : undefined;\n      collectComponentRefEdges(comp, schema).forEach(({ path: refPath, ref }) => {\n        if (!ids.has(ref)) {\n          errors.push({\n            code: \"unresolved_child\",\n            path: `components[${i}].${refPath}`,\n            message: `Child reference '${ref}' does not match any component id`,\n          });\n        }\n      });\n\n      // Absolute binding paths must resolve against the data model (unless\n      // deferred — see `validateBindings`).\n      if (validateBindings) collectAbsoluteBindingPaths(comp).forEach((p) => {\n        if (!absolutePathResolves(p, data ?? {})) {\n          errors.push({\n            code: \"unresolved_binding\",\n            path: `components[${i}]`,\n            message: `Binding path '${p}' does not resolve in the data model`,\n          });\n        }\n      });\n    }\n  });\n\n  // The child reference tree must be a DAG — a component that (transitively)\n  // references itself never terminates at render time. Report each cycle once.\n  findChildCycles(components, catalog).forEach((cycle) => {\n    errors.push({\n      code: \"child_cycle\",\n      path: `components[id=${cycle[0]}]`,\n      message: `Child reference cycle detected: ${[...cycle, cycle[0]].join(\" -> \")}`,\n    });\n  });\n\n  if (!components.some((c) => isObject(c) && c.id === \"root\")) {\n    errors.push({ code: \"no_root\", path: \"components\", message: \"No component has id 'root'\" });\n  }\n\n  return { valid: errors.length === 0, errors };\n}\n\n/**\n * Pull child-id references out of a `child`/`children` value: an array of ids or\n * `{componentId,...}` templates, a single `{componentId,...}` template, or a bare\n * string id (the singular `child` shape Card/Button use).\n */\nfunction collectChildRefs(children: unknown): string[] {\n  const refs: string[] = [];\n  const push = (v: unknown) => {\n    if (typeof v === \"string\") refs.push(v);\n    else if (isObject(v) && typeof v.componentId === \"string\") refs.push(v.componentId);\n  };\n  if (Array.isArray(children)) children.forEach(push);\n  else push(children);\n  return refs;\n}\n\n/** A single child reference and the field-path suffix it was found at (e.g. `children[0]`, `tabItems[1].child`). */\ninterface RefEdge {\n  path: string;\n  ref: string;\n}\n\n/**\n * Collect every child reference a component makes, paired with its field-path\n * suffix, by deriving ref-fields from the catalog (#1948).\n *\n * The implicit `child` (single) and `children` (list) fields are ALWAYS ref\n * fields, even with no catalog — this preserves the #1944 / catalog-free\n * behaviour. Other fields are refs ONLY when the component's catalog schema\n * marks the property `\"format\": \"componentRef\"` (single) or\n * `\"componentRefList\"` (list). For an array-typed property whose `items` is an\n * object schema, marked sub-properties are honoured per element (this is how\n * Tabs `tabItems[].child` is found — derived, never hard-coded). A property with\n * no marker is treated as data, never a ref — a bare data string and a bare ref\n * string are otherwise indistinguishable, so shape-based detection is unsafe.\n *\n * Path grammar (byte-aligned with the Python/.NET siblings):\n *   single-ref field             → `<field>`\n *   list-ref field (array)       → `<field>[k]`\n *   list-ref field (single tmpl) → `<field>`\n *   nested array-of-object ref   → `<arrayField>[k].<refField>` (and `[j]` if that sub-field is itself a list)\n */\nfunction collectComponentRefEdges(\n  comp: Record<string, unknown>,\n  schema: { properties?: Record<string, unknown>; [k: string]: unknown } | undefined,\n): RefEdge[] {\n  const edges: RefEdge[] = [];\n\n  const pushSingle = (field: string, value: unknown) => {\n    collectChildRefs(value).forEach((ref) => edges.push({ path: field, ref }));\n  };\n  const pushList = (field: string, value: unknown) => {\n    if (Array.isArray(value)) {\n      value.forEach((item, k) => collectChildRefs(item).forEach((ref) => edges.push({ path: `${field}[${k}]`, ref })));\n    } else {\n      collectChildRefs(value).forEach((ref) => edges.push({ path: field, ref }));\n    }\n  };\n\n  // Implicit refs — always, regardless of catalog.\n  pushSingle(\"child\", comp.child);\n  pushList(\"children\", comp.children);\n\n  // Explicit catalog-marked refs.\n  const props = schema?.properties;\n  if (isObject(props)) {\n    for (const [field, propSchema] of Object.entries(props)) {\n      if (field === \"child\" || field === \"children\" || !isObject(propSchema)) continue;\n      const fmt = propSchema.format;\n      if (fmt === \"componentRef\") {\n        pushSingle(field, comp[field]);\n      } else if (fmt === \"componentRefList\") {\n        pushList(field, comp[field]);\n      } else if (propSchema.type === \"array\" && isObject(propSchema.items)) {\n        const itemProps = (propSchema.items as Record<string, unknown>).properties;\n        const arrVal = comp[field];\n        if (isObject(itemProps) && Array.isArray(arrVal)) {\n          arrVal.forEach((item, k) => {\n            if (!isObject(item)) return;\n            for (const [sub, subSchema] of Object.entries(itemProps)) {\n              if (!isObject(subSchema)) continue;\n              if (subSchema.format === \"componentRef\") {\n                collectChildRefs(item[sub]).forEach((ref) => edges.push({ path: `${field}[${k}].${sub}`, ref }));\n              } else if (subSchema.format === \"componentRefList\") {\n                const subVal = item[sub];\n                if (Array.isArray(subVal)) {\n                  subVal.forEach((sv, j) => collectChildRefs(sv).forEach((ref) => edges.push({ path: `${field}[${k}].${sub}[${j}]`, ref })));\n                } else {\n                  collectChildRefs(subVal).forEach((ref) => edges.push({ path: `${field}[${k}].${sub}`, ref }));\n                }\n              }\n            }\n          });\n        }\n      }\n    }\n  }\n\n  return edges;\n}\n\n/** id → ordered child-id references, derived per component via `collectComponentRefEdges`. */\nfunction childAdjacency(components: Array<Record<string, unknown>>, catalog?: A2UIValidationCatalog): Map<string, string[]> {\n  const adj = new Map<string, string[]>();\n  for (const comp of components) {\n    if (isObject(comp) && typeof comp.id === \"string\") {\n      const type = typeof comp.component === \"string\" ? comp.component : undefined;\n      const schema = catalog && type ? catalog.components[type] : undefined;\n      adj.set(\n        comp.id,\n        collectComponentRefEdges(comp, schema).map((e) => e.ref),\n      );\n    }\n  }\n  return adj;\n}\n\n/**\n * Find unique child-reference cycles (self-references and longer loops) over the\n * child graph via a depth-first search. Each cycle is canonicalised — rotated so\n * the lexicographically smallest id leads — so the same loop reached from\n * different entry points collapses to one finding, and the reported chain stays\n * byte-identical across the sibling toolkits.\n */\nfunction findChildCycles(components: Array<Record<string, unknown>>, catalog?: A2UIValidationCatalog): string[][] {\n  const adj = childAdjacency(components, catalog);\n  const color = new Map<string, number>(); // absent/0 = unvisited, 1 = on stack, 2 = done\n  const cycles = new Map<string, string[]>();\n\n  const canonical = (nodes: string[]): string[] => {\n    let m = 0;\n    for (let i = 1; i < nodes.length; i++) if (nodes[i] < nodes[m]) m = i;\n    return [...nodes.slice(m), ...nodes.slice(0, m)];\n  };\n\n  // Iterative DFS (explicit frame stack, not call recursion): the validator runs\n  // on untrusted model output, so a pathologically deep child chain must not\n  // overflow the native call stack. `path` mirrors the on-stack (gray) nodes in\n  // entry order, so `path.indexOf(v)` recovers the cycle slice on a back edge.\n  for (const root of adj.keys()) {\n    if ((color.get(root) ?? 0) !== 0) continue;\n    const frames: Array<{ node: string; i: number }> = [{ node: root, i: 0 }];\n    const path: string[] = [root];\n    color.set(root, 1);\n    while (frames.length > 0) {\n      const frame = frames[frames.length - 1];\n      const neighbors = adj.get(frame.node) ?? [];\n      if (frame.i >= neighbors.length) {\n        color.set(frame.node, 2);\n        frames.pop();\n        path.pop();\n        continue;\n      }\n      const v = neighbors[frame.i++];\n      const c = color.get(v) ?? 0;\n      if (c === 0) {\n        color.set(v, 1);\n        path.push(v);\n        frames.push({ node: v, i: 0 });\n      } else if (c === 1) {\n        const cyc = canonical(path.slice(path.indexOf(v)));\n        const key = cyc.join(\"\u0000\");\n        if (!cycles.has(key)) cycles.set(key, cyc);\n      }\n    }\n  }\n  return [...cycles.values()];\n}\n\n/** Recursively collect absolute (`/…`) binding paths from a component's props. */\nfunction collectAbsoluteBindingPaths(node: unknown, acc: string[] = []): string[] {\n  if (Array.isArray(node)) {\n    node.forEach((v) => collectAbsoluteBindingPaths(v, acc));\n  } else if (isObject(node)) {\n    if (typeof node.path === \"string\" && node.path.startsWith(\"/\")) acc.push(node.path);\n    for (const [k, v] of Object.entries(node)) {\n      if (k === \"path\") continue;\n      collectAbsoluteBindingPaths(v, acc);\n    }\n  }\n  return acc;\n}\n","/**\n * A2UI error-recovery loop (OSS-162).\n *\n * Framework-agnostic: the toolkit cannot bind/invoke a model, so the adapter\n * supplies an `invokeSubagent` closure (its framework-specific model call) and a\n * `buildEnvelope` closure (its prepared create/update context). This module owns\n * the loop: invoke → validate (shared `validateA2UIComponents`) → on failure feed\n * the structured errors back into the prompt and retry, up to `maxAttempts`.\n *\n * The SAME validator gates the middleware's paint decision, so the tool's retry\n * decision and the middleware's suppress decision can never disagree.\n */\nimport {\n  validateA2UIComponents,\n  type A2UIValidationCatalog,\n  type A2UIValidationError,\n} from \"./validate\";\n\n/** Default attempt cap (initial try + retries). Configurable per call. */\nexport const MAX_A2UI_ATTEMPTS = 3;\n\n/** Activity type the middleware/client use for the recovery status channel. */\nexport const A2UI_RECOVERY_ACTIVITY_TYPE = \"a2ui_recovery\";\n\n/**\n * Developer-configurable recovery surface (Tyler's requirement). The threshold\n * is behavioral, not a hardcoded number: `showRetryUIAfter` lets the host decide\n * when the \"Retrying…\" status becomes perceptible enough to show.\n */\nexport interface A2UIRecoveryConfig {\n  /** Attempt cap (initial + retries). Default `MAX_A2UI_ATTEMPTS`. */\n  maxAttempts?: number;\n  /** When the (client-side) \"Retrying UI generation…\" status may appear. */\n  showRetryUIAfter?: { ms?: number; attempts?: number };\n  // NOTE: debugExposure is NOT here — how much retry/error detail the renderer\n  // surfaces is a presentation concern configured server-side via the\n  // A2UIMiddleware's `recovery.debugExposure` (stamped into the a2ui_recovery\n  // activity), not on this generation-loop config. (OSS-162)\n}\n\n/** One attempt's outcome — surfaced to the adapter via `onAttempt` for status + dev traces. */\nexport interface A2UIAttemptRecord {\n  /** 1-based attempt number. */\n  attempt: number;\n  ok: boolean;\n  errors: A2UIValidationError[];\n}\n\nexport interface RunA2UIRecoveryInput {\n  /** The prepared sub-agent system prompt (output of `prepareA2UIRequest`). */\n  basePrompt: string;\n  /** Inline catalog for semantic validation; omit for structural-only. */\n  catalog?: A2UIValidationCatalog;\n  config?: A2UIRecoveryConfig;\n  /**\n   * Run the sub-agent once with `prompt` (already augmented with prior errors on\n   * retries) and return its `render_a2ui` args `{surfaceId, components, data}`,\n   * or `null` if the model produced no tool call.\n   */\n  invokeSubagent: (prompt: string, attempt: number) => Promise<Record<string, unknown> | null>;\n  /** Turn validated `render_a2ui` args into the final operations envelope. */\n  buildEnvelope: (args: Record<string, unknown>) => string;\n  /** Per-attempt callback for emitting recovery status + dev logs. */\n  onAttempt?: (record: A2UIAttemptRecord) => void;\n}\n\nexport interface RunA2UIRecoveryResult {\n  /** Either the validated operations envelope, or a structured hard-failure envelope. */\n  envelope: string;\n  attempts: A2UIAttemptRecord[];\n  ok: boolean;\n}\n\n/** Render structured errors as a compact, model-readable list. */\nexport function formatValidationErrors(errors: A2UIValidationError[]): string {\n  return errors.map((e) => `- [${e.code}] ${e.path}: ${e.message}`).join(\"\\n\");\n}\n\n/** Append a fix-it block describing the prior attempt's errors. No-op when there are none. */\nexport function augmentPromptWithValidationErrors(prompt: string, errors: A2UIValidationError[]): string {\n  if (!errors.length) return prompt;\n  return (\n    `${prompt}\\n\\n## Previous attempt was invalid — fix these and regenerate:\\n` +\n    `${formatValidationErrors(errors)}\\n`\n  );\n}\n\nconst NO_TOOL_CALL_ERROR: A2UIValidationError = {\n  code: \"empty_components\",\n  path: \"components\",\n  message: \"Sub-agent did not call render_a2ui\",\n};\n\n/** Wrap an exhausted-recovery hard failure as the JSON envelope the middleware recognises. */\nfunction wrapRecoveryExhaustedEnvelope(maxAttempts: number, attempts: A2UIAttemptRecord[]): string {\n  return JSON.stringify({\n    error: `Failed to generate valid A2UI after ${maxAttempts} attempt(s)`,\n    code: \"a2ui_recovery_exhausted\",\n    attempts,\n  });\n}\n\n/**\n * Drive the validate→retry loop. Returns the validated envelope on success, or a\n * structured `a2ui_recovery_exhausted` envelope once the cap is hit. Never retries\n * an attempt whose components validated (the adapter must commit it).\n */\nexport async function runA2UIGenerationWithRecovery(\n  input: RunA2UIRecoveryInput,\n): Promise<RunA2UIRecoveryResult> {\n  const maxAttempts = input.config?.maxAttempts ?? MAX_A2UI_ATTEMPTS;\n  const attempts: A2UIAttemptRecord[] = [];\n  let lastErrors: A2UIValidationError[] = [];\n\n  for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n    const prompt = augmentPromptWithValidationErrors(input.basePrompt, lastErrors);\n    const args = await input.invokeSubagent(prompt, attempt);\n\n    if (!args) {\n      const record: A2UIAttemptRecord = { attempt, ok: false, errors: [NO_TOOL_CALL_ERROR] };\n      attempts.push(record);\n      input.onAttempt?.(record);\n      lastErrors = record.errors;\n      continue;\n    }\n\n    const components = Array.isArray(args.components) ? (args.components as Array<Record<string, unknown>>) : [];\n    const data =\n      args.data && typeof args.data === \"object\" && !Array.isArray(args.data)\n        ? (args.data as Record<string, unknown>)\n        : {};\n    const result = validateA2UIComponents({ components, data, catalog: input.catalog });\n    const record: A2UIAttemptRecord = { attempt, ok: result.valid, errors: result.errors };\n    attempts.push(record);\n    input.onAttempt?.(record);\n\n    if (result.valid) {\n      return { envelope: input.buildEnvelope(args), attempts, ok: true };\n    }\n    lastErrors = result.errors;\n  }\n\n  return { envelope: wrapRecoveryExhaustedEnvelope(maxAttempts, attempts), attempts, ok: false };\n}\n","/**\n * @ag-ui/a2ui-toolkit\n *\n * Framework-agnostic building blocks for A2UI subagent tools. Each per-\n * framework adapter (LangGraph, ADK, Mastra, etc.) composes these helpers\n * with its framework-specific glue (tool decorator, runtime accessor, model\n * binding/invoke). Nothing in this package depends on any agent framework.\n */\n\nimport type { A2UIRecoveryConfig, A2UIAttemptRecord } from \"./recovery\";\nimport type { A2UIValidationCatalog } from \"./validate\";\n\n/** Container key the A2UI middleware looks for in tool results. */\nexport const A2UI_OPERATIONS_KEY = \"a2ui_operations\";\n\n/** Default catalog id used when the subagent does not specify one. */\nexport const BASIC_CATALOG_ID = \"https://a2ui.org/specification/v0_9/basic_catalog.json\";\n\n/** A single A2UI v0.9 server-to-client operation. */\nexport type A2UIOperation = Record<string, unknown>;\n\n// ---------------------------------------------------------------------------\n// Op builders\n// ---------------------------------------------------------------------------\n\nexport function createSurface(surfaceId: string, catalogId: string): A2UIOperation {\n  return {\n    version: \"v0.9\",\n    createSurface: { surfaceId, catalogId },\n  };\n}\n\nexport function updateComponents(\n  surfaceId: string,\n  components: Array<Record<string, unknown>>,\n): A2UIOperation {\n  return {\n    version: \"v0.9\",\n    updateComponents: { surfaceId, components },\n  };\n}\n\nexport function updateDataModel(\n  surfaceId: string,\n  data: unknown,\n  path: string = \"/\",\n): A2UIOperation {\n  return {\n    version: \"v0.9\",\n    updateDataModel: { surfaceId, path, value: data },\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Inner render_a2ui tool definition\n// ---------------------------------------------------------------------------\n\n/**\n * JSON schema for the inner ``render_a2ui`` tool. Framework adapters bind\n * this on the subagent's model with ``tool_choice=\"render_a2ui\"`` so the\n * structured-output call produces ``{surfaceId, components, data}``. The\n * catalog id is owned by the factory, not the subagent — the subagent can't\n * invent a catalog the host hasn't registered.\n */\nexport const RENDER_A2UI_TOOL_DEF = {\n  type: \"function\" as const,\n  function: {\n    name: \"render_a2ui\",\n    description:\n      \"Render a dynamic A2UI v0.9 surface. The root component must have id 'root'. \" +\n      \"Use components from the available catalog only.\",\n    parameters: {\n      type: \"object\",\n      properties: {\n        surfaceId: {\n          type: \"string\",\n          description: \"Unique surface identifier.\",\n        },\n        components: {\n          type: \"array\",\n          description:\n            \"A2UI v0.9 component array (flat format). The root component must have id 'root'.\",\n          items: { type: \"object\" },\n        },\n        data: {\n          type: \"object\",\n          description:\n            \"Optional initial data model for the surface (form values, list items, etc.).\",\n        },\n      },\n      required: [\"surfaceId\", \"components\"],\n    },\n  },\n};\n\n// ---------------------------------------------------------------------------\n// State helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Build the prompt prefix from AG-UI state context entries + the A2UI\n * component catalog. Framework integrations conventionally extract the\n * catalog into ``state[\"ag-ui\"][\"a2ui_schema\"]`` and forward other context\n * entries (generation guidelines, design guidelines) under\n * ``state[\"ag-ui\"][\"context\"]``.\n */\nexport function buildContextPrompt(state: Record<string, unknown>): string {\n  const agUi = (state[\"ag-ui\"] as Record<string, unknown> | undefined) ?? {};\n  const parts: string[] = [];\n\n  const contextEntries = (agUi.context as Array<Record<string, unknown>> | undefined) ?? [];\n  for (const entry of contextEntries) {\n    const desc = entry?.description as string | undefined;\n    const value = entry?.value as string | undefined;\n    if (desc) {\n      parts.push(`## ${desc}\\n${value ?? \"\"}\\n`);\n    } else if (value) {\n      parts.push(`${value}\\n`);\n    }\n  }\n\n  const schema = agUi.a2ui_schema as string | undefined;\n  if (schema) {\n    parts.push(`## Available Components\\n${schema}\\n`);\n  }\n\n  return parts.join(\"\\n\");\n}\n\n/**\n * Context-entry description the ``@ag-ui/a2ui-middleware`` stamps onto the A2UI\n * component schema it injects into ``RunAgentInput.context``. Single home for\n * the constant so every framework adapter splits on the same string. MUST stay\n * byte-identical to ``A2UI_SCHEMA_CONTEXT_DESCRIPTION`` in\n * ``@ag-ui/a2ui-middleware`` (this is a wire contract, not prose).\n */\nexport const A2UI_SCHEMA_CONTEXT_DESCRIPTION =\n  \"A2UI Component Schema — available components for generating UI surfaces. \" +\n  \"Use these component names and properties when creating A2UI operations.\";\n\n/**\n * Split AG-UI context entries into the A2UI component-schema entry and the\n * rest. The schema entry is the one whose ``description`` exactly equals\n * ``A2UI_SCHEMA_CONTEXT_DESCRIPTION``. Returns ``[schemaValue, regularContext]``:\n * adapters route ``schemaValue`` to ``state[\"ag-ui\"][\"a2ui_schema\"]`` (rendered\n * as ``## Available Components`` by ``buildContextPrompt``) and ``regularContext``\n * to ``state[\"ag-ui\"][\"context\"]``. Entries are returned unchanged.\n */\nexport function splitA2UISchemaContext(\n  context: Array<Record<string, unknown>> | undefined | null,\n): [string | undefined, Array<Record<string, unknown>>] {\n  let schemaValue: string | undefined;\n  const regular: Array<Record<string, unknown>> = [];\n  for (const entry of context ?? []) {\n    const description = entry?.description as string | undefined;\n    if (description === A2UI_SCHEMA_CONTEXT_DESCRIPTION) {\n      schemaValue = entry?.value as string | undefined;\n    } else {\n      regular.push(entry);\n    }\n  }\n  return [schemaValue, regular];\n}\n\n/**\n * Find the frontend-registered A2UI catalog in run ``state``, returning\n * ``[componentSchema, catalogId]`` or ``undefined`` when no catalog is present.\n * Framework-agnostic, so every adapter resolves the catalog the same way.\n * Both delivery shapes live under the canonical ``state[\"ag-ui\"]`` key:\n * - Schema entry: ``state[\"ag-ui\"][\"a2ui_schema\"]``, a JSON string\n *   ``{\"catalogId\": ..., \"components\": [...]}`` (toolkit reads the schema from\n *   state for the prompt itself, so only the id is surfaced here).\n * - Catalog context entry: an ``state[\"ag-ui\"][\"context\"]`` entry whose\n *   description mentions ``\"A2UI catalog\"``; the value lists catalogs as\n *   ``\"- <catalogId>\"`` lines, the first being the custom catalog.\n */\nexport function resolveA2UICatalog(\n  state: Record<string, unknown>,\n): [string | undefined, string | undefined] | undefined {\n  const agUi = (state[\"ag-ui\"] as Record<string, unknown> | undefined) ?? {};\n  const a2uiSchema = agUi.a2ui_schema;\n  if (a2uiSchema) {\n    let catalogId: string | undefined;\n    try {\n      const parsed =\n        typeof a2uiSchema === \"string\" ? JSON.parse(a2uiSchema) : a2uiSchema;\n      if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n        catalogId = (parsed as Record<string, unknown>).catalogId as\n          | string\n          | undefined;\n      }\n    } catch {\n      // Unparseable schema -> no id (degrade to the configured default).\n    }\n    return [undefined, catalogId];\n  }\n\n  const contextEntries =\n    (agUi.context as Array<Record<string, unknown>> | undefined) ?? [];\n  for (const entry of contextEntries) {\n    const description = (entry?.description as string | undefined) ?? \"\";\n    const value = (entry?.value as string | undefined) ?? \"\";\n    if (!description.includes(\"A2UI catalog\") || !value) continue;\n    const match = value.match(/^\\s*-\\s+(\\S+)/m);\n    return [value, match ? match[1] : undefined];\n  }\n\n  return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Prior surface lookup (used for intent=\"update\")\n// ---------------------------------------------------------------------------\n\nexport interface PriorSurface {\n  components: Array<Record<string, unknown>>;\n  data: unknown;\n  catalogId?: string;\n}\n\n/**\n * Locate the most recent rendered state for ``surfaceId`` in message history.\n *\n * Walks backwards looking for a tool result whose content is a JSON string\n * containing ``a2ui_operations`` for the given surface. Returns the\n * reconstructed ``{components, data, catalogId}``, or ``undefined`` if no\n * matching surface is found.\n */\nexport function findPriorSurface(\n  messages: Array<any>,\n  surfaceId: string,\n): PriorSurface | undefined {\n  // Accumulate the surface's state across the walk, newest-to-oldest. For each\n  // field, the FIRST occurrence we see (newest) wins; older messages only fill\n  // in fields the more recent ones omitted.\n  //\n  // Per-message end-state is computed FORWARD because the renderer applies ops\n  // in document order. The last op affecting the surface in a message\n  // determines that message's contribution — including `deleteSurface`, which\n  // wipes the surface. If the NEWEST message to mention the surface ends in\n  // delete, the surface is gone and we must return undefined; older\n  // create/update ops are stale and would resurrect a surface the renderer no\n  // longer shows.\n  let components: Array<Record<string, unknown>> | undefined;\n  let data: unknown;\n  let dataSeen = false;\n  let catalogId: string | undefined;\n  let matched = false;\n\n  for (let i = messages.length - 1; i >= 0; i--) {\n    const msg = messages[i];\n    if (!msg) continue;\n    const role = msg.type ?? msg.role;\n    if (role !== \"tool\" && role !== \"ToolMessage\") continue;\n    const content = msg.content;\n    if (typeof content !== \"string\") continue;\n    let parsed: unknown;\n    try {\n      parsed = JSON.parse(content);\n    } catch {\n      continue;\n    }\n    if (!parsed || typeof parsed !== \"object\") continue;\n    const ops = (parsed as Record<string, unknown>)[A2UI_OPERATIONS_KEY];\n    if (!Array.isArray(ops)) continue;\n\n    // Compute this message's END STATE for surfaceId by walking ops forward.\n    // `deleteSurface` resets the per-message accumulator; subsequent create /\n    // update ops in the same message restore it.\n    let msgMentions = false;\n    let msgDeleted = false;\n    let msgCatalogId: string | undefined;\n    let msgComponents: Array<Record<string, unknown>> | undefined;\n    let msgData: unknown;\n    let msgDataSeen = false;\n\n    for (const op of ops) {\n      if (!op || typeof op !== \"object\") continue;\n      const opObj = op as Record<string, unknown>;\n\n      const ds = opObj.deleteSurface as Record<string, unknown> | undefined;\n      if (ds && ds.surfaceId === surfaceId) {\n        msgMentions = true;\n        msgDeleted = true;\n        msgCatalogId = undefined;\n        msgComponents = undefined;\n        msgData = undefined;\n        msgDataSeen = false;\n        continue;\n      }\n\n      const cs = opObj.createSurface as Record<string, unknown> | undefined;\n      if (cs && cs.surfaceId === surfaceId) {\n        msgMentions = true;\n        msgDeleted = false;\n        if (typeof cs.catalogId === \"string\") {\n          msgCatalogId = cs.catalogId;\n        }\n      }\n      const uc = opObj.updateComponents as Record<string, unknown> | undefined;\n      if (uc && uc.surfaceId === surfaceId) {\n        msgMentions = true;\n        msgDeleted = false;\n        if (Array.isArray(uc.components)) {\n          msgComponents = uc.components as Array<Record<string, unknown>>;\n        }\n      }\n      const ud = opObj.updateDataModel as Record<string, unknown> | undefined;\n      if (ud && ud.surfaceId === surfaceId) {\n        msgMentions = true;\n        msgDeleted = false;\n        msgData = ud.value;\n        msgDataSeen = true;\n      }\n    }\n\n    if (!msgMentions) continue;\n\n    if (!matched) {\n      // First (newest) message to mention the surface — its end state is the\n      // authoritative current state.\n      if (msgDeleted) return undefined;\n      matched = true;\n      catalogId = msgCatalogId;\n      components = msgComponents;\n      data = msgData;\n      dataSeen = msgDataSeen;\n    } else {\n      // Older message: only fill in fields not yet set. A delete here is\n      // overridden by the newer creation we already recorded.\n      if (msgDeleted) continue;\n      if (catalogId === undefined && msgCatalogId !== undefined) catalogId = msgCatalogId;\n      if (components === undefined && msgComponents !== undefined) components = msgComponents;\n      if (!dataSeen && msgDataSeen) {\n        data = msgData;\n        dataSeen = true;\n      }\n    }\n\n    // Early-exit once every field has been populated — nothing older can\n    // override what we already have.\n    if (matched && components !== undefined && catalogId !== undefined && dataSeen) {\n      return { components, data, catalogId };\n    }\n  }\n\n  if (!matched) return undefined;\n  return { components: components ?? [], data, catalogId };\n}\n\n// ---------------------------------------------------------------------------\n// Prompt assembly\n// ---------------------------------------------------------------------------\n\nexport interface EditContext {\n  surfaceId: string;\n  prior: PriorSurface;\n  changes?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Subagent prompt guidelines (OSS-248)\n//\n// Re-enables the rich generation + design guidance the legacy\n// `copilotkit.a2ui.a2ui_prompt` shipped. The two DEFAULT_* blocks are applied\n// automatically (per-field) so subagent output is well-designed out of the box;\n// a host overrides either block via `A2UIGuidelines`. Pass an empty string to\n// suppress a block entirely.\n// ---------------------------------------------------------------------------\n\n/**\n * Default generation guidance (tool-call contract, id/path/data-binding rules).\n * Applied when `A2UIGuidelines.generationGuidelines` is unset (`undefined`).\n * Ported verbatim from the legacy `copilotkit.a2ui` defaults (OSS-248).\n */\nexport const DEFAULT_GENERATION_GUIDELINES = `\\\nGenerate A2UI v0.9 JSON.\n\n## A2UI Protocol Instructions\n\nA2UI (Agent to UI) is a protocol for rendering rich UI surfaces from agent responses.\n\nCRITICAL: You MUST call the render_a2ui tool with ALL of these arguments:\n- surfaceId: A unique ID for the surface (e.g. \"product-comparison\")\n- components: REQUIRED — the A2UI component array. NEVER omit this. Use a List with\n  children: { componentId: \"card-id\", path: \"/items\" } for repeating cards.\n- data: OPTIONAL — a JSON object written to the root of the surface data model.\n  Use for pre-filling form values or providing data for path-bound components.\n- every component must have the \"component\" field specifying the component type (e.g. \"Text\", \"Image\", \"Row\", \"Column\", \"List\", \"Button\", etc.)\n\nCOMPONENT ID RULES:\n- Every component ID must be unique within the surface.\n- A component MUST NOT reference itself as child/children. This causes a\n  circular dependency error. For example, if a component has id=\"avatar\",\n  its child must be a DIFFERENT id (e.g. \"avatar-img\"), never \"avatar\".\n- The child/children tree must be a DAG — no cycles allowed.\n\nPATH RULES FOR TEMPLATES:\nComponents inside a repeating List use RELATIVE paths (no leading slash).\nThe path is resolved relative to each array item automatically.\nIf List has children: { componentId: \"card\", path: \"/items\" } and item has key \"name\",\nuse { \"path\": \"name\" } (NO leading slash — relative to item).\nCRITICAL: Do NOT use \"/name\" (absolute) inside templates — use \"name\" (relative).\nThe List's own path (\"/items\") uses a leading slash (absolute), but all\ncomponents INSIDE the template card use paths WITHOUT leading slash.\nDo NOT use \"/items/0/name\" or \"/items/{@key}/name\" — just \"name\".\n\nDATA MODEL:\nThe \"data\" key in the tool args is a plain JSON object that initializes the surface\ndata model. Components bound to paths (e.g. \"value\": { \"path\": \"/form/name\" })\nread from and write to this data model. Examples:\n  For forms:  \"data\": { \"form\": { \"name\": \"Alice\", \"email\": \"\" } }\n  For lists:  \"data\": { \"items\": [{\"name\": \"Product A\"}, {\"name\": \"Product B\"}] }\n  For mixed:  \"data\": { \"form\": { \"query\": \"\" }, \"results\": [...] }\n\nFORMS AND TWO-WAY DATA BINDING:\nTo create editable forms, bind input components to data model paths using { \"path\": \"...\" }.\nThe client automatically writes user input back to the data model at the bound path.\nCRITICAL: Using a literal value (e.g. \"value\": \"\") makes the field READ-ONLY.\nYou MUST use { \"path\": \"...\" } to make inputs editable.\n\nAll input components use \"value\" as the binding property:\n- TextField:     \"value\": { \"path\": \"/form/fieldName\" }\n- CheckBox:      \"value\": { \"path\": \"/form/isChecked\" }\n- Slider:        \"value\": { \"path\": \"/form/sliderVal\" }\n- DateTimeInput: \"value\": { \"path\": \"/form/date\" }\n- ChoicePicker:  \"value\": { \"path\": \"/form/choices\" }\n\nTo retrieve form values when a button is clicked, include \"context\" with path references\nin the button's action. Paths are resolved to their current values at click time:\n  \"action\": { \"event\": { \"name\": \"submit\", \"context\": { \"userName\": { \"path\": \"/form/name\" } } } }\n\nTo pre-fill form values, pass initial data via the \"data\" tool argument:\n  \"data\": { \"form\": { \"name\": \"Markus\" } }\n\nFORM EXAMPLE (editable text field with pre-filled value + submit button):\n  \"components\": [\n    { \"id\": \"root\", \"component\": \"Card\", \"child\": \"form-col\" },\n    { \"id\": \"form-col\", \"component\": \"Column\", \"children\": [\"name-field\", \"submit-row\"] },\n    { \"id\": \"name-field\", \"component\": \"TextField\", \"label\": \"Name\", \"value\": { \"path\": \"/form/name\" } },\n    { \"id\": \"submit-row\", \"component\": \"Row\", \"justify\": \"end\", \"children\": [\"submit-btn\"] },\n    { \"id\": \"submit-btn\", \"component\": \"Button\", \"child\": \"btn-text\", \"variant\": \"primary\",\n      \"action\": { \"event\": { \"name\": \"submit\", \"context\": { \"userName\": { \"path\": \"/form/name\" } } } } },\n    { \"id\": \"btn-text\", \"component\": \"Text\", \"text\": \"Submit\" }\n  ],\n  \"data\": { \"form\": { \"name\": \"Markus\" } }`;\n\n/**\n * Default design guidance (visual hierarchy, layout, imagery, action format).\n * Applied when `A2UIGuidelines.designGuidelines` is unset (`undefined`).\n * Ported verbatim from the legacy `copilotkit.a2ui` defaults (OSS-248).\n */\nexport const DEFAULT_DESIGN_GUIDELINES = `\\\nCreate polished, visually appealing interfaces:\n- Always include a title heading (h2) for the surface, outside the List.\n  Wrap in a Column: [title, list] as root.\n- For card templates, create clear visual hierarchy:\n  - h3 for primary text (names, titles)\n  - h2 for featured numbers (prices, scores) — makes them stand out\n  - caption for secondary info (ratings, categories, metadata)\n  - body for descriptions\n- Use Divider between logical sections within cards.\n- Use Row with justify=\"spaceBetween\" for label-value pairs\n  (e.g. \"Rating\" on left, \"4.5/5\" on right).\n- Include images when relevant (logos, icons, product photos):\n  - Use Image component with variant=\"smallFeature\" or \"avatar\"\n  - Prefer company logos for branded products — Google favicons are reliable:\n    https://www.google.com/s2/favicons?domain=sony.com&sz=128\n    https://www.google.com/s2/favicons?domain=bose.com&sz=128\n  - For generic icons: https://placehold.co/128x128/EEE/999?text=🎧\n  - Do NOT invent Unsplash photo-IDs — they will 404. Only use real, known URLs.\n- Use horizontal List direction for side-by-side comparison cards.\n- Keep cards clean — avoid clutter. Whitespace is good.\n- Use consistent surfaceIds (lowercase, hyphenated).\n- NEVER use the same ID for a component and its child — this creates a\n  circular dependency. E.g. if id=\"avatar\", child must NOT be \"avatar\".\n- Both Row and Column support \"justify\" and \"align\".\n- Add Button for interactivity. Button needs child (Text ID) + action.\n  Action MUST use this exact nested format:\n    \"action\": { \"event\": { \"name\": \"myAction\", \"context\": { \"key\": \"value\" } } }\n  The \"event\" key holds an OBJECT with \"name\" (required) and \"context\" (optional).\n  Do NOT use a flat format like {\"event\": \"name\"} — \"event\" must be an object.\n  Use variant=\"primary\" for main action buttons, variant=\"borderless\" for links.\n- For forms: wrap fields in a Card with a Column. Place the submit button in a\n  Row with justify=\"end\". Every input MUST use path binding on the \"value\" property\n  (e.g. \"value\": { \"path\": \"/form/name\" }) to be editable. The submit button's action\n  context MUST reference the same paths to capture the user's input.\n\nUse the SAME surfaceId as the main surface. Match action names to Button action event names.`;\n\n/**\n * Prompt knobs threaded from the host through the adapter into the subagent\n * prompt. The toolkit owns this shape so a new knob is added here (and rendered\n * in `buildSubagentPrompt`) without editing any framework adapter — each adapter\n * forwards this bag verbatim.\n *\n * Per-field semantics (mirrors the legacy `a2ui_prompt` defaults):\n *   - key absent / `undefined` → the built-in `DEFAULT_*` block is used.\n *   - `\"\"` (empty string)      → that block is suppressed (no section emitted).\n *   - any other string         → replaces the default for that block.\n *\n * `compositionGuide` has no default; it is appended only when provided.\n */\nexport interface A2UIGuidelines {\n  generationGuidelines?: string;\n  designGuidelines?: string;\n  compositionGuide?: string;\n}\n\nexport interface BuildSubagentPromptInput {\n  /** Output of ``buildContextPrompt(state)``. */\n  contextPrompt: string;\n  /** Generation/design/composition prompt knobs (per-field defaults applied). */\n  guidelines?: A2UIGuidelines;\n  /** When set, instructs the subagent to edit a prior surface in place. */\n  editContext?: EditContext;\n}\n\n/**\n * Compose the full system prompt the subagent sees.\n *\n * Section order: generation guidelines → design guidelines → context + catalog\n * (from ``contextPrompt``) → composition guide → edit-existing-surface block.\n * Faithful to the legacy ``a2ui_prompt`` ordering (generation lead, design\n * header, then available components).\n *\n * Generation and design fall back per-field to ``DEFAULT_GENERATION_GUIDELINES``\n * / ``DEFAULT_DESIGN_GUIDELINES`` when unset (``undefined``); an empty string\n * suppresses the block.\n */\nexport function buildSubagentPrompt(input: BuildSubagentPromptInput): string {\n  // Per-field fallback: `undefined` → built-in default; `\"\"` → host explicitly\n  // suppressed the block (`??` treats only null/undefined as missing, so an\n  // empty string is preserved as the escape hatch).\n  const generation = input.guidelines?.generationGuidelines ?? DEFAULT_GENERATION_GUIDELINES;\n  const design = input.guidelines?.designGuidelines ?? DEFAULT_DESIGN_GUIDELINES;\n  const compositionGuide = input.guidelines?.compositionGuide;\n\n  const parts: string[] = [];\n  if (generation) parts.push(generation);\n  if (design) parts.push(`## Design Guidelines\\n${design}`);\n  if (input.contextPrompt) parts.push(input.contextPrompt);\n  if (compositionGuide) parts.push(compositionGuide);\n\n  if (input.editContext) {\n    const { surfaceId, prior, changes } = input.editContext;\n    let editBlock =\n      `## Editing an existing surface\\n` +\n      `You are editing surface '${surfaceId}'. Produce the FULL ` +\n      `updated components array and data model — not just a diff. Preserve ` +\n      `component ids that the user has not asked to change so the renderer ` +\n      `can reconcile them. Reuse the same catalogId.\\n\\n` +\n      `### Previous components\\n${JSON.stringify(prior.components, null, 2)}\\n\\n` +\n      `### Previous data\\n${JSON.stringify(prior.data, null, 2)}\\n`;\n    if (changes) {\n      editBlock += `\\n### Requested changes\\n${changes}\\n`;\n    }\n    parts.push(editBlock);\n  }\n\n  return parts.filter((p) => p && p.length > 0).join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Operations envelope\n// ---------------------------------------------------------------------------\n\nexport interface AssembleOpsInput {\n  /** ``\"create\"`` to render a new surface, ``\"update\"`` to modify a prior one. */\n  intent: \"create\" | \"update\";\n  surfaceId: string;\n  catalogId: string;\n  components: Array<Record<string, unknown>>;\n  data?: Record<string, unknown>;\n}\n\n/**\n * Produce the final A2UI v0.9 operation list for a render result.\n *\n * ``create`` emits ``[createSurface, updateComponents, updateDataModel?]``.\n * ``update`` skips ``createSurface`` so the frontend reconciles the existing\n * surface in place instead of erroring (per v0.9 spec, ``createSurface`` on\n * an existing id is invalid).\n */\nexport function assembleOps(input: AssembleOpsInput): A2UIOperation[] {\n  const ops: A2UIOperation[] = [];\n  if (input.intent !== \"update\") {\n    ops.push(createSurface(input.surfaceId, input.catalogId));\n  }\n  ops.push(updateComponents(input.surfaceId, input.components));\n  if (input.data && Object.keys(input.data).length > 0) {\n    ops.push(updateDataModel(input.surfaceId, input.data));\n  }\n  return ops;\n}\n\n/**\n * Wrap a list of A2UI operations as the JSON envelope the A2UI middleware\n * looks for in tool results.\n */\nexport function wrapAsOperationsEnvelope(ops: A2UIOperation[]): string {\n  return JSON.stringify({ [A2UI_OPERATIONS_KEY]: ops });\n}\n\n/**\n * Wrap an error as the JSON string a subagent tool returns when it can't\n * produce a surface. Keeps the error shape consistent across frameworks.\n */\nexport function wrapErrorEnvelope(message: string): string {\n  return JSON.stringify({ error: message });\n}\n\n// ---------------------------------------------------------------------------\n// Subagent-tool defaults (shared so every framework adapter advertises the\n// same planner-facing surface and behaviour)\n// ---------------------------------------------------------------------------\n\n/** Surface id used when the subagent omits ``surfaceId`` on a create. */\nexport const DEFAULT_SURFACE_ID = \"dynamic-surface\";\n\n/** Default name the outer A2UI tool is advertised under to the main planner. */\nexport const GENERATE_A2UI_TOOL_NAME = \"generate_a2ui\";\n\n/** Default description shown to the main agent's planner. */\nexport const GENERATE_A2UI_TOOL_DESCRIPTION =\n  \"Generate or update a dynamic A2UI surface based on the conversation. \" +\n  \"A secondary LLM designs the UI components and data. \" +\n  \"Use intent='create' (default) when the user requests new visual content \" +\n  \"(cards, forms, lists, dashboards, comparisons, etc.). \" +\n  \"Use intent='update' with target_surface_id to modify a surface you \" +\n  \"previously rendered (e.g. 'change the second card's price', \" +\n  \"'add a Buy button', 'use red instead of blue').\";\n\n/** Planner-facing descriptions for the outer tool's three arguments. */\nexport const GENERATE_A2UI_ARG_DESCRIPTIONS = {\n  intent:\n    \"'create' to render a new surface; 'update' to modify a surface previously rendered in this conversation. Defaults to 'create'.\",\n  target_surface_id: \"Required when intent='update'. The surface id of the prior render to modify.\",\n  changes: \"Optional natural-language description of the changes to apply when intent='update'.\",\n} as const;\n\n// ---------------------------------------------------------------------------\n// Shared A2UI tool-factory params (OSS-248)\n//\n// One params shape, owned by the toolkit, consumed identically by every\n// framework adapter. A framework's factory is always\n// `getA2UITools(params: A2UIToolParams<TModel>)` — only the body (tool\n// decorator, runtime/state accessor, model bind+invoke) differs per framework.\n//\n// `model` is the single framework-specific field, so the type is generic over\n// it. Adding a new knob = add a field here (+ apply its default in\n// `resolveA2UIToolParams`) — NO adapter signature ever changes, and a brand-new\n// framework adapter gets the knob for free on day one.\n// ---------------------------------------------------------------------------\n\nexport interface A2UIToolParams<TModel = unknown> {\n  /** Chat model the subagent invokes for structured A2UI output. The one\n   *  framework-specific field — typed per framework via the generic. */\n  model: TModel;\n  /** Generation/design/composition prompt knobs (per-field defaults applied). */\n  guidelines?: A2UIGuidelines;\n  /** Surface id used when the subagent omits `surfaceId`. */\n  defaultSurfaceId?: string;\n  /** Catalog id assigned to every new surface this factory creates — the\n   *  subagent never picks the catalog. Falls back to the basic v0.9 catalog. */\n  defaultCatalogId?: string;\n  /** Name advertised to the main agent's planner. */\n  toolName?: string;\n  /** Description shown to the main agent's planner. */\n  toolDescription?: string;\n  /** Inline catalog enabling catalog-aware recovery. Pass the SAME catalog the\n   *  host gives the middleware so retry decision + paint gate agree. */\n  catalog?: A2UIValidationCatalog;\n  /** Recovery loop config: attempt cap, retry-UI threshold, debug exposure. */\n  recovery?: A2UIRecoveryConfig;\n  /** Per-attempt hook for recovery status / dev logs (non-disruptive). */\n  onA2UIAttempt?: (record: A2UIAttemptRecord) => void;\n}\n\n/** `A2UIToolParams` with every optional field resolved to its effective value.\n *  Returned by `resolveA2UIToolParams` so adapters never re-implement defaults. */\nexport interface ResolvedA2UIToolParams<TModel = unknown> {\n  model: TModel;\n  guidelines?: A2UIGuidelines;\n  defaultSurfaceId: string;\n  defaultCatalogId: string;\n  toolName: string;\n  toolDescription: string;\n  catalog?: A2UIValidationCatalog;\n  recovery?: A2UIRecoveryConfig;\n  onA2UIAttempt?: (record: A2UIAttemptRecord) => void;\n}\n\n/**\n * Normalize an `A2UIToolParams` into a `ResolvedA2UIToolParams`, filling the\n * canonical defaults so each framework adapter stops re-implementing\n * `toolName || DEFAULT` / `catalogId || BASIC` lines.\n *\n * Uses `||` (not `??`) so an accidental empty-string override from a caller\n * falls back to the canonical default rather than advertising a nameless /\n * empty-description tool or emitting a blank surface/catalog id.\n */\nexport function resolveA2UIToolParams<TModel>(\n  params: A2UIToolParams<TModel>,\n): ResolvedA2UIToolParams<TModel> {\n  return {\n    model: params.model,\n    guidelines: params.guidelines,\n    defaultSurfaceId: params.defaultSurfaceId || DEFAULT_SURFACE_ID,\n    defaultCatalogId: params.defaultCatalogId || BASIC_CATALOG_ID,\n    toolName: params.toolName || GENERATE_A2UI_TOOL_NAME,\n    toolDescription: params.toolDescription || GENERATE_A2UI_TOOL_DESCRIPTION,\n    catalog: params.catalog,\n    recovery: params.recovery,\n    onA2UIAttempt: params.onA2UIAttempt,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// High-level orchestration\n//\n// These two functions hold the entire create/update decision + prompt prep +\n// result-assembly logic so every framework adapter is reduced to pure glue\n// (tool decorator, state access, model bind+invoke, tool-call read).\n// ---------------------------------------------------------------------------\n\nexport interface PrepareA2UIRequestInput {\n  /** Raw ``intent`` arg from the planner (defaults to ``\"create\"``). */\n  intent?: string;\n  /** Raw ``target_surface_id`` arg from the planner. */\n  targetSurfaceId?: string;\n  /** Raw ``changes`` arg from the planner. */\n  changes?: string;\n  /** Conversation history with the current (unbalanced) tool call stripped. */\n  messages: Array<any>;\n  /** The agent's run state (read for context + catalog via buildContextPrompt). */\n  state: Record<string, unknown>;\n  /**\n   * Generation/design/composition prompt knobs, forwarded verbatim to\n   * ``buildSubagentPrompt``. The toolkit owns the shape so adapters never need\n   * editing when a knob is added.\n   */\n  guidelines?: A2UIGuidelines;\n}\n\nexport interface PreparedA2UIRequest {\n  /** System prompt to feed the subagent. Empty string when ``error`` is set. */\n  prompt: string;\n  /** Whether this is an in-place edit of a prior surface. */\n  isUpdate: boolean;\n  /** The reconstructed prior surface, when editing. */\n  prior?: PriorSurface;\n  /** Set when the request is invalid (e.g. update with no matching surface). */\n  error?: string;\n}\n\n/**\n * Resolve the create/update decision, locate any prior surface, and build the\n * subagent system prompt. Returns ``error`` instead of a prompt when the\n * request is invalid (update referencing a surface not in history).\n */\nexport function prepareA2UIRequest(input: PrepareA2UIRequestInput): PreparedA2UIRequest {\n  const intent = input.intent ?? \"create\";\n  const isUpdate = intent === \"update\" && Boolean(input.targetSurfaceId);\n\n  const prior = isUpdate ? findPriorSurface(input.messages, input.targetSurfaceId!) : undefined;\n\n  if (isUpdate && !prior) {\n    return {\n      prompt: \"\",\n      isUpdate,\n      error:\n        `intent='update' requested target_surface_id='${input.targetSurfaceId}' ` +\n        `but no prior render of that surface was found in conversation history`,\n    };\n  }\n\n  const prompt = buildSubagentPrompt({\n    contextPrompt: buildContextPrompt(input.state),\n    guidelines: input.guidelines,\n    editContext: prior\n      ? { surfaceId: input.targetSurfaceId!, prior, changes: input.changes }\n      : undefined,\n  });\n\n  return { prompt, isUpdate, prior };\n}\n\nexport interface BuildA2UIEnvelopeInput {\n  /** The subagent's ``render_a2ui`` structured-output args. */\n  args: Record<string, unknown>;\n  /** From ``prepareA2UIRequest``. */\n  isUpdate: boolean;\n  /** The planner's ``target_surface_id`` (used as the surface id on update). */\n  targetSurfaceId?: string;\n  /** The prior surface from ``prepareA2UIRequest`` (supplies the catalog id on update). */\n  prior?: PriorSurface;\n  /** Surface id used when the subagent omits one on create. */\n  defaultSurfaceId?: string;\n  /** Catalog id used when there's no prior surface to inherit one from. */\n  defaultCatalogId?: string;\n}\n\n/**\n * Turn the subagent's structured output into the final operations envelope.\n *\n * Catalog ownership stays with the host: the subagent never picks a catalog,\n * so the id comes from the prior surface (update) or the configured default\n * (create) — never from the model's args.\n */\nexport function buildA2UIEnvelope(input: BuildA2UIEnvelopeInput): string {\n  // Treat empty-string defaults as unset. `??` alone would propagate \"\" into\n  // the emitted createSurface / updateComponents ops and surface as\n  // \"Catalog not found: \" / a blank surface id at render time — hiding the\n  // real cause (host misconfiguration). The middleware streaming path uses\n  // the same guard for symmetry.\n  const safeDefaultSurfaceId =\n    input.defaultSurfaceId && input.defaultSurfaceId.length > 0\n      ? input.defaultSurfaceId\n      : DEFAULT_SURFACE_ID;\n  const safeDefaultCatalogId =\n    input.defaultCatalogId && input.defaultCatalogId.length > 0\n      ? input.defaultCatalogId\n      : BASIC_CATALOG_ID;\n\n  // Narrow ``args.surfaceId`` to a non-empty string before using it — the\n  // model's output is untrusted and could send a number / object / null.\n  const argSurfaceId =\n    typeof input.args.surfaceId === \"string\" && input.args.surfaceId.length > 0\n      ? input.args.surfaceId\n      : \"\";\n  const surfaceId = input.isUpdate\n    ? input.targetSurfaceId || safeDefaultSurfaceId\n    : argSurfaceId || safeDefaultSurfaceId;\n\n  const catalogId = input.prior?.catalogId || safeDefaultCatalogId;\n\n  const rawComponents = input.args.components;\n  const components: Array<Record<string, unknown>> = Array.isArray(rawComponents)\n    ? (rawComponents as Array<Record<string, unknown>>)\n    : [];\n  const rawData = input.args.data;\n  const data: Record<string, unknown> =\n    rawData && typeof rawData === \"object\" && !Array.isArray(rawData)\n      ? (rawData as Record<string, unknown>)\n      : {};\n\n  const ops = assembleOps({\n    intent: input.isUpdate ? \"update\" : \"create\",\n    surfaceId,\n    catalogId,\n    components,\n    data,\n  });\n\n  return wrapAsOperationsEnvelope(ops);\n}\n\n// ---------------------------------------------------------------------------\n// Error-recovery loop (OSS-162) — semantic validation + validate→retry loop,\n// shared so the middleware (paint gate) and adapters (retry driver) agree.\n// ---------------------------------------------------------------------------\nexport * from \"./validate\";\nexport * from \"./recovery\";\n"],"mappings":";;AA+DA,SAAS,qBAAqB,MAAc,MAAwB;CAClE,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,QAAQ,MAAM,EAAE,SAAS,EAAE;CAC5D,IAAI,SAAkB;AACtB,MAAK,MAAM,OAAO,UAAU;AAC1B,MAAI,UAAU,QAAQ,OAAO,WAAW,SAAU,QAAO;AACzD,MAAI,MAAM,QAAQ,OAAO,EAAE;GACzB,MAAM,MAAM,OAAO,IAAI;AACvB,OAAI,CAAC,OAAO,UAAU,IAAI,IAAI,MAAM,KAAK,OAAO,OAAO,OAAQ,QAAO;AACtE,YAAS,OAAO;SACX;AACL,OAAI,EAAE,OAAQ,QAAqC,QAAO;AAC1D,YAAU,OAAmC;;;AAGjD,QAAO;;;AAIT,SAAS,SAAS,GAA0C;AAC1D,QAAO,OAAO,MAAM,YAAY,MAAM,QAAQ,CAAC,MAAM,QAAQ,EAAE;;;;;;;;;;;AAYjE,SAAgB,uBAAuB,OAA8C;CACnF,MAAM,EAAE,YAAY,MAAM,YAAY;CACtC,MAAM,mBAAmB,MAAM,oBAAoB;CACnD,MAAM,SAAgC,EAAE;AAKxC,KAAI,CAAC,MAAM,QAAQ,WAAW,IAAI,WAAW,WAAW,EACtD,QAAO;EACL,OAAO;EACP,QAAQ,CAAC;GAAE,MAAM;GAAoB,MAAM;GAAc,SAAS;GAA6C,CAAC;EACjH;CAGH,MAAM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