@dudousxd/nestjs-agent-core 0.41.0 → 0.42.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/genui/index.ts","../../src/genui/schema.ts","../../src/genui/catalog.ts","../../src/genui/tree.ts","../../src/genui/text.ts","../../src/genui/capabilities.ts","../../src/genui/tools.ts","../../src/genui/builtins.ts","../../src/genui/registry.ts"],"sourcesContent":["/**\n * `@dudousxd/nestjs-agent-core/genui` — the generative-UI catalog: component definitions (Standard\n * Schema or JSON Schema props), validation, model-facing catalog text, plain-text fallbacks and the\n * tools that push `ui` frames. Isomorphic: this entry imports nothing server-only, so the same\n * catalog file serves the NestJS app and the browser. Builtin definitions live at\n * `@dudousxd/nestjs-agent-core/genui/builtins`.\n */\nexport {\n type Catalog,\n type CatalogOptions,\n COMPONENT_NAME,\n type ComponentDefinition,\n defineCatalog,\n defineComponent,\n toolNameFor,\n toSnakeCase,\n} from './catalog.js';\nexport {\n type AjvLike,\n ajvValidator,\n builtinJsonSchemaValidator,\n formatIssues,\n type GenuiIssue,\n type GenuiValidation,\n isStandardSchema,\n type JsonSchema,\n type JsonSchemaValidator,\n type PropsSchema,\n toJsonSchema,\n validateProps,\n validatePropsSync,\n} from './schema.js';\nexport {\n type CatalogTextOptions,\n catalogToModelText,\n componentToText,\n fillTemplate,\n getPath,\n summarizeSchema,\n treeToText,\n} from './text.js';\nexport {\n GENUI_SHOW_TOOL,\n type GenuiCatalogScope,\n type GenuiTool,\n type GenuiToolOutput,\n type GenuiToolsOptions,\n genuiTools,\n jsonStandardSchema,\n type ResolveGenuiCatalog,\n showToolJsonSchema,\n} from './tools.js';\nexport {\n type FlatSpec,\n GENUI_TREE_COMPONENT,\n type GenuiElement,\n type GenuiTreeProps,\n type TreeLimits,\n treeJsonSchema,\n treeToFlatSpec,\n validateTree,\n} from './tree.js';\n\nexport {\n type UiCapabilities,\n type PreparedUiEmission,\n negotiateCatalog,\n prepareUiEmission,\n validateUiCapabilities,\n} from './capabilities.js';\n\nexport {\n type ComponentPresentation,\n type ComponentFactory,\n type ComponentRenderer,\n type ComponentManifest,\n type ComponentRegistry,\n type TableCell,\n type TableProps,\n type ChartProps,\n createComponent,\n createComponentRegistry,\n snapshotComponentPresentation,\n table,\n chart,\n} from './registry.js';\nexport { validatePresentationBatch } from './registry.js';\n","import type { StandardJSONSchemaV1, StandardSchemaV1 } from '@standard-schema/spec';\n\n/** A JSON Schema document (draft-07 / 2020-12 subset). Plain data, so a catalog can be stored and shipped. */\nexport type JsonSchema = Record<string, unknown>;\n\n/** One problem with a value, addressed by its path from the root of the value. */\nexport interface GenuiIssue {\n path: (string | number)[];\n message: string;\n}\n\nexport type GenuiValidation<T = unknown> =\n | { ok: true; value: T }\n | { ok: false; issues: GenuiIssue[] };\n\n/**\n * Validates a value against a JSON Schema. The package ships {@link builtinJsonSchemaValidator} (a\n * dependency-free subset that covers what component props use); pass {@link ajvValidator} to a\n * catalog for full JSON Schema.\n */\nexport interface JsonSchemaValidator {\n validate(schema: JsonSchema, value: unknown): GenuiIssue[];\n}\n\n/** A component's props schema: any Standard Schema (Zod, Valibot, ArkType) or a JSON Schema object. */\nexport type PropsSchema = StandardSchemaV1 | JsonSchema;\n\nexport function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n '~standard' in schema &&\n typeof (schema as StandardSchemaV1)['~standard']?.validate === 'function'\n );\n}\n\n/**\n * The JSON Schema a props schema presents to a model: the schema itself for a JSON Schema, the\n * Standard JSON Schema converter's output for a Standard Schema that has one (Zod 4, Valibot,\n * ArkType). `undefined` when neither is available (e.g. Zod 3) — the model then gets the\n * component's description only.\n */\nexport function toJsonSchema(schema: PropsSchema): JsonSchema | undefined {\n if (!isStandardSchema(schema)) {\n return schema;\n }\n const standard = schema['~standard'] as StandardSchemaV1['~standard'] &\n Partial<StandardJSONSchemaV1['~standard']>;\n const converter = standard.jsonSchema;\n if (converter === undefined || typeof converter.input !== 'function') {\n return undefined;\n }\n try {\n return converter.input({ target: 'draft-07' });\n } catch {\n return undefined;\n }\n}\n\n/** Validate against either kind of props schema. A Standard Schema's own (possibly transformed) output wins. */\nexport async function validateProps(\n schema: PropsSchema,\n value: unknown,\n validator: JsonSchemaValidator,\n): Promise<GenuiValidation> {\n if (isStandardSchema(schema)) {\n const result = await schema['~standard'].validate(value);\n if (result.issues !== undefined) {\n return { ok: false, issues: toGenuiIssues(result.issues) };\n }\n return { ok: true, value: result.value };\n }\n const issues = validator.validate(schema, value);\n return issues.length > 0 ? { ok: false, issues } : { ok: true, value };\n}\n\n/**\n * {@link validateProps} without waiting: the verdict when it is available synchronously (always\n * for JSON Schema, and for every Standard Schema whose `validate` does not return a promise — Zod,\n * Valibot and ArkType all answer synchronously for synchronous schemas), `undefined` otherwise. What\n * a renderer uses to decide on its first paint instead of flashing a placeholder.\n */\nexport function validatePropsSync(\n schema: PropsSchema,\n value: unknown,\n validator: JsonSchemaValidator,\n): GenuiValidation | undefined {\n if (!isStandardSchema(schema)) {\n const issues = validator.validate(schema, value);\n return issues.length > 0 ? { ok: false, issues } : { ok: true, value };\n }\n const result = schema['~standard'].validate(value);\n if (result instanceof Promise) {\n result.catch(() => undefined);\n return undefined;\n }\n return result.issues !== undefined\n ? { ok: false, issues: toGenuiIssues(result.issues) }\n : { ok: true, value: result.value };\n}\n\nfunction toGenuiIssues(issues: readonly StandardSchemaV1.Issue[]): GenuiIssue[] {\n return issues.map((issue) => ({\n path: (issue.path ?? []).map((segment) =>\n typeof segment === 'object' && segment !== null && 'key' in segment\n ? (segment.key as string | number)\n : (segment as string | number),\n ),\n message: issue.message,\n }));\n}\n\n/** `a.b[0].c: message; …` — what a model is handed back when its props were refused. */\nexport function formatIssues(issues: readonly GenuiIssue[]): string {\n return issues\n .map(\n (issue) => `${issue.path.length > 0 ? formatPath(issue.path) : '(root)'}: ${issue.message}`,\n )\n .join('; ');\n}\n\nfunction formatPath(path: readonly (string | number)[]): string {\n return path\n .map((segment, index) =>\n typeof segment === 'number' ? `[${segment}]` : index === 0 ? segment : `.${segment}`,\n )\n .join('');\n}\n\n/**\n * Structural type of an Ajv instance, so the package never imports Ajv: `new Ajv({ allErrors: true })`\n * satisfies it.\n */\nexport interface AjvLike {\n compile(schema: object): ((data: unknown) => boolean | Promise<unknown>) & {\n errors?: { instancePath?: string; message?: string }[] | null;\n };\n}\n\n/**\n * Full JSON Schema validation through the app's own Ajv instance. Compiled validators are cached\n * per schema object.\n */\nexport function ajvValidator(ajv: AjvLike): JsonSchemaValidator {\n const compiled = new WeakMap<object, ReturnType<AjvLike['compile']>>();\n return {\n validate(schema, value) {\n let fn = compiled.get(schema);\n if (fn === undefined) {\n fn = ajv.compile(schema);\n compiled.set(schema, fn);\n }\n if (fn(value) === true) {\n return [];\n }\n return (fn.errors ?? []).map((error) => ({\n path: (error.instancePath ?? '')\n .split('/')\n .filter((segment) => segment.length > 0)\n .map((segment) => {\n const decoded = segment.replace(/~1/g, '/').replace(/~0/g, '~');\n return /^\\d+$/.test(decoded) ? Number(decoded) : decoded;\n }),\n message: error.message ?? 'is invalid',\n }));\n },\n };\n}\n\n/**\n * A dependency-free JSON Schema validator for the keywords component props actually use: `type`\n * (incl. `integer`, `null`, type arrays), `enum`, `const`, `properties`, `required`,\n * `additionalProperties`, `items`, `minItems`/`maxItems`, `minLength`/`maxLength`/`pattern`,\n * `minimum`/`maximum`, `anyOf`/`oneOf`/`allOf`, `not`, and local `$ref`s (`#`, `#/$defs/…`,\n * `#/definitions/…`). Unknown keywords (e.g. `format`) are ignored. Use {@link ajvValidator} when\n * you need the rest.\n */\nexport const builtinJsonSchemaValidator: JsonSchemaValidator = {\n validate(schema, value) {\n const issues: GenuiIssue[] = [];\n check(schema, value, [], schema, issues, 0);\n return issues;\n },\n};\n\nconst MAX_DEPTH = 64;\n\nfunction typeOf(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n return typeof value;\n}\n\nfunction matchesType(type: string, value: unknown): boolean {\n switch (type) {\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'number':\n return typeof value === 'number' && Number.isFinite(value);\n case 'object':\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n default:\n return typeOf(value) === type;\n }\n}\n\nfunction resolveRef(root: JsonSchema, ref: string): JsonSchema | undefined {\n if (ref === '#') return root;\n if (!ref.startsWith('#/')) return undefined;\n let current: unknown = root;\n for (const raw of ref.slice(2).split('/')) {\n const key = raw.replace(/~1/g, '/').replace(/~0/g, '~');\n if (typeof current !== 'object' || current === null) return undefined;\n current = (current as Record<string, unknown>)[key];\n }\n return typeof current === 'object' && current !== null ? (current as JsonSchema) : undefined;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((key) =>\n deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n );\n}\n\nfunction check(\n schema: unknown,\n value: unknown,\n path: (string | number)[],\n root: JsonSchema,\n issues: GenuiIssue[],\n depth: number,\n): void {\n if (schema === true || schema === undefined) return;\n if (schema === false) {\n issues.push({ path, message: 'is not allowed' });\n return;\n }\n if (typeof schema !== 'object' || schema === null) return;\n if (depth > MAX_DEPTH) {\n issues.push({ path, message: 'is nested too deeply' });\n return;\n }\n const s = schema as Record<string, unknown>;\n\n if (typeof s.$ref === 'string') {\n const target = resolveRef(root, s.$ref);\n if (target === undefined) {\n issues.push({ path, message: `references unknown schema ${s.$ref}` });\n return;\n }\n check(target, value, path, root, issues, depth + 1);\n }\n\n if (s.type !== undefined) {\n const types = Array.isArray(s.type) ? (s.type as string[]) : [s.type as string];\n if (!types.some((type) => matchesType(type, value))) {\n issues.push({ path, message: `must be ${types.join(' or ')}` });\n return;\n }\n }\n if (Array.isArray(s.enum) && !s.enum.some((option) => deepEqual(option, value))) {\n issues.push({\n path,\n message: `must be one of ${s.enum.map((option) => JSON.stringify(option)).join(', ')}`,\n });\n }\n if ('const' in s && !deepEqual(s.const, value)) {\n issues.push({ path, message: `must be ${JSON.stringify(s.const)}` });\n }\n\n if (typeof value === 'string') {\n if (typeof s.minLength === 'number' && value.length < s.minLength) {\n issues.push({ path, message: `must be at least ${s.minLength} characters` });\n }\n if (typeof s.maxLength === 'number' && value.length > s.maxLength) {\n issues.push({ path, message: `must be at most ${s.maxLength} characters` });\n }\n if (typeof s.pattern === 'string') {\n let pattern: RegExp | undefined;\n try {\n pattern = new RegExp(s.pattern, 'u');\n } catch {\n pattern = undefined;\n }\n if (pattern !== undefined && !pattern.test(value)) {\n issues.push({ path, message: `must match ${s.pattern}` });\n }\n }\n }\n if (typeof value === 'number') {\n if (typeof s.minimum === 'number' && value < s.minimum) {\n issues.push({ path, message: `must be >= ${s.minimum}` });\n }\n if (typeof s.maximum === 'number' && value > s.maximum) {\n issues.push({ path, message: `must be <= ${s.maximum}` });\n }\n }\n\n if (Array.isArray(value)) {\n if (typeof s.minItems === 'number' && value.length < s.minItems) {\n issues.push({ path, message: `must have at least ${s.minItems} items` });\n }\n if (typeof s.maxItems === 'number' && value.length > s.maxItems) {\n issues.push({ path, message: `must have at most ${s.maxItems} items` });\n }\n if (s.items !== undefined && !Array.isArray(s.items)) {\n value.forEach((item, index) => {\n check(s.items, item, [...path, index], root, issues, depth + 1);\n });\n }\n }\n\n if (matchesType('object', value)) {\n const record = value as Record<string, unknown>;\n const properties =\n typeof s.properties === 'object' && s.properties !== null\n ? (s.properties as Record<string, unknown>)\n : {};\n if (Array.isArray(s.required)) {\n for (const key of s.required as string[]) {\n if (record[key] === undefined) {\n issues.push({ path: [...path, key], message: 'is required' });\n }\n }\n }\n for (const [key, entry] of Object.entries(record)) {\n if (key in properties) {\n if (entry !== undefined) {\n check(properties[key], entry, [...path, key], root, issues, depth + 1);\n }\n } else if (s.additionalProperties === false) {\n issues.push({ path: [...path, key], message: 'is not a known property' });\n } else if (typeof s.additionalProperties === 'object' && s.additionalProperties !== null) {\n check(s.additionalProperties, entry, [...path, key], root, issues, depth + 1);\n }\n }\n }\n\n if (Array.isArray(s.allOf)) {\n for (const sub of s.allOf) check(sub, value, path, root, issues, depth + 1);\n }\n if (Array.isArray(s.anyOf) || Array.isArray(s.oneOf)) {\n const options = (Array.isArray(s.anyOf) ? s.anyOf : s.oneOf) as unknown[];\n const passing = options.filter((sub) => {\n const nested: GenuiIssue[] = [];\n check(sub, value, path, root, nested, depth + 1);\n return nested.length === 0;\n }).length;\n if (Array.isArray(s.anyOf) ? passing === 0 : passing !== 1) {\n issues.push({\n path,\n message: Array.isArray(s.anyOf)\n ? 'does not match any allowed shape'\n : 'must match exactly one allowed shape',\n });\n }\n }\n if (s.not !== undefined) {\n const nested: GenuiIssue[] = [];\n check(s.not, value, path, root, nested, depth + 1);\n if (nested.length === 0) {\n issues.push({ path, message: 'matches a shape that is not allowed' });\n }\n }\n}\n","import {\n type GenuiValidation,\n type JsonSchema,\n type JsonSchemaValidator,\n type PropsSchema,\n builtinJsonSchemaValidator,\n toJsonSchema,\n validateProps,\n validatePropsSync,\n} from './schema.js';\n\n/**\n * One component a server may push into a conversation. Data only — how it LOOKS is each app's own\n * renderer, looked up by {@link name}. The same definition serves the model (description + props\n * schema), the server (validation), text-only channels ({@link fallbackText}) and the client\n * (validation before rendering).\n */\nexport interface ComponentDefinition<P = Record<string, unknown>> {\n /** Registry key, e.g. `DataTable`. What a `ui` frame's `component` names. */\n name: string;\n /** Human label: \"Data table\". */\n title: string;\n /** Shown to the model: what the component is for and when to use it. */\n description: string;\n /** The props schema: a Standard Schema (Zod, Valibot, ArkType) or a JSON Schema object. */\n props: PropsSchema;\n /** Portable normalized props schema. Required when input transformations are not idempotent. */\n outputProps?: PropsSchema;\n /**\n * The component takes nested elements (a layout: `Stack`, `Card`). Only meaningful in tree mode,\n * where a node's `children` are validated against the catalog too.\n */\n children?: boolean;\n /**\n * Plain text / Slack mrkdwn rendering of these props, for a channel that cannot draw the\n * component. Absent → {@link componentToText} prints the props as JSON.\n */\n fallbackText?: (props: P) => string;\n /**\n * Pushed by the server (e.g. an approval card), never offered to the model. Excluded from\n * {@link catalogToModelText} and from the tool factories.\n */\n internal?: boolean;\n /**\n * Schema version of {@link props}. Stamped on every `ui` frame the component is pushed with, so a\n * client can keep rendering messages persisted under an older shape.\n */\n version?: number;\n}\n\n/** Component names: an identifier a registry key, a tool name and a snake_case slug can all be derived from. */\nexport const COMPONENT_NAME = /^[A-Za-z][A-Za-z0-9]{0,63}$/;\n\n/** Declare a component. Validates the name and returns the definition unchanged (typed). */\nexport function defineComponent<P = Record<string, unknown>>(\n definition: ComponentDefinition<P>,\n): ComponentDefinition<P> {\n if (!COMPONENT_NAME.test(definition.name)) {\n throw new Error(\n `genui: component name \"${definition.name}\" must be letters and digits, starting with a letter (e.g. DataTable)`,\n );\n }\n if (\n definition.version !== undefined &&\n (!Number.isSafeInteger(definition.version) || definition.version <= 0)\n )\n throw new RangeError('genui: component version must be a positive safe integer');\n if (definition.fallbackText !== undefined && typeof definition.fallbackText !== 'function')\n throw new TypeError('genui: fallbackText must be a function');\n return definition;\n}\n\nexport interface CatalogOptions {\n /** How JSON Schema props are checked. Default: {@link builtinJsonSchemaValidator}; pass `ajvValidator(new Ajv())` for full JSON Schema. */\n jsonSchemaValidator?: JsonSchemaValidator;\n}\n\n/** An immutable set of component definitions, looked up by name. */\nexport interface Catalog {\n readonly components: readonly ComponentDefinition<any>[];\n readonly validator: JsonSchemaValidator;\n get(name: string): ComponentDefinition<any> | undefined;\n has(name: string): boolean;\n /** The components a model may be offered (every non-`internal` one). */\n modelComponents(): ComponentDefinition<any>[];\n /** Validate `props` for `component`. An unknown component is a validation failure, not a throw. */\n validate(component: string, props: unknown): Promise<GenuiValidation<Record<string, unknown>>>;\n /**\n * {@link validate} without waiting — `undefined` only when the component's Standard Schema\n * validates asynchronously. An unknown component is a failure, as in `validate`.\n */\n validateSync(\n component: string,\n props: unknown,\n ): GenuiValidation<Record<string, unknown>> | undefined;\n /** The component's props as JSON Schema, when it can be derived (see {@link toJsonSchema}). */\n jsonSchemaFor(component: string): JsonSchema | undefined;\n /** A new catalog with these components added (a later definition replaces an earlier one of the same name). */\n extend(components: readonly ComponentDefinition<any>[]): Catalog;\n}\n\n/**\n * Collect component definitions into a {@link Catalog}. Names must be unique; to override a\n * definition (e.g. a builtin), use {@link Catalog.extend}.\n */\nexport function defineCatalog(\n components: readonly ComponentDefinition<any>[],\n options: CatalogOptions = {},\n): Catalog {\n const byName = new Map<string, ComponentDefinition<any>>();\n for (const component of components) {\n defineComponent(component);\n if (byName.has(component.name)) {\n throw new Error(`genui: component \"${component.name}\" is defined twice in one catalog`);\n }\n byName.set(component.name, component);\n }\n return buildCatalog(byName, options.jsonSchemaValidator ?? builtinJsonSchemaValidator);\n}\n\nfunction buildCatalog(\n byName: Map<string, ComponentDefinition<any>>,\n validator: JsonSchemaValidator,\n): Catalog {\n const list = Object.freeze([...byName.values()]);\n return {\n components: list,\n validator,\n get: (name) => byName.get(name),\n has: (name) => byName.has(name),\n modelComponents: () => list.filter((component) => component.internal !== true),\n async validate(component, props) {\n const definition = byName.get(component);\n if (definition === undefined) {\n return {\n ok: false,\n issues: [{ path: [], message: `unknown component \"${component}\"` }],\n };\n }\n const result = await validateProps(\n definition.outputProps ?? definition.props,\n props,\n validator,\n );\n return result as GenuiValidation<Record<string, unknown>>;\n },\n validateSync(component, props) {\n const definition = byName.get(component);\n if (definition === undefined) {\n return {\n ok: false,\n issues: [{ path: [], message: `unknown component \"${component}\"` }],\n };\n }\n return validatePropsSync(definition.outputProps ?? definition.props, props, validator) as\n | GenuiValidation<Record<string, unknown>>\n | undefined;\n },\n jsonSchemaFor(component) {\n const definition = byName.get(component);\n return definition === undefined\n ? undefined\n : toJsonSchema(definition.outputProps ?? definition.props);\n },\n extend(more) {\n const next = new Map(byName);\n for (const component of more) {\n defineComponent(component);\n next.set(component.name, component);\n }\n return buildCatalog(next, validator);\n },\n };\n}\n\n/** `DataTable` → `data_table`, `KPICards` → `kpi_cards`. */\nexport function toSnakeCase(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')\n .replace(/[^a-zA-Z0-9]+/g, '_')\n .toLowerCase();\n}\n\n/** The per-component tool name: `ui__show_data_table` with the default prefix. */\nexport function toolNameFor(component: string, prefix = 'ui__show_'): string {\n return `${prefix}${toSnakeCase(component)}`;\n}\n","import type { Catalog } from './catalog.js';\nimport { type GenuiIssue, type GenuiValidation, type JsonSchema, validateProps } from './schema.js';\n\n/**\n * One node of a composed UI: a catalog component, its props, and — for components declared with\n * `children: true` — nested nodes. The shape json-render calls a \"nested element\", so a tree\n * converts to a json-render flat spec with {@link treeToFlatSpec}.\n */\nexport interface GenuiElement {\n type: string;\n props: Record<string, unknown>;\n children?: GenuiElement[];\n}\n\n/**\n * The `ui` frame component a tree-mode tool pushes: `{ component: GENUI_TREE_COMPONENT, props: {\n * root } }`. Not a valid component name, so it can never collide with a catalog entry.\n */\nexport const GENUI_TREE_COMPONENT = 'genui:tree';\n\n/** Props of a {@link GENUI_TREE_COMPONENT} frame. */\nexport interface GenuiTreeProps {\n root: GenuiElement;\n}\n\nexport interface TreeLimits {\n /** Deepest nesting accepted. Default 12. */\n maxDepth?: number;\n /** Most nodes accepted in one tree. Default 200. */\n maxNodes?: number;\n}\n\n/**\n * Validate a model-composed tree against the catalog: every node's `type` must be a model-facing\n * component, its props must pass that component's schema, and only components declared with\n * `children: true` may have children. Returns the tree with each node's props as its schema\n * produced them (defaults applied by a Standard Schema, for instance).\n *\n * Lenient about one thing models get wrong: a `children` array sent as a JSON STRING (sometimes\n * with a stray trailing `}`) is parsed back into the array the model plainly meant.\n */\nexport async function validateTree(\n catalog: Catalog,\n tree: unknown,\n limits: TreeLimits = {},\n phase: 'input' | 'output' = 'output',\n): Promise<GenuiValidation<GenuiElement>> {\n const maxDepth = limits.maxDepth ?? 12;\n const maxNodes = limits.maxNodes ?? 200;\n const issues: GenuiIssue[] = [];\n let nodes = 0;\n\n const visit = async (\n node: unknown,\n path: (string | number)[],\n depth: number,\n ): Promise<GenuiElement | undefined> => {\n nodes += 1;\n if (nodes > maxNodes) {\n if (nodes === maxNodes + 1) {\n issues.push({ path, message: `the tree has more than ${maxNodes} elements` });\n }\n return undefined;\n }\n if (depth > maxDepth) {\n issues.push({ path, message: `the tree is nested deeper than ${maxDepth} levels` });\n return undefined;\n }\n if (typeof node !== 'object' || node === null || Array.isArray(node)) {\n issues.push({ path, message: 'must be an element object { type, props, children? }' });\n return undefined;\n }\n const element = node as Record<string, unknown>;\n if (typeof element.type !== 'string') {\n issues.push({ path: [...path, 'type'], message: 'must be a component name' });\n return undefined;\n }\n const definition = catalog.get(element.type);\n if (definition === undefined || definition.internal === true) {\n issues.push({\n path: [...path, 'type'],\n message: `unknown component \"${element.type}\" (allowed: ${catalog\n .modelComponents()\n .map((component) => component.name)\n .join(', ')})`,\n });\n return undefined;\n }\n const validated =\n phase === 'input'\n ? ((await validateProps(\n definition.props,\n element.props ?? {},\n catalog.validator,\n )) as GenuiValidation<Record<string, unknown>>)\n : await catalog.validate(element.type, element.props ?? {});\n let props: Record<string, unknown> = {};\n if (!validated.ok) {\n for (const issue of validated.issues) {\n issues.push({ path: [...path, 'props', ...issue.path], message: issue.message });\n }\n } else {\n props = validated.value;\n }\n const rawChildren = parseChildrenIfStringified(element.children);\n if (rawChildren === undefined || rawChildren === null) {\n return { type: element.type, props };\n }\n if (!Array.isArray(rawChildren)) {\n issues.push({\n path: [...path, 'children'],\n message: 'must be an array of elements (a literal array, not a string)',\n });\n return undefined;\n }\n if (rawChildren.length > 0 && definition.children !== true) {\n issues.push({\n path: [...path, 'children'],\n message: `${element.type} does not take children`,\n });\n return undefined;\n }\n const children: GenuiElement[] = [];\n for (const [index, child] of rawChildren.entries()) {\n const next = await visit(child, [...path, 'children', index], depth + 1);\n if (next !== undefined) {\n children.push(next);\n }\n }\n return children.length > 0\n ? { type: element.type, props, children }\n : { type: element.type, props };\n };\n\n const root = await visit(tree, [], 1);\n return issues.length > 0 || root === undefined\n ? { ok: false, issues: issues.length > 0 ? issues : [{ path: [], message: 'is invalid' }] }\n : { ok: true, value: root };\n}\n\n/**\n * The JSON Schema of a tree-mode tool's input: a recursive `{ type, props, children? }` node whose\n * `type` is one of the catalog's model-facing component names. Per-component props are described\n * to the model in the tool description (see `catalogToModelText`) and checked by\n * {@link validateTree}, which keeps this schema small enough for every provider.\n */\nexport function treeJsonSchema(catalog: Catalog): JsonSchema {\n return {\n type: 'object',\n properties: {\n type: {\n type: 'string',\n enum: catalog.modelComponents().map((component) => component.name),\n description: 'Component name from the catalog',\n },\n props: {\n type: 'object',\n description: \"The component's props, as the catalog describes them\",\n },\n children: {\n type: 'array',\n items: { $ref: '#' },\n description:\n 'Nested elements, only for components that take children. A literal JSON array, never a JSON-stringified one.',\n },\n },\n required: ['type', 'props'],\n };\n}\n\n/** A json-render flat spec: `{ root, elements: { [id]: { type, props, children: id[] } } }`. */\nexport interface FlatSpec {\n root: string;\n elements: Record<string, { type: string; props: Record<string, unknown>; children: string[] }>;\n}\n\n/** Convert a tree to a json-render flat spec (ids are `el-0`, `el-1`, … in depth-first order). */\nexport function treeToFlatSpec(root: GenuiElement): FlatSpec {\n const elements: FlatSpec['elements'] = {};\n let next = 0;\n const visit = (node: GenuiElement): string => {\n const id = `el-${next++}`;\n const entry = { type: node.type, props: node.props, children: [] as string[] };\n elements[id] = entry;\n for (const child of node.children ?? []) {\n entry.children.push(visit(child));\n }\n return id;\n };\n return { root: visit(root), elements };\n}\n\nfunction parseChildrenIfStringified(value: unknown): unknown {\n if (typeof value !== 'string') return value;\n const trimmed = value.trim();\n if (!trimmed.startsWith('[')) return value;\n return leadingJsonArray(trimmed) ?? value;\n}\n\n/**\n * The array `text` opens with, ignoring what follows: a model that stringifies `children` tends to\n * carry the enclosing object's `}` along, which `JSON.parse` refuses whole.\n */\nfunction leadingJsonArray(text: string): unknown[] | undefined {\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let index = 0; index < text.length; index += 1) {\n const char = text[index];\n if (inString) {\n if (escaped) escaped = false;\n else if (char === '\\\\') escaped = true;\n else if (char === '\"') inString = false;\n continue;\n }\n if (char === '\"') inString = true;\n else if (char === '[' || char === '{') depth += 1;\n else if (char === ']' || char === '}') {\n depth -= 1;\n if (depth === 0) {\n try {\n const parsed: unknown = JSON.parse(text.slice(0, index + 1));\n return Array.isArray(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n }\n }\n }\n return undefined;\n}\n","import { type Catalog, toolNameFor } from './catalog.js';\nimport { type JsonSchema, toJsonSchema } from './schema.js';\nimport { GENUI_TREE_COMPONENT, type GenuiElement } from './tree.js';\n\n/**\n * Plain text (Slack mrkdwn compatible) for a pushed component: its definition's `fallbackText`, or\n * the props as a JSON block when the catalog has no text for it. A tree frame\n * ({@link GENUI_TREE_COMPONENT}) renders node by node. Never throws — a fallback that fails prints\n * the JSON instead.\n */\nexport function componentToText(\n catalog: Catalog,\n component: string,\n props: Record<string, unknown>,\n): string {\n if (component === GENUI_TREE_COMPONENT) {\n const root = props.root as GenuiElement | undefined;\n return root === undefined ? '' : treeToText(catalog, root);\n }\n const fallback = catalog.get(component)?.fallbackText;\n if (fallback !== undefined) {\n try {\n const text = fallback(props);\n if (typeof text === 'string' && text.trim().length > 0) return text;\n } catch {\n /* fall through to the generic rendering */\n }\n }\n return jsonBlock(props);\n}\n\n/** Plain text for a composed tree: each node's text, depth-first, blank-line free. */\nexport function treeToText(catalog: Catalog, root: GenuiElement): string {\n const out: string[] = [];\n const visit = (node: GenuiElement, depth: number) => {\n if (depth > 32) return;\n const definition = catalog.get(node.type);\n if (definition?.fallbackText !== undefined) {\n try {\n const text = definition.fallbackText(node.props);\n out.push(typeof text === 'string' && text.trim().length > 0 ? text : jsonBlock(node.props));\n } catch {\n out.push(jsonBlock(node.props));\n }\n } else if (definition?.children !== true) {\n out.push(jsonBlock(node.props));\n }\n for (const child of node.children ?? []) visit(child, depth + 1);\n };\n visit(root, 0);\n return out.filter((line) => line.trim().length > 0).join('\\n');\n}\n\nfunction jsonBlock(props: Record<string, unknown>): string {\n const title =\n typeof props.title === 'string' && props.title.length > 0 ? `*${props.title}*\\n` : '';\n return `${title}\\`\\`\\`\\n${JSON.stringify(props, null, 2)}\\n\\`\\`\\``;\n}\n\nexport interface CatalogTextOptions {\n /**\n * `per-component`: each component is its own tool (`ui__show_<snake>`), named in the text.\n * `tree`: one tool takes a nested `{ type, props, children }` tree; the text explains the format.\n * `show`: one tool takes `{ component, props }` (the generic show tool). Default `tree`.\n */\n mode?: 'per-component' | 'tree' | 'show';\n /** Tool-name prefix for `per-component`. Default `ui__show_`. */\n namePrefix?: string;\n}\n\n/**\n * The catalog described for a model: one entry per model-facing component with its description and\n * a compact TypeScript-like signature of its props. What a tree-mode (or show) tool puts in its\n * description, and what a host can add to a system prompt.\n */\nexport function catalogToModelText(catalog: Catalog, options: CatalogTextOptions = {}): string {\n const mode = options.mode ?? 'tree';\n const lines: string[] = [];\n if (mode === 'tree') {\n lines.push(\n 'Compose the UI as ONE tree of elements: { \"type\": <component>, \"props\": { … }, \"children\"?: [ … ] }.',\n 'Only components marked \"takes children\" accept children; `children` is a literal JSON array, never a string.',\n 'Components:',\n );\n } else if (mode === 'show') {\n lines.push('Pass { \"component\": <name>, \"props\": { … } } with one of these components:');\n } else {\n lines.push('Components you can show (one tool each):');\n }\n for (const component of catalog.modelComponents()) {\n const schema = toJsonSchema(component.props);\n const head =\n mode === 'per-component'\n ? `- ${component.name} (tool \\`${toolNameFor(component.name, options.namePrefix)}\\`)`\n : `- ${component.name}`;\n lines.push(`${head}: ${component.description}`);\n if (schema !== undefined) {\n lines.push(` props: ${summarizeSchema(schema, schema, 0)}`);\n }\n if (mode === 'tree' && component.children === true) {\n lines.push(' takes children');\n }\n }\n return lines.join('\\n');\n}\n\n/** A JSON Schema as a one-line TypeScript-like type, e.g. `{ title?: string, rows: object[] }`. */\nexport function summarizeSchema(schema: unknown, root: JsonSchema, depth: number): string {\n if (typeof schema !== 'object' || schema === null) return 'unknown';\n const s = schema as Record<string, unknown>;\n if (depth > 5) return '…';\n if (typeof s.$ref === 'string') {\n return s.$ref === '#' ? 'Self' : (s.$ref.split('/').pop() ?? 'unknown');\n }\n if (Array.isArray(s.enum)) {\n return s.enum.map((option) => JSON.stringify(option)).join(' | ');\n }\n if ('const' in s) return JSON.stringify(s.const);\n const variants = (s.anyOf ?? s.oneOf) as unknown[] | undefined;\n if (Array.isArray(variants)) {\n return variants.map((variant) => summarizeSchema(variant, root, depth + 1)).join(' | ');\n }\n const types = Array.isArray(s.type) ? (s.type as string[]) : s.type !== undefined ? [s.type] : [];\n if (types.length > 1) {\n return types.map((type) => summarizeSchema({ ...s, type }, root, depth + 1)).join(' | ');\n }\n const type = types[0] as string | undefined;\n if (type === 'array') {\n const item = s.items === undefined ? 'unknown' : summarizeSchema(s.items, root, depth + 1);\n return /[|\\s]/.test(item) && !item.startsWith('{') ? `(${item})[]` : `${item}[]`;\n }\n if (type === 'object' || (type === undefined && s.properties !== undefined)) {\n const properties = (s.properties ?? {}) as Record<string, unknown>;\n const keys = Object.keys(properties);\n if (keys.length === 0) return 'object';\n const required = new Set(Array.isArray(s.required) ? (s.required as string[]) : []);\n const fields = keys.map((key) => {\n const field = properties[key] as Record<string, unknown> | undefined;\n const note =\n typeof field?.description === 'string' && depth === 0 ? ` /* ${field.description} */` : '';\n return `${key}${required.has(key) ? '' : '?'}: ${summarizeSchema(field, root, depth + 1)}${note}`;\n });\n return `{ ${fields.join(', ')} }`;\n }\n if (type === 'integer') return 'number';\n return type ?? 'unknown';\n}\n\n/** Replace `{{path}}` placeholders with prop values (objects as JSON). */\nexport function fillTemplate(template: string, props: Record<string, unknown>): string {\n return template.replace(/\\{\\{\\s*([\\w.[\\]]+)\\s*\\}\\}/g, (_match, path: string) => {\n const value = getPath(props, path);\n if (value === null || value === undefined) return '';\n return typeof value === 'object' ? JSON.stringify(value) : String(value);\n });\n}\n\n/** Read `a.b[0].c` from a value; `undefined` when any step is missing. */\nexport function getPath(source: unknown, path: string): unknown {\n let current: any = source;\n for (const part of path\n .replace(/\\[(\\d+)\\]/g, '.$1')\n .split('.')\n .filter(Boolean)) {\n if (current === null || current === undefined) return undefined;\n current = current[part];\n }\n return current;\n}\n","import { COMPONENT_NAME, type Catalog, defineCatalog } from './catalog.js';\nimport { formatIssues } from './schema.js';\nimport { componentToText, treeToText } from './text.js';\nimport { GENUI_TREE_COMPONENT, type GenuiElement, validateTree } from './tree.js';\n\n/** Renderer support only. Component definitions and authorization remain server-owned. */\nexport interface UiCapabilities {\n components: Array<{ name: string; version: number }>;\n}\n\nexport function validateUiCapabilities(value: unknown): UiCapabilities {\n if (\n !record(value) ||\n Object.keys(value).some((key) => key !== 'components') ||\n !Array.isArray(value.components)\n )\n throw new TypeError('Invalid UI capabilities');\n const seen = new Set<string>();\n const components = value.components.map((component: unknown) => {\n if (\n !record(component) ||\n Object.keys(component).some((key) => key !== 'name' && key !== 'version') ||\n typeof component.name !== 'string' ||\n !COMPONENT_NAME.test(component.name) ||\n !Number.isSafeInteger(component.version) ||\n Number(component.version) <= 0 ||\n seen.has(component.name)\n )\n throw new TypeError('Invalid UI component capability');\n seen.add(component.name);\n return { name: component.name, version: Number(component.version) };\n });\n return { components };\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function negotiateCatalog(catalog: Catalog, capabilities?: UiCapabilities): Catalog {\n if (capabilities === undefined) return catalog;\n const supported = validateUiCapabilities(capabilities).components;\n return defineCatalog(\n catalog.components.filter((component) =>\n supported.some(\n (entry) => entry.name === component.name && entry.version === (component.version ?? 1),\n ),\n ),\n { jsonSchemaValidator: catalog.validator },\n );\n}\n\nexport type PreparedUiEmission =\n | {\n kind: 'ui';\n component: string;\n props: Record<string, unknown>;\n version: number;\n fallbackText: string;\n componentVersions?: Record<string, number>;\n }\n | { kind: 'text'; text: string };\n\n/** Validate against current trusted definitions before drawing or generating complete text. */\nexport async function prepareUiEmission(\n catalog: Catalog,\n capabilities: UiCapabilities | undefined,\n component: string,\n props: Record<string, unknown>,\n version?: number,\n): Promise<PreparedUiEmission> {\n const drawable = negotiateCatalog(catalog, capabilities);\n if (component === GENUI_TREE_COMPONENT) {\n if (version !== undefined && version !== 1) throw new Error('Invalid UI tree version');\n const validated = await validateTree(catalog, props.root);\n if (!validated.ok) throw new Error(`Invalid UI tree: ${formatIssues(validated.issues)}`);\n const supported = (node: GenuiElement): boolean =>\n drawable.has(node.type) && (node.children ?? []).every(supported);\n const versions = new Map<string, number>();\n const collectVersions = (node: GenuiElement): void => {\n versions.set(node.type, catalog.get(node.type)?.version ?? 1);\n for (const child of node.children ?? []) collectVersions(child);\n };\n collectVersions(validated.value);\n return supported(validated.value)\n ? {\n kind: 'ui',\n component,\n props: { root: validated.value },\n version: 1,\n fallbackText: treeToText(catalog, validated.value),\n componentVersions: Object.fromEntries(versions),\n }\n : { kind: 'text', text: treeToText(catalog, validated.value) };\n }\n const definition = catalog.get(component);\n if (definition === undefined) throw new Error(`Unknown UI component \"${component}\"`);\n const currentVersion = definition.version ?? 1;\n if (version !== undefined && version !== currentVersion)\n throw new Error(`Invalid UI component version for \"${component}\"`);\n const validated = await catalog.validate(component, props);\n if (!validated.ok) throw new Error(`Invalid UI props: ${formatIssues(validated.issues)}`);\n return drawable.has(component)\n ? {\n kind: 'ui',\n component,\n props: validated.value,\n version: currentVersion,\n fallbackText: componentToText(catalog, component, validated.value),\n }\n : { kind: 'text', text: componentToText(catalog, component, validated.value) };\n}\n","import type { StandardJSONSchemaV1, StandardSchemaV1 } from '@standard-schema/spec';\nimport type { AiToolCtx, ToolDescribeScope, ToolDescription, ToolHandler } from '../spi/tool.js';\nimport type { ToolPresentation } from '../tool-presentation.js';\nimport type { Actor, ToolSpec } from '../types.js';\nimport { negotiateCatalog } from './capabilities.js';\nimport { type Catalog, type ComponentDefinition, toolNameFor } from './catalog.js';\nimport {\n type GenuiIssue,\n type JsonSchema,\n formatIssues,\n isStandardSchema,\n toJsonSchema,\n validateProps,\n} from './schema.js';\nimport { catalogToModelText } from './text.js';\nimport {\n GENUI_TREE_COMPONENT,\n type GenuiElement,\n type TreeLimits,\n treeJsonSchema,\n validateTree,\n} from './tree.js';\n\n/** A lib tool: register it with `provideAgentTool(tool)` (NestJS) or `registry.register(tool.spec, tool.handler)`. */\nexport interface GenuiTool {\n spec: ToolSpec & { terminal?: boolean };\n handler: ToolHandler;\n}\n\n/** What a genui tool returns to the model: what was pushed, and the `ui` frame's id. */\nexport interface GenuiToolOutput {\n shown: string;\n id: string;\n}\n\n/**\n * Who a catalog is being resolved for. `tenant` is `actor.tenantRef`. `threadId` is absent only\n * when a tool list is built outside a conversation (the MCP server's `tools/list`).\n */\nexport interface GenuiCatalogScope {\n actor: Actor;\n threadId?: string;\n tenant?: string;\n agentName?: string;\n}\n\n/** Answers which catalog applies to a request — a tenant's own, versioned components. */\nexport type ResolveGenuiCatalog = (scope: GenuiCatalogScope) => Catalog | Promise<Catalog>;\n\nexport interface GenuiToolsOptions {\n /**\n * `per-component` (default): one tool per model-facing component, `ui__show_<snake>`, whose input\n * IS the component's props. `tree`: a single tool whose input is a nested\n * `{ type, props, children }` tree composed from the catalog (json-render's nested shape).\n */\n mode?: 'per-component' | 'tree';\n /**\n * The model's turn ends once a genui call succeeds — no further model call to narrate what the UI\n * already shows. Stamped as `spec.terminal`.\n */\n terminal?: boolean;\n /** Tool-name prefix for `per-component`. Default `ui__show_`. */\n namePrefix?: string;\n /** Tool name for `tree`. Default `ui__render`. */\n treeToolName?: string;\n /** Extra text prepended to the tree tool's description (when to call it, house rules). */\n treeInstructions?: string;\n /** Size limits for `tree`. */\n treeLimits?: TreeLimits;\n /**\n * Also offer ONE generic tool taking `{ component, props }`, validated against the (resolved)\n * catalog — how a model reaches components that only exist per request (a tenant's own), which a\n * boot-time tool list cannot name. `true` names it `ui__show`; a string names it.\n */\n showTool?: boolean | string;\n /** Extra text prepended to the show tool's description. */\n showInstructions?: string;\n /** Roles allowed to call the tools (the `ToolSpec.roles` gate). Undefined → the roles policy default. */\n roles?: string[];\n /** Override the generated presentation per component (or for the tree / show tool, under its tool name). */\n presentation?: (component: string) => ToolPresentation | undefined;\n /**\n * The catalog for THIS request, consulted when a call is validated and when the turn's tool list\n * is described to the model. The `catalog` argument is then the boot-time one: it names the\n * per-component tools and is what a list built without a resolver would show. Omit → the\n * `catalog` argument serves every request.\n */\n resolveCatalog?: ResolveGenuiCatalog;\n}\n\n/** The default name of the generic show tool ({@link GenuiToolsOptions.showTool}). */\nexport const GENUI_SHOW_TOOL = 'ui__show';\n\n/**\n * Tools that let a model push catalog components into the conversation as `ui` frames. Each call\n * validates its input against the catalog (a refused call reaches the model as a tool error it can\n * fix) and then pushes through `ctx.emitUi`, which streams the frame live and persists it on the\n * assistant message.\n */\nexport function genuiTools(catalog: Catalog, options: GenuiToolsOptions = {}): GenuiTool[] {\n const tools =\n options.mode === 'tree'\n ? [treeTool(catalog, options)]\n : catalog.modelComponents().map((component) => componentTool(catalog, component, options));\n if (options.showTool !== undefined && options.showTool !== false) {\n tools.push(showTool(catalog, options));\n }\n return tools;\n}\n\nfunction scopeOf(input: {\n actor: Actor;\n threadId?: string;\n agentName?: string;\n}): GenuiCatalogScope {\n return {\n actor: input.actor,\n ...(input.threadId !== undefined ? { threadId: input.threadId } : {}),\n ...(input.actor.tenantRef !== undefined ? { tenant: input.actor.tenantRef } : {}),\n ...(input.agentName !== undefined ? { agentName: input.agentName } : {}),\n };\n}\n\nfunction catalogFor(\n catalog: Catalog,\n options: GenuiToolsOptions,\n scope: GenuiCatalogScope,\n): Catalog | Promise<Catalog> {\n return options.resolveCatalog === undefined ? catalog : options.resolveCatalog(scope);\n}\n\nfunction common(options: GenuiToolsOptions): Pick<ToolSpec, 'roles'> & { terminal?: boolean } {\n return {\n ...(options.roles !== undefined ? { roles: options.roles } : {}),\n ...(options.terminal === true ? { terminal: true } : {}),\n };\n}\n\nfunction componentTool(\n catalog: Catalog,\n component: ComponentDefinition<any>,\n options: GenuiToolsOptions,\n): GenuiTool {\n const presentation = options.presentation?.(component.name) ?? {\n label: component.title,\n running: `Showing ${lowerFirst(component.title)}`,\n done: `Showed ${lowerFirst(component.title)}`,\n result: { kind: 'elsewhere' as const },\n };\n const describeFor = (definition: ComponentDefinition<any>) =>\n `Show the user a ${definition.title} (${definition.name}). ${definition.description}`;\n const dynamic = options.resolveCatalog !== undefined;\n // With a resolver the component's schema may differ per request (a tenant's version of it), so\n // the registry lets any object through and `execute` validates against the resolved definition.\n const inputSchema: StandardSchemaV1 = dynamic\n ? permissiveSchema(toJsonSchema(component.props) ?? { type: 'object' })\n : isStandardSchema(component.props)\n ? component.props\n : jsonStandardSchema(component.props, (value) =>\n catalog.validator.validate(component.props as JsonSchema, value),\n );\n const handler: ToolHandler = {\n async execute(input: unknown, ctx: AiToolCtx): Promise<GenuiToolOutput> {\n const resolved = await catalogFor(catalog, options, scopeOf(ctx));\n const definition = modelComponent(resolved, component.name);\n if (definition === undefined) {\n throw new Error(`component \"${component.name}\" is not available here`);\n }\n // Static handlers receive the registry's parsed output; dynamic handlers parse the\n // request-specific input here. Never run an input transformation on portable output.\n const validated = await validateProps(\n dynamic ? definition.props : (definition.outputProps ?? definition.props),\n input,\n resolved.validator,\n );\n if (!validated.ok) {\n throw new Error(`invalid ${component.name} props: ${formatIssues(validated.issues)}`);\n }\n return push(\n ctx,\n component.name,\n validated.value as Record<string, unknown>,\n definition.version,\n );\n },\n };\n handler.describe = async (scope: ToolDescribeScope): Promise<ToolDescription> => {\n const resolved = negotiateCatalog(\n await catalogFor(catalog, options, scopeOf(scope)),\n scope.uiCapabilities,\n );\n const definition = modelComponent(resolved, component.name);\n if (definition === undefined) {\n return {\n available: false,\n description: `Not available in this conversation — do not call this tool. (${component.name})`,\n };\n }\n return {\n description: describeFor(definition),\n inputSchema: permissiveSchema(toJsonSchema(definition.props) ?? { type: 'object' }),\n };\n };\n return {\n spec: {\n name: toolNameFor(component.name, options.namePrefix),\n kind: 'read',\n description: describeFor(component),\n inputSchema,\n presentation,\n ...common(options),\n },\n handler,\n };\n}\n\nfunction treeTool(catalog: Catalog, options: GenuiToolsOptions): GenuiTool {\n const name = options.treeToolName ?? 'ui__render';\n const presentation = options.presentation?.(name) ?? {\n label: 'Answer',\n running: 'Laying out the answer',\n done: 'Laid out the answer',\n result: { kind: 'elsewhere' as const },\n };\n const describeFor = (resolved: Catalog) =>\n [\n options.treeInstructions ?? 'Render a rich UI to present the answer to the user.',\n catalogToModelText(resolved, { mode: 'tree' }),\n ].join('\\n');\n const dynamic = options.resolveCatalog !== undefined;\n const handler: ToolHandler = {\n async execute(input: unknown, ctx: AiToolCtx): Promise<GenuiToolOutput> {\n const resolved = await catalogFor(catalog, options, scopeOf(ctx));\n const result = await validateTree(\n resolved,\n input,\n options.treeLimits,\n dynamic ? 'input' : 'output',\n );\n if (!result.ok) {\n throw new Error(`invalid UI tree: ${formatIssues(result.issues)}`);\n }\n const root: GenuiElement = result.value;\n return push(ctx, GENUI_TREE_COMPONENT, { root });\n },\n };\n handler.describe = async (scope: ToolDescribeScope): Promise<ToolDescription> => {\n const resolved = negotiateCatalog(\n await catalogFor(catalog, options, scopeOf(scope)),\n scope.uiCapabilities,\n );\n return {\n available: resolved.modelComponents().length > 0,\n description: describeFor(resolved),\n inputSchema: permissiveSchema(treeJsonSchema(resolved)),\n };\n };\n return {\n spec: {\n name,\n kind: 'read',\n description: describeFor(catalog),\n inputSchema: dynamic\n ? permissiveSchema(treeJsonSchema(catalog))\n : asyncJsonStandardSchema(treeJsonSchema(catalog), async (value) => {\n const result = await validateTree(catalog, value, options.treeLimits, 'input');\n return result.ok ? { value: result.value } : { issues: result.issues };\n }),\n presentation,\n ...common(options),\n },\n handler,\n };\n}\n\n/** The show tool's input: a component name (one of the catalog's) and its props. */\nexport function showToolJsonSchema(catalog: Catalog): JsonSchema {\n return {\n type: 'object',\n properties: {\n component: {\n type: 'string',\n enum: catalog.modelComponents().map((component) => component.name),\n description: 'Component name from the catalog',\n },\n props: {\n type: 'object',\n description: \"The component's props, as the catalog describes them\",\n },\n },\n required: ['component', 'props'],\n };\n}\n\nasync function validateShow(\n catalog: Catalog,\n input: unknown,\n phase: 'input' | 'output' = 'input',\n): Promise<\n | { ok: true; definition: ComponentDefinition<any>; props: Record<string, unknown> }\n | { ok: false; issues: GenuiIssue[] }\n> {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n return { ok: false, issues: [{ path: [], message: 'must be { component, props }' }] };\n }\n const { component, props } = input as { component?: unknown; props?: unknown };\n if (typeof component !== 'string') {\n return { ok: false, issues: [{ path: ['component'], message: 'must be a component name' }] };\n }\n const definition = modelComponent(catalog, component);\n if (definition === undefined) {\n const allowed = catalog\n .modelComponents()\n .map((each) => each.name)\n .join(', ');\n return {\n ok: false,\n issues: [\n { path: ['component'], message: `unknown component \"${component}\" (allowed: ${allowed})` },\n ],\n };\n }\n const validated = await validateProps(\n phase === 'input' ? definition.props : (definition.outputProps ?? definition.props),\n props ?? {},\n catalog.validator,\n );\n if (!validated.ok) {\n return {\n ok: false,\n issues: validated.issues.map((issue) => ({ ...issue, path: ['props', ...issue.path] })),\n };\n }\n return { ok: true, definition, props: validated.value as Record<string, unknown> };\n}\n\nfunction showTool(catalog: Catalog, options: GenuiToolsOptions): GenuiTool {\n const name = typeof options.showTool === 'string' ? options.showTool : GENUI_SHOW_TOOL;\n const presentation = options.presentation?.(name) ?? {\n label: 'Show',\n running: 'Preparing a view',\n done: 'Showed a view',\n result: { kind: 'elsewhere' as const },\n };\n const describeFor = (resolved: Catalog) =>\n [\n options.showInstructions ?? 'Show the user one component from the catalog.',\n catalogToModelText(resolved, { mode: 'show' }),\n ].join('\\n');\n const dynamic = options.resolveCatalog !== undefined;\n const handler: ToolHandler = {\n async execute(input: unknown, ctx: AiToolCtx): Promise<GenuiToolOutput> {\n const resolved = await catalogFor(catalog, options, scopeOf(ctx));\n const result = await validateShow(resolved, input, dynamic ? 'input' : 'output');\n if (!result.ok) {\n throw new Error(`invalid ${name} call: ${formatIssues(result.issues)}`);\n }\n return push(ctx, result.definition.name, result.props, result.definition.version);\n },\n };\n handler.describe = async (scope: ToolDescribeScope): Promise<ToolDescription> => {\n const resolved = negotiateCatalog(\n await catalogFor(catalog, options, scopeOf(scope)),\n scope.uiCapabilities,\n );\n return {\n available: resolved.modelComponents().length > 0,\n description: describeFor(resolved),\n inputSchema: permissiveSchema(showToolJsonSchema(resolved)),\n };\n };\n return {\n spec: {\n name,\n kind: 'read',\n description: describeFor(catalog),\n inputSchema: dynamic\n ? permissiveSchema(showToolJsonSchema(catalog))\n : asyncJsonStandardSchema(showToolJsonSchema(catalog), async (value) => {\n const result = await validateShow(catalog, value);\n return result.ok\n ? { value: { component: result.definition.name, props: result.props } }\n : { issues: result.issues };\n }),\n presentation,\n ...common(options),\n },\n handler,\n };\n}\n\nfunction modelComponent(catalog: Catalog, name: string): ComponentDefinition<any> | undefined {\n const definition = catalog.get(name);\n return definition === undefined || definition.internal === true ? undefined : definition;\n}\n\nasync function push(\n ctx: AiToolCtx,\n component: string,\n props: Record<string, unknown>,\n version?: number,\n): Promise<GenuiToolOutput> {\n const { id } = await ctx.emitUi(component, props, version !== undefined ? { version } : {});\n return { shown: component, id };\n}\n\nfunction lowerFirst(text: string): string {\n return text.length > 0 ? `${text[0]?.toLowerCase()}${text.slice(1)}` : text;\n}\n\ntype JsonStandardSchema = StandardSchemaV1 & StandardJSONSchemaV1;\n\n/**\n * A JSON Schema presented as a Standard Schema WITH the Standard JSON Schema extension, so the lib\n * validates tool input through `~standard.validate` and the AI SDK adapter hands the model the\n * schema itself (it reads `~standard.jsonSchema.input`).\n */\nexport function jsonStandardSchema(\n schema: JsonSchema,\n validate: (value: unknown) => GenuiIssue[],\n): JsonStandardSchema {\n return asyncJsonStandardSchema(schema, (value) => {\n const issues = validate(value);\n return issues.length > 0 ? { issues } : { value };\n });\n}\n\n/** Shows the model `schema`, accepts any value: validation happens in `execute`, per request. */\nfunction permissiveSchema(schema: JsonSchema): JsonStandardSchema {\n return asyncJsonStandardSchema(schema, (value) => ({ value }));\n}\n\nfunction asyncJsonStandardSchema(\n schema: JsonSchema,\n validate: (\n value: unknown,\n ) =>\n | { value: unknown; issues?: undefined }\n | { issues: GenuiIssue[] }\n | Promise<{ value: unknown; issues?: undefined } | { issues: GenuiIssue[] }>,\n): JsonStandardSchema {\n const toResult = (\n outcome: { value: unknown; issues?: undefined } | { issues: GenuiIssue[] },\n ): StandardSchemaV1.Result<unknown> =>\n outcome.issues !== undefined\n ? {\n issues: outcome.issues.map((issue) => ({ message: issue.message, path: issue.path })),\n }\n : { value: (outcome as { value: unknown }).value };\n return {\n '~standard': {\n version: 1,\n vendor: 'nestjs-agent-genui',\n validate(value) {\n const outcome = validate(value);\n return outcome instanceof Promise ? outcome.then(toResult) : toResult(outcome);\n },\n jsonSchema: {\n input: () => schema,\n output: () => schema,\n },\n },\n } as JsonStandardSchema;\n}\n","/**\n * Optional builtin component DEFINITIONS — names, props schemas, model descriptions and plain-text\n * fallbacks for the components most chat apps want. No visuals: an app renders each with its own\n * look, keyed by name. Use them as-is, pick some, or extend them:\n *\n * ```ts\n * const catalog = defineCatalog([...BUILTIN_COMPONENTS, ...LAYOUT_COMPONENTS, myDealCard]);\n * ```\n */\nimport { type ComponentDefinition, defineComponent } from './catalog.js';\nimport type { JsonSchema } from './schema.js';\n\ntype Props = Record<string, any>;\n\nconst str = (description?: string, extra: JsonSchema = {}): JsonSchema => ({\n type: 'string',\n ...(description !== undefined ? { description } : {}),\n ...extra,\n});\nconst obj = (properties: Record<string, JsonSchema>, required: string[] = []): JsonSchema => ({\n type: 'object',\n properties,\n required,\n additionalProperties: false,\n});\nconst arr = (items: JsonSchema, extra: JsonSchema = {}): JsonSchema => ({\n type: 'array',\n items,\n ...extra,\n});\nconst cell: JsonSchema = { type: ['string', 'number', 'boolean', 'null'] };\nconst row: JsonSchema = { type: 'object', additionalProperties: cell };\n\nconst s = (value: unknown): string => (value === null || value === undefined ? '' : String(value));\nconst heading = (props: Props): string => (props.title ? `*${s(props.title)}*\\n` : '');\n\n/** A fixed-width text table in a code block, at most `max` rows. */\nexport function textTable(\n columns: readonly { key: string; label: string }[],\n rows: readonly Props[],\n max = 15,\n): string {\n const shown = rows.slice(0, max);\n const widths = columns.map((column) =>\n Math.min(28, Math.max(column.label.length, ...shown.map((r) => s(r[column.key]).length))),\n );\n const format = (values: string[]) =>\n values\n .map((value, index) => value.slice(0, widths[index]).padEnd(widths[index] ?? 0))\n .join(' ');\n const lines = [\n format(columns.map((column) => column.label)),\n widths.map((width) => '-'.repeat(width)).join(' '),\n ...shown.map((r) => format(columns.map((column) => s(r[column.key])))),\n ];\n if (rows.length > max) lines.push(`… ${rows.length - max} more rows`);\n return `\\`\\`\\`\\n${lines.join('\\n')}\\n\\`\\`\\``;\n}\n\nexport interface DiffLine {\n op: 'same' | 'add' | 'del';\n text: string;\n}\n\n/** Line diff (LCS) — good enough for snippets up to a few hundred lines. */\nexport function lineDiff(before: string, after: string): DiffLine[] {\n const a = before.split('\\n');\n const b = after.split('\\n');\n if (a.length * b.length > 250_000) {\n return [\n ...a.map((text) => ({ op: 'del' as const, text })),\n ...b.map((text) => ({ op: 'add' as const, text })),\n ];\n }\n const dp: number[][] = Array.from({ length: a.length + 1 }, () =>\n new Array<number>(b.length + 1).fill(0),\n );\n const at = (i: number, j: number): number => dp[i]?.[j] ?? 0;\n for (let i = a.length - 1; i >= 0; i--) {\n for (let j = b.length - 1; j >= 0; j--) {\n (dp[i] as number[])[j] =\n a[i] === b[j] ? at(i + 1, j + 1) + 1 : Math.max(at(i + 1, j), at(i, j + 1));\n }\n }\n const out: DiffLine[] = [];\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length) {\n if (a[i] === b[j]) {\n out.push({ op: 'same', text: a[i] as string });\n i++;\n j++;\n } else if (at(i + 1, j) >= at(i, j + 1)) {\n out.push({ op: 'del', text: a[i++] as string });\n } else {\n out.push({ op: 'add', text: b[j++] as string });\n }\n }\n while (i < a.length) out.push({ op: 'del', text: a[i++] as string });\n while (j < b.length) out.push({ op: 'add', text: b[j++] as string });\n return out;\n}\n\nfunction bar(value: number, max: number, width = 20): string {\n const n = max > 0 ? Math.round((Math.abs(value) / max) * width) : 0;\n return '█'.repeat(n) || '▏';\n}\n\nexport const DataTable = defineComponent<Props>({\n name: 'DataTable',\n title: 'Data table',\n description:\n 'Tabular data (records with the same fields) as a sortable table. Prefer it over markdown tables for more than 3 rows.',\n props: obj(\n {\n title: str('Short caption'),\n columns: arr(\n obj(\n {\n key: str('Field name in each row'),\n label: str('Column header'),\n align: str(undefined, { enum: ['left', 'right', 'center'] }),\n format: str('How to format values', {\n enum: ['text', 'number', 'currency', 'percent', 'date', 'link'],\n }),\n },\n ['key', 'label'],\n ),\n { minItems: 1, maxItems: 12 },\n ),\n rows: arr(row, { maxItems: 500 }),\n },\n ['columns', 'rows'],\n ),\n fallbackText: (props) => `${heading(props)}${textTable(props.columns ?? [], props.rows ?? [])}`,\n});\n\nexport const Chart = defineComponent<Props>({\n name: 'Chart',\n title: 'Chart',\n description:\n '`bar` to compare categories, `line` for a trend over time. `data` is a list of points; `xKey` names the category/time field and each series names a numeric field.',\n props: obj(\n {\n type: str('Chart type', { enum: ['bar', 'line'] }),\n title: str(),\n xKey: str('Field of each point used for the x axis'),\n series: arr(obj({ key: str('Numeric field'), label: str() }, ['key']), {\n minItems: 1,\n maxItems: 6,\n }),\n data: arr(row, { minItems: 1, maxItems: 200 }),\n unit: str('Unit shown after values, e.g. `KB` or `%`'),\n },\n ['type', 'xKey', 'series', 'data'],\n ),\n fallbackText: (props) => {\n const series: { key: string }[] = props.series ?? [];\n const data: Props[] = props.data ?? [];\n const first = series[0]?.key ?? '';\n const max = Math.max(0, ...data.map((point) => Math.abs(Number(point[first]) || 0)));\n const unit = props.unit ? ` ${s(props.unit)}` : '';\n const lines = data\n .slice(0, 20)\n .map(\n (point) =>\n `${s(point[props.xKey]).slice(0, 18).padEnd(18)} ${bar(Number(point[first]) || 0, max)} ${s(point[first])}${unit}`,\n );\n return `${heading(props)}\\`\\`\\`\\n${lines.join('\\n')}\\n\\`\\`\\``;\n },\n});\n\nexport const KpiCards = defineComponent<Props>({\n name: 'KpiCards',\n title: 'KPI cards',\n description: 'A few key numbers (metrics, totals, counts) as cards.',\n props: obj(\n {\n title: str(),\n items: arr(\n obj(\n {\n label: str(),\n value: { type: ['string', 'number'] },\n delta: str('Change, e.g. `+12%`'),\n trend: str(undefined, { enum: ['up', 'down', 'flat'] }),\n hint: str(),\n },\n ['label', 'value'],\n ),\n { minItems: 1, maxItems: 8 },\n ),\n },\n ['items'],\n ),\n fallbackText: (props) =>\n `${heading(props)}${(props.items ?? [])\n .map(\n (item: Props) =>\n `• *${s(item.label)}:* ${s(item.value)}${item.delta ? ` (${s(item.delta)})` : ''}`,\n )\n .join('\\n')}`,\n});\n\nexport const SourceCards = defineComponent<Props>({\n name: 'SourceCards',\n title: 'Sources',\n description: 'The documents, pages or links an answer is based on, as cards.',\n props: obj(\n {\n title: str(),\n items: arr(\n obj({ title: str(), url: str(), snippet: str(), source: str('e.g. Wiki, GitHub') }, [\n 'title',\n ]),\n { minItems: 1, maxItems: 12 },\n ),\n },\n ['items'],\n ),\n fallbackText: (props) =>\n `${heading(props)}${(props.items ?? [])\n .map(\n (item: Props) =>\n `• ${item.url ? `<${s(item.url)}|${s(item.title)}>` : s(item.title)}${item.source ? ` — ${s(item.source)}` : ''}`,\n )\n .join('\\n')}`,\n});\n\nexport const Checklist = defineComponent<Props>({\n name: 'Checklist',\n title: 'Checklist',\n description: 'Steps or a to-do list with done/not-done state.',\n props: obj(\n {\n title: str(),\n items: arr(obj({ label: str(), done: { type: 'boolean' }, note: str() }, ['label']), {\n minItems: 1,\n maxItems: 50,\n }),\n },\n ['items'],\n ),\n fallbackText: (props) =>\n `${heading(props)}${(props.items ?? [])\n .map(\n (item: Props) =>\n `${item.done ? '☑' : '☐'} ${s(item.label)}${item.note ? ` — _${s(item.note)}_` : ''}`,\n )\n .join('\\n')}`,\n});\n\nexport const Timeline = defineComponent<Props>({\n name: 'Timeline',\n title: 'Timeline',\n description: 'Events in chronological order (the history of a project, an incident, a deal).',\n props: obj(\n {\n title: str(),\n events: arr(obj({ date: str(), title: str(), description: str() }, ['title']), {\n minItems: 1,\n maxItems: 50,\n }),\n },\n ['events'],\n ),\n fallbackText: (props) =>\n `${heading(props)}${(props.events ?? [])\n .map(\n (event: Props) =>\n `• ${event.date ? `*${s(event.date)}* ` : ''}${s(event.title)}${event.description ? ` — ${s(event.description)}` : ''}`,\n )\n .join('\\n')}`,\n});\n\nexport const CodeBlock = defineComponent<Props>({\n name: 'CodeBlock',\n title: 'Code',\n description: 'A code snippet or file excerpt with syntax highlighting.',\n props: obj({ title: str(), language: str(), code: str() }, ['code']),\n fallbackText: (props) => `${heading(props)}\\`\\`\\`\\n${s(props.code)}\\n\\`\\`\\``,\n});\n\nexport const Diff = defineComponent<Props>({\n name: 'Diff',\n title: 'Diff',\n description: 'A before/after change to a text or code file, as a line diff.',\n props: obj({ title: str(), language: str(), before: str(), after: str() }, ['before', 'after']),\n fallbackText: (props) =>\n `${heading(props)}\\`\\`\\`\\n${lineDiff(s(props.before), s(props.after))\n .map((line) => `${line.op === 'add' ? '+' : line.op === 'del' ? '-' : ' '} ${line.text}`)\n .join('\\n')}\\n\\`\\`\\``,\n});\n\nexport const Callout = defineComponent<Props>({\n name: 'Callout',\n title: 'Callout',\n description: 'A short note, warning or success message, emphasized.',\n props: obj(\n {\n tone: str(undefined, { enum: ['info', 'success', 'warning', 'danger'] }),\n title: str(),\n text: str(),\n },\n ['text'],\n ),\n fallbackText: (props) =>\n `${props.tone === 'warning' || props.tone === 'danger' ? ':warning: ' : ':information_source: '}${heading(props)}${s(props.text)}`,\n});\n\nexport const Stack = defineComponent<Props>({\n name: 'Stack',\n title: 'Stack',\n description: 'Lays its children out vertically (or horizontally with direction=row).',\n props: obj({ direction: str(undefined, { enum: ['column', 'row'] }), gap: { type: 'number' } }),\n children: true,\n fallbackText: () => '',\n});\n\nexport const Card = defineComponent<Props>({\n name: 'Card',\n title: 'Card',\n description: 'A box with an optional title around its children.',\n props: obj({ title: str(), subtitle: str() }),\n children: true,\n fallbackText: (props) =>\n props.title ? `*${s(props.title)}*${props.subtitle ? ` — ${s(props.subtitle)}` : ''}` : '',\n});\n\nexport const Heading = defineComponent<Props>({\n name: 'Heading',\n title: 'Heading',\n description: 'A heading.',\n props: obj({ text: str() }, ['text']),\n fallbackText: (props) => `*${s(props.text)}*`,\n});\n\nexport const Text = defineComponent<Props>({\n name: 'Text',\n title: 'Text',\n description: 'A paragraph of plain text (no markdown).',\n props: obj({ text: str(), muted: { type: 'boolean' } }, ['text']),\n fallbackText: (props) => s(props.text),\n});\n\nexport const Badge = defineComponent<Props>({\n name: 'Badge',\n title: 'Badge',\n description: 'A small label.',\n props: obj(\n {\n text: str(),\n tone: str(undefined, { enum: ['neutral', 'brand', 'success', 'warning', 'danger'] }),\n },\n ['text'],\n ),\n fallbackText: (props) => `[${s(props.text)}]`,\n});\n\nexport const Link = defineComponent<Props>({\n name: 'Link',\n title: 'Link',\n description: 'A link to an http(s) URL.',\n props: obj({ text: str(), url: str(undefined, { pattern: '^https?://' }) }, ['text', 'url']),\n fallbackText: (props) => `<${s(props.url)}|${s(props.text || props.url)}>`,\n});\n\nexport const Image = defineComponent<Props>({\n name: 'Image',\n title: 'Image',\n description: 'An image from an https URL.',\n props: obj({ url: str(undefined, { pattern: '^https://' }), alt: str() }, ['url']),\n fallbackText: (props) => s(props.url),\n});\n\n/** Content components: data a model shows. */\nexport const BUILTIN_COMPONENTS: readonly ComponentDefinition<Props>[] = [\n DataTable,\n Chart,\n KpiCards,\n SourceCards,\n Checklist,\n Timeline,\n CodeBlock,\n Diff,\n Callout,\n];\n\n/** Layout and text primitives, mostly for composing trees (`Stack`, `Card` take children). */\nexport const LAYOUT_COMPONENTS: readonly ComponentDefinition<Props>[] = [\n Stack,\n Card,\n Heading,\n Text,\n Badge,\n Link,\n Image,\n];\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { Chart, DataTable } from './builtins.js';\nimport {\n type Catalog,\n type CatalogOptions,\n type ComponentDefinition,\n defineCatalog,\n defineComponent,\n} from './catalog.js';\nimport { type JsonSchema, formatIssues, validateProps } from './schema.js';\nimport { componentToText } from './text.js';\n\n/** Plain, durable data. Renderer functions and binary attachments never enter a UI frame. */\nexport interface ComponentPresentation<P = Record<string, unknown>> {\n component: string;\n props: P;\n version: number;\n fallbackText: string;\n}\n\nexport interface ComponentFactory<Input, Output = Input> {\n (props: Input): Promise<ComponentPresentation<Output>>;\n readonly definition: ComponentDefinition<Output>;\n}\n\n/** Reject values JSON would silently discard/coerce, and detach from caller-owned objects. */\nexport function snapshotComponentPresentation<T>(value: T): T {\n const seen = new Set<object>();\n const check = (entry: unknown): void => {\n if (entry === null || typeof entry === 'string' || typeof entry === 'boolean') return;\n if (typeof entry === 'number' && Number.isFinite(entry)) return;\n if (typeof entry !== 'object' || entry === null)\n throw new TypeError('genui: presentation must contain only JSON values');\n if (seen.has(entry))\n throw new TypeError('genui: presentation must contain acyclic JSON values');\n if (\n !Array.isArray(entry) &&\n Object.getPrototypeOf(entry) !== Object.prototype &&\n Object.getPrototypeOf(entry) !== null\n )\n throw new TypeError('genui: presentation must contain plain JSON objects');\n seen.add(entry);\n for (const item of Object.values(entry)) check(item);\n seen.delete(entry);\n };\n check(value);\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nexport function createComponent<S extends StandardSchemaV1>(\n definition: Omit<ComponentDefinition<StandardSchemaV1.InferOutput<S>>, 'props'> & { props: S },\n options?: CatalogOptions,\n): ComponentFactory<StandardSchemaV1.InferInput<S>, StandardSchemaV1.InferOutput<S>>;\nexport function createComponent<P = Record<string, unknown>>(\n definition: ComponentDefinition<P>,\n options?: CatalogOptions,\n): ComponentFactory<P>;\nexport function createComponent<P>(\n definition: ComponentDefinition<P>,\n options: CatalogOptions = {},\n): unknown {\n defineComponent(definition);\n const catalog = defineCatalog([definition], options);\n const factory = async (props: unknown): Promise<ComponentPresentation> => {\n const result = await validateProps(definition.props, props, catalog.validator);\n if (!result.ok)\n throw new Error(`genui: invalid ${definition.name} props: ${formatIssues(result.issues)}`);\n const normalized = snapshotComponentPresentation(result.value);\n if (typeof normalized !== 'object' || normalized === null || Array.isArray(normalized))\n throw new TypeError('genui: component props must be a JSON object');\n const portable = await catalog.validate(definition.name, normalized);\n if (\n !portable.ok ||\n canonicalJson(snapshotComponentPresentation(portable.value)) !== canonicalJson(normalized)\n ) {\n throw new Error(\n `genui: ${definition.name} requires outputProps accepting stable normalized JSON props`,\n );\n }\n return {\n component: definition.name,\n props: normalized as Record<string, unknown>,\n version: definition.version ?? 1,\n fallbackText: componentToText(\n catalog,\n definition.name,\n normalized as Record<string, unknown>,\n ),\n };\n };\n return Object.assign(factory, { definition });\n}\n\nexport type ComponentRenderer<P = Record<string, unknown>, Context = unknown> = (\n props: P,\n context?: Context,\n) => unknown | Promise<unknown>;\n\nexport interface ComponentManifest {\n name: string;\n title: string;\n description: string;\n version: number;\n props?: JsonSchema;\n}\n\nexport interface ComponentRegistry<Context = unknown> {\n readonly catalog: Catalog;\n readonly manifest: readonly ComponentManifest[];\n register<P>(\n definition: ComponentDefinition<P>,\n renderers: Record<string, ComponentRenderer<P, Context>>,\n ): this;\n /** Revalidate against the app's authoritative definition and regenerate trusted fallback text. */\n prepare(presentation: ComponentPresentation): Promise<ComponentPresentation>;\n render(presentation: ComponentPresentation, channel: string, context?: Context): Promise<unknown>;\n}\n\n/** A registry is owned by one app/tenant; registering never mutates a shared singleton. */\nexport function createComponentRegistry<Context = unknown>(\n options: CatalogOptions = {},\n): ComponentRegistry<Context> {\n let catalog = defineCatalog([], options);\n const channels = new Map<string, Record<string, ComponentRenderer<never, Context>>>();\n const registry: ComponentRegistry<Context> = {\n get catalog() {\n return catalog;\n },\n get manifest() {\n return catalog.components.map((definition) => {\n const props = catalog.jsonSchemaFor(definition.name);\n return {\n name: definition.name,\n title: definition.title,\n description: definition.description,\n version: definition.version ?? 1,\n ...(props === undefined ? {} : { props: snapshotComponentPresentation(props) }),\n };\n });\n },\n register(definition, renderers) {\n if (catalog.has(definition.name))\n throw new Error(`genui: component \"${definition.name}\" is already registered`);\n catalog = catalog.extend([definition]);\n channels.set(definition.name, { ...renderers } as Record<\n string,\n ComponentRenderer<never, Context>\n >);\n return this;\n },\n async prepare(presentation) {\n const definition = catalog.get(presentation.component);\n if (definition === undefined)\n throw new Error(`genui: unknown component \"${presentation.component}\"`);\n if (presentation.version !== (definition.version ?? 1))\n throw new Error(`genui: component \"${presentation.component}\" version mismatch`);\n const validated = await catalog.validate(presentation.component, presentation.props);\n if (!validated.ok)\n throw new Error(\n `genui: invalid ${presentation.component} props: ${formatIssues(validated.issues)}`,\n );\n const props = snapshotComponentPresentation(validated.value);\n if (typeof props !== 'object' || props === null || Array.isArray(props))\n throw new TypeError('genui: component props must be a JSON object');\n return {\n component: definition.name,\n props,\n version: definition.version ?? 1,\n fallbackText: componentToText(catalog, definition.name, props),\n };\n },\n async render(presentation, channel, context) {\n const prepared = await this.prepare(presentation);\n const mapping = channels.get(prepared.component);\n const renderer =\n mapping === undefined\n ? undefined\n : Object.hasOwn(mapping, channel)\n ? mapping[channel]\n : Object.hasOwn(mapping, 'text')\n ? mapping.text\n : undefined;\n return renderer === undefined\n ? prepared.fallbackText\n : renderer(prepared.props as never, context);\n },\n };\n return registry;\n}\n\nexport type TableCell = string | number | boolean | null;\nexport interface TableProps {\n title?: string;\n columns: {\n key: string;\n label: string;\n align?: 'left' | 'right' | 'center';\n format?: 'text' | 'number' | 'currency' | 'percent' | 'date' | 'link';\n }[];\n rows: Record<string, TableCell>[];\n}\nexport interface ChartProps {\n type: 'bar' | 'line';\n title?: string;\n xKey: string;\n series: { key: string; label?: string }[];\n data: Record<string, TableCell>[];\n unit?: string;\n}\n\nexport const table = createComponent<TableProps>(DataTable);\nexport const chart = createComponent<ChartProps>(Chart);\n\n/** Prepare all JSON emissions before any sink receives a partial batch. Factories validate schemas. */\nexport function validatePresentationBatch(\n presentations: ComponentPresentation<object> | readonly ComponentPresentation<object>[],\n): ComponentPresentation[] {\n const batch = Array.isArray(presentations) ? presentations : [presentations];\n return batch.map((item: ComponentPresentation<object>) => {\n const presentation = snapshotComponentPresentation(item);\n if (\n typeof presentation !== 'object' ||\n presentation === null ||\n typeof presentation.component !== 'string' ||\n !/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(presentation.component) ||\n !Number.isSafeInteger(presentation.version) ||\n presentation.version <= 0 ||\n typeof presentation.fallbackText !== 'string' ||\n typeof presentation.props !== 'object' ||\n presentation.props === null ||\n Array.isArray(presentation.props)\n ) {\n throw new TypeError('genui: invalid component presentation');\n }\n return presentation as ComponentPresentation;\n });\n}\n\n/** Object order is immaterial; array order remains part of the portable contract. */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;\n if (typeof value === 'object' && value !== null) {\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)\n .join(',')}}`;\n }\n return JSON.stringify(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC2BO,SAASA,iBAAiBC,QAAe;AAC9C,SACE,OAAOA,WAAW,YAClBA,WAAW,QACX,eAAeA,UACf,OAAQA,OAA4B,WAAA,GAAcC,aAAa;AAEnE;AAPgBF;AAeT,SAASG,aAAaF,QAAmB;AAC9C,MAAI,CAACD,iBAAiBC,MAAAA,GAAS;AAC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AAO,IAAIW,OAAOyE,KAAKD,OAAAA,EACpBE,KAAI,EACJjC,IAAI,CAACkC,QAAQ,GAAGpE,KAAKE,UAAUkE,GAAAA,CAAAA,IAAQ9C,cAAc2C,QAAOG,GAAAA,CAAI,CAAA,EAAG,EACnEJ,KAAK,GAAA,CAAA;EACV;AACA,SAAOhE,KAAKE,UAAUpB,KAAAA;AACxB;AAVSwC;","names":["isStandardSchema","schema","validate","toJsonSchema","standard","converter","jsonSchema","undefined","input","target","validateProps","value","validator","result","issues","ok","toGenuiIssues","length","validatePropsSync","Promise","catch","map","issue","path","segment","key","message","formatIssues","formatPath","join","index","ajvValidator","ajv","compiled","WeakMap","fn","get","compile","set","errors","error","instancePath","split","filter","decoded","replace","test","Number","builtinJsonSchemaValidator","check","MAX_DEPTH","typeOf","Array","isArray","matchesType","type","isInteger","isFinite","resolveRef","root","ref","startsWith","current","raw","slice","deepEqual","a","b","keysA","Object","keys","keysB","every","depth","push","s","$ref","types","some","enum","option","JSON","stringify","const","minLength","maxLength","pattern","RegExp","minimum","maximum","minItems","maxItems","items","forEach","item","record","properties","required","entry","entries","additionalProperties","allOf","sub","anyOf","oneOf","options","passing","nested","not","COMPONENT_NAME","defineComponent","definition","test","name","Error","version","undefined","Number","isSafeInteger","RangeError","fallbackText","TypeError","defineCatalog","components","options","byName","Map","component","has","set","buildCatalog","jsonSchemaValidator","builtinJsonSchemaValidator","validator","list","Object","freeze","values","get","modelComponents","filter","internal","validate","props","ok","issues","path","message","result","validateProps","outputProps","validateSync","validatePropsSync","jsonSchemaFor","toJsonSchema","extend","more","next","toSnakeCase","replace","toLowerCase","toolNameFor","prefix","GENUI_TREE_COMPONENT","validateTree","catalog","tree","limits","phase","maxDepth","maxNodes","issues","nodes","visit","node","path","depth","push","message","undefined","Array","isArray","element","type","definition","get","internal","modelComponents","map","component","name","join","validated","validateProps","props","validator","validate","ok","issue","value","rawChildren","parseChildrenIfStringified","children","length","index","child","entries","next","root","treeJsonSchema","properties","enum","description","items","$ref","required","treeToFlatSpec","elements","id","entry","trimmed","trim","startsWith","leadingJsonArray","text","inString","escaped","char","parsed","JSON","parse","slice","componentToText","catalog","component","props","GENUI_TREE_COMPONENT","root","undefined","treeToText","fallback","get","fallbackText","text","trim","length","jsonBlock","out","visit","node","depth","definition","type","push","children","child","filter","line","join","title","JSON","stringify","catalogToModelText","options","mode","lines","modelComponents","schema","toJsonSchema","head","name","toolNameFor","namePrefix","description","summarizeSchema","s","$ref","split","pop","Array","isArray","enum","map","option","const","variants","anyOf","oneOf","variant","types","item","items","test","startsWith","properties","keys","Object","required","Set","fields","key","field","note","has","fillTemplate","template","replace","_match","path","value","getPath","String","source","current","part","Boolean","validateUiCapabilities","value","record","Object","keys","some","key","Array","isArray","components","TypeError","seen","Set","map","component","name","COMPONENT_NAME","test","Number","isSafeInteger","version","has","add","negotiateCatalog","catalog","capabilities","undefined","supported","defineCatalog","filter","entry","jsonSchemaValidator","validator","prepareUiEmission","props","drawable","GENUI_TREE_COMPONENT","Error","validated","validateTree","root","ok","formatIssues","issues","node","type","children","every","versions","Map","collectVersions","set","get","child","kind","fallbackText","treeToText","componentVersions","fromEntries","text","definition","currentVersion","validate","componentToText","GENUI_SHOW_TOOL","genuiTools","catalog","options","tools","mode","treeTool","modelComponents","map","component","componentTool","showTool","undefined","push","scopeOf","input","actor","threadId","tenantRef","tenant","agentName","catalogFor","scope","resolveCatalog","common","roles","terminal","presentation","name","label","title","running","lowerFirst","done","result","kind","describeFor","definition","description","dynamic","inputSchema","permissiveSchema","toJsonSchema","props","type","isStandardSchema","jsonStandardSchema","value","validator","validate","handler","execute","ctx","resolved","modelComponent","Error","validated","validateProps","outputProps","ok","formatIssues","issues","version","describe","negotiateCatalog","uiCapabilities","available","spec","toolNameFor","namePrefix","treeToolName","treeInstructions","catalogToModelText","join","validateTree","treeLimits","root","GENUI_TREE_COMPONENT","length","treeJsonSchema","asyncJsonStandardSchema","showToolJsonSchema","properties","enum","required","validateShow","phase","Array","isArray","path","message","allowed","each","issue","showInstructions","get","internal","id","emitUi","shown","text","toLowerCase","slice","schema","toResult","outcome","vendor","Promise","then","jsonSchema","output","str","description","extra","type","undefined","obj","properties","required","additionalProperties","arr","items","cell","row","s","value","String","heading","props","title","textTable","columns","rows","max","shown","slice","widths","map","column","Math","min","label","length","r","key","format","values","index","padEnd","join","lines","width","repeat","push","lineDiff","before","after","a","split","b","text","op","dp","Array","from","fill","at","i","j","out","bar","n","round","abs","DataTable","defineComponent","name","align","enum","minItems","maxItems","fallbackText","Chart","xKey","series","data","unit","first","point","Number","KpiCards","delta","trend","hint","item","SourceCards","url","snippet","source","Checklist","done","note","Timeline","events","date","event","CodeBlock","language","code","Diff","line","Callout","tone","Stack","direction","gap","children","Card","subtitle","Heading","Text","muted","Badge","Link","pattern","Image","alt","snapshotComponentPresentation","value","seen","Set","check","entry","Number","isFinite","TypeError","has","Array","isArray","Object","getPrototypeOf","prototype","add","item","values","delete","JSON","parse","stringify","createComponent","definition","options","defineComponent","catalog","defineCatalog","factory","props","result","validateProps","validator","ok","Error","name","formatIssues","issues","normalized","portable","validate","canonicalJson","component","version","fallbackText","componentToText","assign","createComponentRegistry","channels","Map","registry","manifest","components","map","jsonSchemaFor","title","description","undefined","register","renderers","extend","set","prepare","presentation","get","validated","render","channel","context","prepared","mapping","renderer","hasOwn","text","table","DataTable","chart","Chart","validatePresentationBatch","presentations","batch","test","isSafeInteger","join","record","keys","sort","key"]}
1
+ {"version":3,"sources":["../../src/genui/index.ts","../../src/genui/schema.ts","../../src/genui/catalog.ts","../../src/genui/tree.ts","../../src/genui/text.ts","../../src/genui/capabilities.ts","../../src/genui/tools.ts","../../src/genui/builtins.ts","../../src/genui/registry.ts"],"sourcesContent":["/**\n * `@dudousxd/nestjs-agent-core/genui` — the generative-UI catalog: component definitions (Standard\n * Schema or JSON Schema props), validation, model-facing catalog text, plain-text fallbacks and the\n * tools that push `ui` frames. Isomorphic: this entry imports nothing server-only, so the same\n * catalog file serves the NestJS app and the browser. Builtin definitions live at\n * `@dudousxd/nestjs-agent-core/genui/builtins`.\n */\nexport {\n type Catalog,\n type CatalogOptions,\n COMPONENT_NAME,\n type ComponentDefinition,\n defineCatalog,\n defineComponent,\n flatComponents,\n toolNameFor,\n toSnakeCase,\n} from './catalog.js';\nexport {\n type AjvLike,\n ajvValidator,\n builtinJsonSchemaValidator,\n formatIssues,\n type GenuiIssue,\n type GenuiValidation,\n isStandardSchema,\n type JsonSchema,\n type JsonSchemaValidator,\n type PropsSchema,\n toJsonSchema,\n validateProps,\n validatePropsSync,\n} from './schema.js';\nexport {\n type CatalogTextOptions,\n catalogToModelText,\n componentToText,\n fillTemplate,\n getPath,\n summarizeSchema,\n treeToText,\n} from './text.js';\nexport {\n GENUI_SHOW_TOOL,\n type GenuiCatalogScope,\n type GenuiTool,\n type GenuiToolOutput,\n type GenuiToolsOptions,\n genuiTools,\n jsonStandardSchema,\n type ResolveGenuiCatalog,\n showToolJsonSchema,\n} from './tools.js';\nexport {\n type FlatSpec,\n GENUI_TREE_COMPONENT,\n type GenuiElement,\n type GenuiTreeProps,\n type TreeLimits,\n treeJsonSchema,\n treeToFlatSpec,\n validateTree,\n} from './tree.js';\n\nexport {\n type UiCapabilities,\n type PreparedUiEmission,\n negotiateCatalog,\n prepareUiEmission,\n validateUiCapabilities,\n} from './capabilities.js';\n\nexport {\n type ComponentPresentation,\n type ComponentFactory,\n type ComponentRenderer,\n type ComponentManifest,\n type ComponentRegistry,\n type TableCell,\n type TableProps,\n type ChartProps,\n createComponent,\n createComponentRegistry,\n snapshotComponentPresentation,\n table,\n chart,\n} from './registry.js';\nexport { validatePresentationBatch } from './registry.js';\n","import type { StandardJSONSchemaV1, StandardSchemaV1 } from '@standard-schema/spec';\n\n/** A JSON Schema document (draft-07 / 2020-12 subset). Plain data, so a catalog can be stored and shipped. */\nexport type JsonSchema = Record<string, unknown>;\n\n/** One problem with a value, addressed by its path from the root of the value. */\nexport interface GenuiIssue {\n path: (string | number)[];\n message: string;\n}\n\nexport type GenuiValidation<T = unknown> =\n | { ok: true; value: T }\n | { ok: false; issues: GenuiIssue[] };\n\n/**\n * Validates a value against a JSON Schema. The package ships {@link builtinJsonSchemaValidator} (a\n * dependency-free subset that covers what component props use); pass {@link ajvValidator} to a\n * catalog for full JSON Schema.\n */\nexport interface JsonSchemaValidator {\n validate(schema: JsonSchema, value: unknown): GenuiIssue[];\n}\n\n/** A component's props schema: any Standard Schema (Zod, Valibot, ArkType) or a JSON Schema object. */\nexport type PropsSchema = StandardSchemaV1 | JsonSchema;\n\nexport function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n return (\n typeof schema === 'object' &&\n schema !== null &&\n '~standard' in schema &&\n typeof (schema as StandardSchemaV1)['~standard']?.validate === 'function'\n );\n}\n\n/**\n * The JSON Schema a props schema presents to a model: the schema itself for a JSON Schema, the\n * Standard JSON Schema converter's output for a Standard Schema that has one (Zod 4, Valibot,\n * ArkType). `undefined` when neither is available (e.g. Zod 3) — the model then gets the\n * component's description only.\n */\nexport function toJsonSchema(schema: PropsSchema): JsonSchema | undefined {\n if (!isStandardSchema(schema)) {\n return schema;\n }\n const standard = schema['~standard'] as StandardSchemaV1['~standard'] &\n Partial<StandardJSONSchemaV1['~standard']>;\n const converter = standard.jsonSchema;\n if (converter === undefined || typeof converter.input !== 'function') {\n return undefined;\n }\n try {\n return converter.input({ target: 'draft-07' });\n } catch {\n return undefined;\n }\n}\n\n/** Validate against either kind of props schema. A Standard Schema's own (possibly transformed) output wins. */\nexport async function validateProps(\n schema: PropsSchema,\n value: unknown,\n validator: JsonSchemaValidator,\n): Promise<GenuiValidation> {\n if (isStandardSchema(schema)) {\n const result = await schema['~standard'].validate(value);\n if (result.issues !== undefined) {\n return { ok: false, issues: toGenuiIssues(result.issues) };\n }\n return { ok: true, value: result.value };\n }\n const issues = validator.validate(schema, value);\n return issues.length > 0 ? { ok: false, issues } : { ok: true, value };\n}\n\n/**\n * {@link validateProps} without waiting: the verdict when it is available synchronously (always\n * for JSON Schema, and for every Standard Schema whose `validate` does not return a promise — Zod,\n * Valibot and ArkType all answer synchronously for synchronous schemas), `undefined` otherwise. What\n * a renderer uses to decide on its first paint instead of flashing a placeholder.\n */\nexport function validatePropsSync(\n schema: PropsSchema,\n value: unknown,\n validator: JsonSchemaValidator,\n): GenuiValidation | undefined {\n if (!isStandardSchema(schema)) {\n const issues = validator.validate(schema, value);\n return issues.length > 0 ? { ok: false, issues } : { ok: true, value };\n }\n const result = schema['~standard'].validate(value);\n if (result instanceof Promise) {\n result.catch(() => undefined);\n return undefined;\n }\n return result.issues !== undefined\n ? { ok: false, issues: toGenuiIssues(result.issues) }\n : { ok: true, value: result.value };\n}\n\nfunction toGenuiIssues(issues: readonly StandardSchemaV1.Issue[]): GenuiIssue[] {\n return issues.map((issue) => ({\n path: (issue.path ?? []).map((segment) =>\n typeof segment === 'object' && segment !== null && 'key' in segment\n ? (segment.key as string | number)\n : (segment as string | number),\n ),\n message: issue.message,\n }));\n}\n\n/** `a.b[0].c: message; …` — what a model is handed back when its props were refused. */\nexport function formatIssues(issues: readonly GenuiIssue[]): string {\n return issues\n .map(\n (issue) => `${issue.path.length > 0 ? formatPath(issue.path) : '(root)'}: ${issue.message}`,\n )\n .join('; ');\n}\n\nfunction formatPath(path: readonly (string | number)[]): string {\n return path\n .map((segment, index) =>\n typeof segment === 'number' ? `[${segment}]` : index === 0 ? segment : `.${segment}`,\n )\n .join('');\n}\n\n/**\n * Structural type of an Ajv instance, so the package never imports Ajv: `new Ajv({ allErrors: true })`\n * satisfies it.\n */\nexport interface AjvLike {\n compile(schema: object): ((data: unknown) => boolean | Promise<unknown>) & {\n errors?: { instancePath?: string; message?: string }[] | null;\n };\n}\n\n/**\n * Full JSON Schema validation through the app's own Ajv instance. Compiled validators are cached\n * per schema object.\n */\nexport function ajvValidator(ajv: AjvLike): JsonSchemaValidator {\n const compiled = new WeakMap<object, ReturnType<AjvLike['compile']>>();\n return {\n validate(schema, value) {\n let fn = compiled.get(schema);\n if (fn === undefined) {\n fn = ajv.compile(schema);\n compiled.set(schema, fn);\n }\n if (fn(value) === true) {\n return [];\n }\n return (fn.errors ?? []).map((error) => ({\n path: (error.instancePath ?? '')\n .split('/')\n .filter((segment) => segment.length > 0)\n .map((segment) => {\n const decoded = segment.replace(/~1/g, '/').replace(/~0/g, '~');\n return /^\\d+$/.test(decoded) ? Number(decoded) : decoded;\n }),\n message: error.message ?? 'is invalid',\n }));\n },\n };\n}\n\n/**\n * A dependency-free JSON Schema validator for the keywords component props actually use: `type`\n * (incl. `integer`, `null`, type arrays), `enum`, `const`, `properties`, `required`,\n * `additionalProperties`, `items`, `minItems`/`maxItems`, `minLength`/`maxLength`/`pattern`,\n * `minimum`/`maximum`, `anyOf`/`oneOf`/`allOf`, `not`, and local `$ref`s (`#`, `#/$defs/…`,\n * `#/definitions/…`). Unknown keywords (e.g. `format`) are ignored. Use {@link ajvValidator} when\n * you need the rest.\n */\nexport const builtinJsonSchemaValidator: JsonSchemaValidator = {\n validate(schema, value) {\n const issues: GenuiIssue[] = [];\n check(schema, value, [], schema, issues, 0);\n return issues;\n },\n};\n\nconst MAX_DEPTH = 64;\n\nfunction typeOf(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n return typeof value;\n}\n\nfunction matchesType(type: string, value: unknown): boolean {\n switch (type) {\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'number':\n return typeof value === 'number' && Number.isFinite(value);\n case 'object':\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n default:\n return typeOf(value) === type;\n }\n}\n\nfunction resolveRef(root: JsonSchema, ref: string): JsonSchema | undefined {\n if (ref === '#') return root;\n if (!ref.startsWith('#/')) return undefined;\n let current: unknown = root;\n for (const raw of ref.slice(2).split('/')) {\n const key = raw.replace(/~1/g, '/').replace(/~0/g, '~');\n if (typeof current !== 'object' || current === null) return undefined;\n current = (current as Record<string, unknown>)[key];\n }\n return typeof current === 'object' && current !== null ? (current as JsonSchema) : undefined;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((key) =>\n deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n );\n}\n\nfunction check(\n schema: unknown,\n value: unknown,\n path: (string | number)[],\n root: JsonSchema,\n issues: GenuiIssue[],\n depth: number,\n): void {\n if (schema === true || schema === undefined) return;\n if (schema === false) {\n issues.push({ path, message: 'is not allowed' });\n return;\n }\n if (typeof schema !== 'object' || schema === null) return;\n if (depth > MAX_DEPTH) {\n issues.push({ path, message: 'is nested too deeply' });\n return;\n }\n const s = schema as Record<string, unknown>;\n\n if (typeof s.$ref === 'string') {\n const target = resolveRef(root, s.$ref);\n if (target === undefined) {\n issues.push({ path, message: `references unknown schema ${s.$ref}` });\n return;\n }\n check(target, value, path, root, issues, depth + 1);\n }\n\n if (s.type !== undefined) {\n const types = Array.isArray(s.type) ? (s.type as string[]) : [s.type as string];\n if (!types.some((type) => matchesType(type, value))) {\n issues.push({ path, message: `must be ${types.join(' or ')}` });\n return;\n }\n }\n if (Array.isArray(s.enum) && !s.enum.some((option) => deepEqual(option, value))) {\n issues.push({\n path,\n message: `must be one of ${s.enum.map((option) => JSON.stringify(option)).join(', ')}`,\n });\n }\n if ('const' in s && !deepEqual(s.const, value)) {\n issues.push({ path, message: `must be ${JSON.stringify(s.const)}` });\n }\n\n if (typeof value === 'string') {\n if (typeof s.minLength === 'number' && value.length < s.minLength) {\n issues.push({ path, message: `must be at least ${s.minLength} characters` });\n }\n if (typeof s.maxLength === 'number' && value.length > s.maxLength) {\n issues.push({ path, message: `must be at most ${s.maxLength} characters` });\n }\n if (typeof s.pattern === 'string') {\n let pattern: RegExp | undefined;\n try {\n pattern = new RegExp(s.pattern, 'u');\n } catch {\n pattern = undefined;\n }\n if (pattern !== undefined && !pattern.test(value)) {\n issues.push({ path, message: `must match ${s.pattern}` });\n }\n }\n }\n if (typeof value === 'number') {\n if (typeof s.minimum === 'number' && value < s.minimum) {\n issues.push({ path, message: `must be >= ${s.minimum}` });\n }\n if (typeof s.maximum === 'number' && value > s.maximum) {\n issues.push({ path, message: `must be <= ${s.maximum}` });\n }\n }\n\n if (Array.isArray(value)) {\n if (typeof s.minItems === 'number' && value.length < s.minItems) {\n issues.push({ path, message: `must have at least ${s.minItems} items` });\n }\n if (typeof s.maxItems === 'number' && value.length > s.maxItems) {\n issues.push({ path, message: `must have at most ${s.maxItems} items` });\n }\n if (s.items !== undefined && !Array.isArray(s.items)) {\n value.forEach((item, index) => {\n check(s.items, item, [...path, index], root, issues, depth + 1);\n });\n }\n }\n\n if (matchesType('object', value)) {\n const record = value as Record<string, unknown>;\n const properties =\n typeof s.properties === 'object' && s.properties !== null\n ? (s.properties as Record<string, unknown>)\n : {};\n if (Array.isArray(s.required)) {\n for (const key of s.required as string[]) {\n if (record[key] === undefined) {\n issues.push({ path: [...path, key], message: 'is required' });\n }\n }\n }\n for (const [key, entry] of Object.entries(record)) {\n if (key in properties) {\n if (entry !== undefined) {\n check(properties[key], entry, [...path, key], root, issues, depth + 1);\n }\n } else if (s.additionalProperties === false) {\n issues.push({ path: [...path, key], message: 'is not a known property' });\n } else if (typeof s.additionalProperties === 'object' && s.additionalProperties !== null) {\n check(s.additionalProperties, entry, [...path, key], root, issues, depth + 1);\n }\n }\n }\n\n if (Array.isArray(s.allOf)) {\n for (const sub of s.allOf) check(sub, value, path, root, issues, depth + 1);\n }\n if (Array.isArray(s.anyOf) || Array.isArray(s.oneOf)) {\n const options = (Array.isArray(s.anyOf) ? s.anyOf : s.oneOf) as unknown[];\n const passing = options.filter((sub) => {\n const nested: GenuiIssue[] = [];\n check(sub, value, path, root, nested, depth + 1);\n return nested.length === 0;\n }).length;\n if (Array.isArray(s.anyOf) ? passing === 0 : passing !== 1) {\n issues.push({\n path,\n message: Array.isArray(s.anyOf)\n ? 'does not match any allowed shape'\n : 'must match exactly one allowed shape',\n });\n }\n }\n if (s.not !== undefined) {\n const nested: GenuiIssue[] = [];\n check(s.not, value, path, root, nested, depth + 1);\n if (nested.length === 0) {\n issues.push({ path, message: 'matches a shape that is not allowed' });\n }\n }\n}\n","import {\n type GenuiValidation,\n type JsonSchema,\n type JsonSchemaValidator,\n type PropsSchema,\n builtinJsonSchemaValidator,\n toJsonSchema,\n validateProps,\n validatePropsSync,\n} from './schema.js';\n\n/**\n * One component a server may push into a conversation. Data only — how it LOOKS is each app's own\n * renderer, looked up by {@link name}. The same definition serves the model (description + props\n * schema), the server (validation), text-only channels ({@link fallbackText}) and the client\n * (validation before rendering).\n */\nexport interface ComponentDefinition<P = Record<string, unknown>> {\n /** Registry key, e.g. `DataTable`. What a `ui` frame's `component` names. */\n name: string;\n /** Human label: \"Data table\". */\n title: string;\n /** Shown to the model: what the component is for and when to use it. */\n description: string;\n /** The props schema: a Standard Schema (Zod, Valibot, ArkType) or a JSON Schema object. */\n props: PropsSchema;\n /** Portable normalized props schema. Required when input transformations are not idempotent. */\n outputProps?: PropsSchema;\n /**\n * The component takes nested elements (a layout: `Stack`, `Card`). Only meaningful in tree mode,\n * where a node's `children` are validated against the catalog too. Such a component gets no\n * `ui__show_*` tool and is not offered by the show tool ({@link flatComponents}), and when its\n * {@link fallbackText} comes out empty it writes no text of its own (its children still do).\n */\n children?: boolean;\n /**\n * Plain text / Slack mrkdwn rendering of these props, for a channel that cannot draw the\n * component. Absent → {@link componentToText} prints the props as JSON.\n */\n fallbackText?: (props: P) => string;\n /**\n * Pushed by the server (e.g. an approval card), never offered to the model. Excluded from\n * {@link catalogToModelText} and from the tool factories.\n */\n internal?: boolean;\n /**\n * Schema version of {@link props}. Stamped on every `ui` frame the component is pushed with, so a\n * client can keep rendering messages persisted under an older shape.\n */\n version?: number;\n}\n\n/** Component names: an identifier a registry key, a tool name and a snake_case slug can all be derived from. */\nexport const COMPONENT_NAME = /^[A-Za-z][A-Za-z0-9]{0,63}$/;\n\n/** Declare a component. Validates the name and returns the definition unchanged (typed). */\nexport function defineComponent<P = Record<string, unknown>>(\n definition: ComponentDefinition<P>,\n): ComponentDefinition<P> {\n if (!COMPONENT_NAME.test(definition.name)) {\n throw new Error(\n `genui: component name \"${definition.name}\" must be letters and digits, starting with a letter (e.g. DataTable)`,\n );\n }\n if (\n definition.version !== undefined &&\n (!Number.isSafeInteger(definition.version) || definition.version <= 0)\n )\n throw new RangeError('genui: component version must be a positive safe integer');\n if (definition.fallbackText !== undefined && typeof definition.fallbackText !== 'function')\n throw new TypeError('genui: fallbackText must be a function');\n return definition;\n}\n\nexport interface CatalogOptions {\n /** How JSON Schema props are checked. Default: {@link builtinJsonSchemaValidator}; pass `ajvValidator(new Ajv())` for full JSON Schema. */\n jsonSchemaValidator?: JsonSchemaValidator;\n}\n\n/** An immutable set of component definitions, looked up by name. */\nexport interface Catalog {\n readonly components: readonly ComponentDefinition<any>[];\n readonly validator: JsonSchemaValidator;\n get(name: string): ComponentDefinition<any> | undefined;\n has(name: string): boolean;\n /** The components a model may be offered (every non-`internal` one). */\n modelComponents(): ComponentDefinition<any>[];\n /** Validate `props` for `component`. An unknown component is a validation failure, not a throw. */\n validate(component: string, props: unknown): Promise<GenuiValidation<Record<string, unknown>>>;\n /**\n * {@link validate} without waiting — `undefined` only when the component's Standard Schema\n * validates asynchronously. An unknown component is a failure, as in `validate`.\n */\n validateSync(\n component: string,\n props: unknown,\n ): GenuiValidation<Record<string, unknown>> | undefined;\n /** The component's props as JSON Schema, when it can be derived (see {@link toJsonSchema}). */\n jsonSchemaFor(component: string): JsonSchema | undefined;\n /** A new catalog with these components added (a later definition replaces an earlier one of the same name). */\n extend(components: readonly ComponentDefinition<any>[]): Catalog;\n}\n\n/**\n * The model components a FLAT tool can offer — one whose input is the component's props alone\n * (`ui__show_<name>`, the generic show tool). A layout component (`children: true`) is left out:\n * those tools have no way to pass it children, so it would only ever draw an empty box. Tree mode\n * offers every model component.\n */\nexport function flatComponents(catalog: Catalog): ComponentDefinition<any>[] {\n return catalog.modelComponents().filter((component) => component.children !== true);\n}\n\n/**\n * Collect component definitions into a {@link Catalog}. Names must be unique; to override a\n * definition (e.g. a builtin), use {@link Catalog.extend}.\n */\nexport function defineCatalog(\n components: readonly ComponentDefinition<any>[],\n options: CatalogOptions = {},\n): Catalog {\n const byName = new Map<string, ComponentDefinition<any>>();\n for (const component of components) {\n defineComponent(component);\n if (byName.has(component.name)) {\n throw new Error(`genui: component \"${component.name}\" is defined twice in one catalog`);\n }\n byName.set(component.name, component);\n }\n return buildCatalog(byName, options.jsonSchemaValidator ?? builtinJsonSchemaValidator);\n}\n\nfunction buildCatalog(\n byName: Map<string, ComponentDefinition<any>>,\n validator: JsonSchemaValidator,\n): Catalog {\n const list = Object.freeze([...byName.values()]);\n return {\n components: list,\n validator,\n get: (name) => byName.get(name),\n has: (name) => byName.has(name),\n modelComponents: () => list.filter((component) => component.internal !== true),\n async validate(component, props) {\n const definition = byName.get(component);\n if (definition === undefined) {\n return {\n ok: false,\n issues: [{ path: [], message: `unknown component \"${component}\"` }],\n };\n }\n const result = await validateProps(\n definition.outputProps ?? definition.props,\n props,\n validator,\n );\n return result as GenuiValidation<Record<string, unknown>>;\n },\n validateSync(component, props) {\n const definition = byName.get(component);\n if (definition === undefined) {\n return {\n ok: false,\n issues: [{ path: [], message: `unknown component \"${component}\"` }],\n };\n }\n return validatePropsSync(definition.outputProps ?? definition.props, props, validator) as\n | GenuiValidation<Record<string, unknown>>\n | undefined;\n },\n jsonSchemaFor(component) {\n const definition = byName.get(component);\n return definition === undefined\n ? undefined\n : toJsonSchema(definition.outputProps ?? definition.props);\n },\n extend(more) {\n const next = new Map(byName);\n for (const component of more) {\n defineComponent(component);\n next.set(component.name, component);\n }\n return buildCatalog(next, validator);\n },\n };\n}\n\n/** `DataTable` → `data_table`, `KPICards` → `kpi_cards`. */\nexport function toSnakeCase(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')\n .replace(/[^a-zA-Z0-9]+/g, '_')\n .toLowerCase();\n}\n\n/** The per-component tool name: `ui__show_data_table` with the default prefix. */\nexport function toolNameFor(component: string, prefix = 'ui__show_'): string {\n return `${prefix}${toSnakeCase(component)}`;\n}\n","import type { Catalog } from './catalog.js';\nimport { type GenuiIssue, type GenuiValidation, type JsonSchema, validateProps } from './schema.js';\n\n/**\n * One node of a composed UI: a catalog component, its props, and — for components declared with\n * `children: true` — nested nodes. The shape json-render calls a \"nested element\", so a tree\n * converts to a json-render flat spec with {@link treeToFlatSpec}.\n */\nexport interface GenuiElement {\n type: string;\n props: Record<string, unknown>;\n children?: GenuiElement[];\n}\n\n/**\n * The `ui` frame component a tree-mode tool pushes: `{ component: GENUI_TREE_COMPONENT, props: {\n * root } }`. Not a valid component name, so it can never collide with a catalog entry.\n */\nexport const GENUI_TREE_COMPONENT = 'genui:tree';\n\n/** Props of a {@link GENUI_TREE_COMPONENT} frame. */\nexport interface GenuiTreeProps {\n root: GenuiElement;\n}\n\nexport interface TreeLimits {\n /** Deepest nesting accepted. Default 12. */\n maxDepth?: number;\n /** Most nodes accepted in one tree. Default 200. */\n maxNodes?: number;\n}\n\n/**\n * Validate a model-composed tree against the catalog: every node's `type` must be a model-facing\n * component, its props must pass that component's schema, and only components declared with\n * `children: true` may have children. Returns the tree with each node's props as its schema\n * produced them (defaults applied by a Standard Schema, for instance).\n *\n * Lenient about one thing models get wrong: a `children` array sent as a JSON STRING (sometimes\n * with a stray trailing `}`) is parsed back into the array the model plainly meant.\n */\nexport async function validateTree(\n catalog: Catalog,\n tree: unknown,\n limits: TreeLimits = {},\n phase: 'input' | 'output' = 'output',\n): Promise<GenuiValidation<GenuiElement>> {\n const maxDepth = limits.maxDepth ?? 12;\n const maxNodes = limits.maxNodes ?? 200;\n const issues: GenuiIssue[] = [];\n let nodes = 0;\n\n const visit = async (\n node: unknown,\n path: (string | number)[],\n depth: number,\n ): Promise<GenuiElement | undefined> => {\n nodes += 1;\n if (nodes > maxNodes) {\n if (nodes === maxNodes + 1) {\n issues.push({ path, message: `the tree has more than ${maxNodes} elements` });\n }\n return undefined;\n }\n if (depth > maxDepth) {\n issues.push({ path, message: `the tree is nested deeper than ${maxDepth} levels` });\n return undefined;\n }\n if (typeof node !== 'object' || node === null || Array.isArray(node)) {\n issues.push({ path, message: 'must be an element object { type, props, children? }' });\n return undefined;\n }\n const element = node as Record<string, unknown>;\n if (typeof element.type !== 'string') {\n issues.push({ path: [...path, 'type'], message: 'must be a component name' });\n return undefined;\n }\n const definition = catalog.get(element.type);\n if (definition === undefined || definition.internal === true) {\n issues.push({\n path: [...path, 'type'],\n message: `unknown component \"${element.type}\" (allowed: ${catalog\n .modelComponents()\n .map((component) => component.name)\n .join(', ')})`,\n });\n return undefined;\n }\n const validated =\n phase === 'input'\n ? ((await validateProps(\n definition.props,\n element.props ?? {},\n catalog.validator,\n )) as GenuiValidation<Record<string, unknown>>)\n : await catalog.validate(element.type, element.props ?? {});\n let props: Record<string, unknown> = {};\n if (!validated.ok) {\n for (const issue of validated.issues) {\n issues.push({ path: [...path, 'props', ...issue.path], message: issue.message });\n }\n } else {\n props = validated.value;\n }\n const rawChildren = parseChildrenIfStringified(element.children);\n if (rawChildren === undefined || rawChildren === null) {\n return { type: element.type, props };\n }\n if (!Array.isArray(rawChildren)) {\n issues.push({\n path: [...path, 'children'],\n message: 'must be an array of elements (a literal array, not a string)',\n });\n return undefined;\n }\n if (rawChildren.length > 0 && definition.children !== true) {\n issues.push({\n path: [...path, 'children'],\n message: `${element.type} does not take children`,\n });\n return undefined;\n }\n const children: GenuiElement[] = [];\n for (const [index, child] of rawChildren.entries()) {\n const next = await visit(child, [...path, 'children', index], depth + 1);\n if (next !== undefined) {\n children.push(next);\n }\n }\n return children.length > 0\n ? { type: element.type, props, children }\n : { type: element.type, props };\n };\n\n const root = await visit(tree, [], 1);\n return issues.length > 0 || root === undefined\n ? { ok: false, issues: issues.length > 0 ? issues : [{ path: [], message: 'is invalid' }] }\n : { ok: true, value: root };\n}\n\n/**\n * The JSON Schema of a tree-mode tool's input: a recursive `{ type, props, children? }` node whose\n * `type` is one of the catalog's model-facing component names. Per-component props are described\n * to the model in the tool description (see `catalogToModelText`) and checked by\n * {@link validateTree}, which keeps this schema small enough for every provider.\n */\nexport function treeJsonSchema(catalog: Catalog): JsonSchema {\n return {\n type: 'object',\n properties: {\n type: {\n type: 'string',\n enum: catalog.modelComponents().map((component) => component.name),\n description: 'Component name from the catalog',\n },\n props: {\n type: 'object',\n description: \"The component's props, as the catalog describes them\",\n },\n children: {\n type: 'array',\n items: { $ref: '#' },\n description:\n 'Nested elements, only for components that take children. A literal JSON array, never a JSON-stringified one.',\n },\n },\n required: ['type', 'props'],\n };\n}\n\n/** A json-render flat spec: `{ root, elements: { [id]: { type, props, children: id[] } } }`. */\nexport interface FlatSpec {\n root: string;\n elements: Record<string, { type: string; props: Record<string, unknown>; children: string[] }>;\n}\n\n/** Convert a tree to a json-render flat spec (ids are `el-0`, `el-1`, … in depth-first order). */\nexport function treeToFlatSpec(root: GenuiElement): FlatSpec {\n const elements: FlatSpec['elements'] = {};\n let next = 0;\n const visit = (node: GenuiElement): string => {\n const id = `el-${next++}`;\n const entry = { type: node.type, props: node.props, children: [] as string[] };\n elements[id] = entry;\n for (const child of node.children ?? []) {\n entry.children.push(visit(child));\n }\n return id;\n };\n return { root: visit(root), elements };\n}\n\nfunction parseChildrenIfStringified(value: unknown): unknown {\n if (typeof value !== 'string') return value;\n const trimmed = value.trim();\n if (!trimmed.startsWith('[')) return value;\n return leadingJsonArray(trimmed) ?? value;\n}\n\n/**\n * The array `text` opens with, ignoring what follows: a model that stringifies `children` tends to\n * carry the enclosing object's `}` along, which `JSON.parse` refuses whole.\n */\nfunction leadingJsonArray(text: string): unknown[] | undefined {\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let index = 0; index < text.length; index += 1) {\n const char = text[index];\n if (inString) {\n if (escaped) escaped = false;\n else if (char === '\\\\') escaped = true;\n else if (char === '\"') inString = false;\n continue;\n }\n if (char === '\"') inString = true;\n else if (char === '[' || char === '{') depth += 1;\n else if (char === ']' || char === '}') {\n depth -= 1;\n if (depth === 0) {\n try {\n const parsed: unknown = JSON.parse(text.slice(0, index + 1));\n return Array.isArray(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n }\n }\n }\n return undefined;\n}\n","import { type Catalog, flatComponents, toolNameFor } from './catalog.js';\nimport { type JsonSchema, toJsonSchema } from './schema.js';\nimport { GENUI_TREE_COMPONENT, type GenuiElement } from './tree.js';\n\n/**\n * Plain text (Slack mrkdwn compatible) for a pushed component: its definition's `fallbackText`, or\n * the props as a JSON block when the catalog has no text for it. A tree frame\n * ({@link GENUI_TREE_COMPONENT}) renders node by node. Never throws — a fallback that fails prints\n * the JSON instead. A layout component (`children: true`) whose text comes out empty writes\n * nothing: it has nothing of its own to say, and its props (`direction`, `gap`) are not content.\n */\nexport function componentToText(\n catalog: Catalog,\n component: string,\n props: Record<string, unknown>,\n): string {\n if (component === GENUI_TREE_COMPONENT) {\n const root = props.root as GenuiElement | undefined;\n return root === undefined ? '' : treeToText(catalog, root);\n }\n return ownText(catalog, component, props) ?? '';\n}\n\n/**\n * One component's own text, without its children: its fallback; `undefined` for a layout component\n * with nothing to say; the props as JSON otherwise (no fallback, an empty one, or one that threw).\n */\nfunction ownText(\n catalog: Catalog,\n component: string,\n props: Record<string, unknown>,\n): string | undefined {\n const definition = catalog.get(component);\n const fallback = definition?.fallbackText;\n let failed = false;\n if (fallback !== undefined) {\n try {\n const text = fallback(props);\n if (typeof text === 'string' && text.trim().length > 0) return text;\n } catch {\n failed = true;\n }\n }\n if (definition?.children === true && !failed) return undefined;\n return jsonBlock(props);\n}\n\n/** Plain text for a composed tree: each node's text, depth-first, blank-line free. */\nexport function treeToText(catalog: Catalog, root: GenuiElement): string {\n const out: string[] = [];\n const visit = (node: GenuiElement, depth: number) => {\n if (depth > 32) return;\n const text = ownText(catalog, node.type, node.props);\n if (text !== undefined) out.push(text);\n for (const child of node.children ?? []) visit(child, depth + 1);\n };\n visit(root, 0);\n return out.filter((line) => line.trim().length > 0).join('\\n');\n}\n\nfunction jsonBlock(props: Record<string, unknown>): string {\n const title =\n typeof props.title === 'string' && props.title.length > 0 ? `*${props.title}*\\n` : '';\n return `${title}\\`\\`\\`\\n${JSON.stringify(props, null, 2)}\\n\\`\\`\\``;\n}\n\nexport interface CatalogTextOptions {\n /**\n * `per-component`: each component is its own tool (`ui__show_<snake>`), named in the text.\n * `tree`: one tool takes a nested `{ type, props, children }` tree; the text explains the format.\n * `show`: one tool takes `{ component, props }` (the generic show tool). Default `tree`.\n */\n mode?: 'per-component' | 'tree' | 'show';\n /** Tool-name prefix for `per-component`. Default `ui__show_`. */\n namePrefix?: string;\n}\n\n/**\n * The catalog described for a model: one entry per model-facing component with its description and\n * a compact TypeScript-like signature of its props. What a tree-mode (or show) tool puts in its\n * description, and what a host can add to a system prompt.\n */\nexport function catalogToModelText(catalog: Catalog, options: CatalogTextOptions = {}): string {\n const mode = options.mode ?? 'tree';\n const lines: string[] = [];\n if (mode === 'tree') {\n lines.push(\n 'Compose the UI as ONE tree of elements: { \"type\": <component>, \"props\": { … }, \"children\"?: [ … ] }.',\n 'Only components marked \"takes children\" accept children; `children` is a literal JSON array, never a string.',\n 'Components:',\n );\n } else if (mode === 'show') {\n lines.push('Pass { \"component\": <name>, \"props\": { … } } with one of these components:');\n } else {\n lines.push('Components you can show (one tool each):');\n }\n // Flat modes cannot pass children, so a layout component is not offered there.\n const components = mode === 'tree' ? catalog.modelComponents() : flatComponents(catalog);\n for (const component of components) {\n const schema = toJsonSchema(component.props);\n const head =\n mode === 'per-component'\n ? `- ${component.name} (tool \\`${toolNameFor(component.name, options.namePrefix)}\\`)`\n : `- ${component.name}`;\n lines.push(`${head}: ${component.description}`);\n if (schema !== undefined) {\n lines.push(` props: ${summarizeSchema(schema, schema, 0)}`);\n }\n if (mode === 'tree' && component.children === true) {\n lines.push(' takes children');\n }\n }\n return lines.join('\\n');\n}\n\n/** A JSON Schema as a one-line TypeScript-like type, e.g. `{ title?: string, rows: object[] }`. */\nexport function summarizeSchema(schema: unknown, root: JsonSchema, depth: number): string {\n if (typeof schema !== 'object' || schema === null) return 'unknown';\n const s = schema as Record<string, unknown>;\n if (depth > 5) return '…';\n if (typeof s.$ref === 'string') {\n return s.$ref === '#' ? 'Self' : (s.$ref.split('/').pop() ?? 'unknown');\n }\n if (Array.isArray(s.enum)) {\n return s.enum.map((option) => JSON.stringify(option)).join(' | ');\n }\n if ('const' in s) return JSON.stringify(s.const);\n const variants = (s.anyOf ?? s.oneOf) as unknown[] | undefined;\n if (Array.isArray(variants)) {\n return variants.map((variant) => summarizeSchema(variant, root, depth + 1)).join(' | ');\n }\n const types = Array.isArray(s.type) ? (s.type as string[]) : s.type !== undefined ? [s.type] : [];\n if (types.length > 1) {\n return types.map((type) => summarizeSchema({ ...s, type }, root, depth + 1)).join(' | ');\n }\n const type = types[0] as string | undefined;\n if (type === 'array') {\n const item = s.items === undefined ? 'unknown' : summarizeSchema(s.items, root, depth + 1);\n return /[|\\s]/.test(item) && !item.startsWith('{') ? `(${item})[]` : `${item}[]`;\n }\n if (type === 'object' || (type === undefined && s.properties !== undefined)) {\n const properties = (s.properties ?? {}) as Record<string, unknown>;\n const keys = Object.keys(properties);\n if (keys.length === 0) return 'object';\n const required = new Set(Array.isArray(s.required) ? (s.required as string[]) : []);\n const fields = keys.map((key) => {\n const field = properties[key] as Record<string, unknown> | undefined;\n const note =\n typeof field?.description === 'string' && depth === 0 ? ` /* ${field.description} */` : '';\n return `${key}${required.has(key) ? '' : '?'}: ${summarizeSchema(field, root, depth + 1)}${note}`;\n });\n return `{ ${fields.join(', ')} }`;\n }\n if (type === 'integer') return 'number';\n return type ?? 'unknown';\n}\n\n/** Replace `{{path}}` placeholders with prop values (objects as JSON). */\nexport function fillTemplate(template: string, props: Record<string, unknown>): string {\n return template.replace(/\\{\\{\\s*([\\w.[\\]]+)\\s*\\}\\}/g, (_match, path: string) => {\n const value = getPath(props, path);\n if (value === null || value === undefined) return '';\n return typeof value === 'object' ? JSON.stringify(value) : String(value);\n });\n}\n\n/** Read `a.b[0].c` from a value; `undefined` when any step is missing. */\nexport function getPath(source: unknown, path: string): unknown {\n let current: any = source;\n for (const part of path\n .replace(/\\[(\\d+)\\]/g, '.$1')\n .split('.')\n .filter(Boolean)) {\n if (current === null || current === undefined) return undefined;\n current = current[part];\n }\n return current;\n}\n","import { COMPONENT_NAME, type Catalog, defineCatalog } from './catalog.js';\nimport { formatIssues } from './schema.js';\nimport { componentToText, treeToText } from './text.js';\nimport { GENUI_TREE_COMPONENT, type GenuiElement, validateTree } from './tree.js';\n\n/** Renderer support only. Component definitions and authorization remain server-owned. */\nexport interface UiCapabilities {\n components: Array<{ name: string; version: number }>;\n}\n\nexport function validateUiCapabilities(value: unknown): UiCapabilities {\n if (\n !record(value) ||\n Object.keys(value).some((key) => key !== 'components') ||\n !Array.isArray(value.components)\n )\n throw new TypeError('Invalid UI capabilities');\n const seen = new Set<string>();\n const components = value.components.map((component: unknown) => {\n if (\n !record(component) ||\n Object.keys(component).some((key) => key !== 'name' && key !== 'version') ||\n typeof component.name !== 'string' ||\n !COMPONENT_NAME.test(component.name) ||\n !Number.isSafeInteger(component.version) ||\n Number(component.version) <= 0 ||\n seen.has(component.name)\n )\n throw new TypeError('Invalid UI component capability');\n seen.add(component.name);\n return { name: component.name, version: Number(component.version) };\n });\n return { components };\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function negotiateCatalog(catalog: Catalog, capabilities?: UiCapabilities): Catalog {\n if (capabilities === undefined) return catalog;\n const supported = validateUiCapabilities(capabilities).components;\n return defineCatalog(\n catalog.components.filter((component) =>\n supported.some(\n (entry) => entry.name === component.name && entry.version === (component.version ?? 1),\n ),\n ),\n { jsonSchemaValidator: catalog.validator },\n );\n}\n\nexport type PreparedUiEmission =\n | {\n kind: 'ui';\n component: string;\n props: Record<string, unknown>;\n version: number;\n fallbackText: string;\n componentVersions?: Record<string, number>;\n }\n | { kind: 'text'; text: string };\n\n/** Validate against current trusted definitions before drawing or generating complete text. */\nexport async function prepareUiEmission(\n catalog: Catalog,\n capabilities: UiCapabilities | undefined,\n component: string,\n props: Record<string, unknown>,\n version?: number,\n): Promise<PreparedUiEmission> {\n const drawable = negotiateCatalog(catalog, capabilities);\n if (component === GENUI_TREE_COMPONENT) {\n if (version !== undefined && version !== 1) throw new Error('Invalid UI tree version');\n const validated = await validateTree(catalog, props.root);\n if (!validated.ok) throw new Error(`Invalid UI tree: ${formatIssues(validated.issues)}`);\n const supported = (node: GenuiElement): boolean =>\n drawable.has(node.type) && (node.children ?? []).every(supported);\n const versions = new Map<string, number>();\n const collectVersions = (node: GenuiElement): void => {\n versions.set(node.type, catalog.get(node.type)?.version ?? 1);\n for (const child of node.children ?? []) collectVersions(child);\n };\n collectVersions(validated.value);\n return supported(validated.value)\n ? {\n kind: 'ui',\n component,\n props: { root: validated.value },\n version: 1,\n fallbackText: treeToText(catalog, validated.value),\n componentVersions: Object.fromEntries(versions),\n }\n : { kind: 'text', text: treeToText(catalog, validated.value) };\n }\n const definition = catalog.get(component);\n if (definition === undefined) throw new Error(`Unknown UI component \"${component}\"`);\n const currentVersion = definition.version ?? 1;\n if (version !== undefined && version !== currentVersion)\n throw new Error(`Invalid UI component version for \"${component}\"`);\n const validated = await catalog.validate(component, props);\n if (!validated.ok) throw new Error(`Invalid UI props: ${formatIssues(validated.issues)}`);\n return drawable.has(component)\n ? {\n kind: 'ui',\n component,\n props: validated.value,\n version: currentVersion,\n fallbackText: componentToText(catalog, component, validated.value),\n }\n : { kind: 'text', text: componentToText(catalog, component, validated.value) };\n}\n","import type { StandardJSONSchemaV1, StandardSchemaV1 } from '@standard-schema/spec';\nimport type { AiToolCtx, ToolDescribeScope, ToolDescription, ToolHandler } from '../spi/tool.js';\nimport type { ToolPresentation } from '../tool-presentation.js';\nimport type { Actor, ToolSpec } from '../types.js';\nimport { negotiateCatalog } from './capabilities.js';\nimport { type Catalog, type ComponentDefinition, flatComponents, toolNameFor } from './catalog.js';\nimport {\n type GenuiIssue,\n type JsonSchema,\n formatIssues,\n isStandardSchema,\n toJsonSchema,\n validateProps,\n} from './schema.js';\nimport { catalogToModelText } from './text.js';\nimport {\n GENUI_TREE_COMPONENT,\n type GenuiElement,\n type TreeLimits,\n treeJsonSchema,\n validateTree,\n} from './tree.js';\n\n/** A lib tool: register it with `provideAgentTool(tool)` (NestJS) or `registry.register(tool.spec, tool.handler)`. */\nexport interface GenuiTool {\n spec: ToolSpec & { terminal?: boolean };\n handler: ToolHandler;\n}\n\n/** What a genui tool returns to the model: what was pushed, and the `ui` frame's id. */\nexport interface GenuiToolOutput {\n shown: string;\n id: string;\n}\n\n/**\n * Who a catalog is being resolved for. `tenant` is `actor.tenantRef`. `threadId` is absent only\n * when a tool list is built outside a conversation (the MCP server's `tools/list`).\n */\nexport interface GenuiCatalogScope {\n actor: Actor;\n threadId?: string;\n tenant?: string;\n agentName?: string;\n}\n\n/** Answers which catalog applies to a request — a tenant's own, versioned components. */\nexport type ResolveGenuiCatalog = (scope: GenuiCatalogScope) => Catalog | Promise<Catalog>;\n\nexport interface GenuiToolsOptions {\n /**\n * `per-component` (default): one tool per model-facing component, `ui__show_<snake>`, whose input\n * IS the component's props — except layout components (`children: true`), which a flat input\n * cannot fill. `tree`: a single tool whose input is a nested\n * `{ type, props, children }` tree composed from the catalog (json-render's nested shape).\n */\n mode?: 'per-component' | 'tree';\n /**\n * The model's turn ends once a genui call succeeds — no further model call to narrate what the UI\n * already shows. Stamped as `spec.terminal`.\n */\n terminal?: boolean;\n /** Tool-name prefix for `per-component`. Default `ui__show_`. */\n namePrefix?: string;\n /** Tool name for `tree`. Default `ui__render`. */\n treeToolName?: string;\n /** Extra text prepended to the tree tool's description (when to call it, house rules). */\n treeInstructions?: string;\n /** Size limits for `tree`. */\n treeLimits?: TreeLimits;\n /**\n * Also offer ONE generic tool taking `{ component, props }`, validated against the (resolved)\n * catalog — how a model reaches components that only exist per request (a tenant's own), which a\n * boot-time tool list cannot name. `true` names it `ui__show`; a string names it.\n */\n showTool?: boolean | string;\n /** Extra text prepended to the show tool's description. */\n showInstructions?: string;\n /** Roles allowed to call the tools (the `ToolSpec.roles` gate). Undefined → the roles policy default. */\n roles?: string[];\n /** Override the generated presentation per component (or for the tree / show tool, under its tool name). */\n presentation?: (component: string) => ToolPresentation | undefined;\n /**\n * The catalog for THIS request, consulted when a call is validated and when the turn's tool list\n * is described to the model. The `catalog` argument is then the boot-time one: it names the\n * per-component tools and is what a list built without a resolver would show. Omit → the\n * `catalog` argument serves every request.\n */\n resolveCatalog?: ResolveGenuiCatalog;\n}\n\n/** The default name of the generic show tool ({@link GenuiToolsOptions.showTool}). */\nexport const GENUI_SHOW_TOOL = 'ui__show';\n\n/**\n * Tools that let a model push catalog components into the conversation as `ui` frames. Each call\n * validates its input against the catalog (a refused call reaches the model as a tool error it can\n * fix) and then pushes through `ctx.emitUi`, which streams the frame live and persists it on the\n * assistant message.\n */\nexport function genuiTools(catalog: Catalog, options: GenuiToolsOptions = {}): GenuiTool[] {\n const tools =\n options.mode === 'tree'\n ? [treeTool(catalog, options)]\n : flatComponents(catalog).map((component) => componentTool(catalog, component, options));\n if (options.showTool !== undefined && options.showTool !== false) {\n tools.push(showTool(catalog, options));\n }\n return tools;\n}\n\nfunction scopeOf(input: {\n actor: Actor;\n threadId?: string;\n agentName?: string;\n}): GenuiCatalogScope {\n return {\n actor: input.actor,\n ...(input.threadId !== undefined ? { threadId: input.threadId } : {}),\n ...(input.actor.tenantRef !== undefined ? { tenant: input.actor.tenantRef } : {}),\n ...(input.agentName !== undefined ? { agentName: input.agentName } : {}),\n };\n}\n\nfunction catalogFor(\n catalog: Catalog,\n options: GenuiToolsOptions,\n scope: GenuiCatalogScope,\n): Catalog | Promise<Catalog> {\n return options.resolveCatalog === undefined ? catalog : options.resolveCatalog(scope);\n}\n\nfunction common(options: GenuiToolsOptions): Pick<ToolSpec, 'roles'> & { terminal?: boolean } {\n return {\n ...(options.roles !== undefined ? { roles: options.roles } : {}),\n ...(options.terminal === true ? { terminal: true } : {}),\n };\n}\n\nfunction componentTool(\n catalog: Catalog,\n component: ComponentDefinition<any>,\n options: GenuiToolsOptions,\n): GenuiTool {\n const presentation = options.presentation?.(component.name) ?? {\n label: component.title,\n running: `Showing ${lowerFirst(component.title)}`,\n done: `Showed ${lowerFirst(component.title)}`,\n result: { kind: 'elsewhere' as const },\n };\n const describeFor = (definition: ComponentDefinition<any>) =>\n `Show the user a ${definition.title} (${definition.name}). ${definition.description}`;\n const dynamic = options.resolveCatalog !== undefined;\n // With a resolver the component's schema may differ per request (a tenant's version of it), so\n // the registry lets any object through and `execute` validates against the resolved definition.\n const inputSchema: StandardSchemaV1 = dynamic\n ? permissiveSchema(toJsonSchema(component.props) ?? { type: 'object' })\n : isStandardSchema(component.props)\n ? component.props\n : jsonStandardSchema(component.props, (value) =>\n catalog.validator.validate(component.props as JsonSchema, value),\n );\n const handler: ToolHandler = {\n async execute(input: unknown, ctx: AiToolCtx): Promise<GenuiToolOutput> {\n const resolved = await catalogFor(catalog, options, scopeOf(ctx));\n const definition = flatComponent(resolved, component.name);\n if (definition === undefined) {\n throw new Error(`component \"${component.name}\" is not available here`);\n }\n // Static handlers receive the registry's parsed output; dynamic handlers parse the\n // request-specific input here. Never run an input transformation on portable output.\n const validated = await validateProps(\n dynamic ? definition.props : (definition.outputProps ?? definition.props),\n input,\n resolved.validator,\n );\n if (!validated.ok) {\n throw new Error(`invalid ${component.name} props: ${formatIssues(validated.issues)}`);\n }\n return push(\n ctx,\n component.name,\n validated.value as Record<string, unknown>,\n definition.version,\n );\n },\n };\n handler.describe = async (scope: ToolDescribeScope): Promise<ToolDescription> => {\n const resolved = negotiateCatalog(\n await catalogFor(catalog, options, scopeOf(scope)),\n scope.uiCapabilities,\n );\n const definition = flatComponent(resolved, component.name);\n if (definition === undefined) {\n return {\n available: false,\n description: `Not available in this conversation — do not call this tool. (${component.name})`,\n };\n }\n return {\n description: describeFor(definition),\n inputSchema: permissiveSchema(toJsonSchema(definition.props) ?? { type: 'object' }),\n };\n };\n return {\n spec: {\n name: toolNameFor(component.name, options.namePrefix),\n kind: 'read',\n description: describeFor(component),\n inputSchema,\n presentation,\n ...common(options),\n },\n handler,\n };\n}\n\nfunction treeTool(catalog: Catalog, options: GenuiToolsOptions): GenuiTool {\n const name = options.treeToolName ?? 'ui__render';\n const presentation = options.presentation?.(name) ?? {\n label: 'Answer',\n running: 'Laying out the answer',\n done: 'Laid out the answer',\n result: { kind: 'elsewhere' as const },\n };\n const describeFor = (resolved: Catalog) =>\n [\n options.treeInstructions ?? 'Render a rich UI to present the answer to the user.',\n catalogToModelText(resolved, { mode: 'tree' }),\n ].join('\\n');\n const dynamic = options.resolveCatalog !== undefined;\n const handler: ToolHandler = {\n async execute(input: unknown, ctx: AiToolCtx): Promise<GenuiToolOutput> {\n const resolved = await catalogFor(catalog, options, scopeOf(ctx));\n const result = await validateTree(\n resolved,\n input,\n options.treeLimits,\n dynamic ? 'input' : 'output',\n );\n if (!result.ok) {\n throw new Error(`invalid UI tree: ${formatIssues(result.issues)}`);\n }\n const root: GenuiElement = result.value;\n return push(ctx, GENUI_TREE_COMPONENT, { root });\n },\n };\n handler.describe = async (scope: ToolDescribeScope): Promise<ToolDescription> => {\n const resolved = negotiateCatalog(\n await catalogFor(catalog, options, scopeOf(scope)),\n scope.uiCapabilities,\n );\n return {\n available: resolved.modelComponents().length > 0,\n description: describeFor(resolved),\n inputSchema: permissiveSchema(treeJsonSchema(resolved)),\n };\n };\n return {\n spec: {\n name,\n kind: 'read',\n description: describeFor(catalog),\n inputSchema: dynamic\n ? permissiveSchema(treeJsonSchema(catalog))\n : asyncJsonStandardSchema(treeJsonSchema(catalog), async (value) => {\n const result = await validateTree(catalog, value, options.treeLimits, 'input');\n return result.ok ? { value: result.value } : { issues: result.issues };\n }),\n presentation,\n ...common(options),\n },\n handler,\n };\n}\n\n/** The show tool's input: a component name (one of the catalog's) and its props. */\nexport function showToolJsonSchema(catalog: Catalog): JsonSchema {\n return {\n type: 'object',\n properties: {\n component: {\n type: 'string',\n enum: flatComponents(catalog).map((component) => component.name),\n description: 'Component name from the catalog',\n },\n props: {\n type: 'object',\n description: \"The component's props, as the catalog describes them\",\n },\n },\n required: ['component', 'props'],\n };\n}\n\nasync function validateShow(\n catalog: Catalog,\n input: unknown,\n phase: 'input' | 'output' = 'input',\n): Promise<\n | { ok: true; definition: ComponentDefinition<any>; props: Record<string, unknown> }\n | { ok: false; issues: GenuiIssue[] }\n> {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n return { ok: false, issues: [{ path: [], message: 'must be { component, props }' }] };\n }\n const { component, props } = input as { component?: unknown; props?: unknown };\n if (typeof component !== 'string') {\n return { ok: false, issues: [{ path: ['component'], message: 'must be a component name' }] };\n }\n const definition = flatComponent(catalog, component);\n if (definition === undefined) {\n const allowed = flatComponents(catalog)\n .map((each) => each.name)\n .join(', ');\n return {\n ok: false,\n issues: [\n { path: ['component'], message: `unknown component \"${component}\" (allowed: ${allowed})` },\n ],\n };\n }\n const validated = await validateProps(\n phase === 'input' ? definition.props : (definition.outputProps ?? definition.props),\n props ?? {},\n catalog.validator,\n );\n if (!validated.ok) {\n return {\n ok: false,\n issues: validated.issues.map((issue) => ({ ...issue, path: ['props', ...issue.path] })),\n };\n }\n return { ok: true, definition, props: validated.value as Record<string, unknown> };\n}\n\nfunction showTool(catalog: Catalog, options: GenuiToolsOptions): GenuiTool {\n const name = typeof options.showTool === 'string' ? options.showTool : GENUI_SHOW_TOOL;\n const presentation = options.presentation?.(name) ?? {\n label: 'Show',\n running: 'Preparing a view',\n done: 'Showed a view',\n result: { kind: 'elsewhere' as const },\n };\n const describeFor = (resolved: Catalog) =>\n [\n options.showInstructions ?? 'Show the user one component from the catalog.',\n catalogToModelText(resolved, { mode: 'show' }),\n ].join('\\n');\n const dynamic = options.resolveCatalog !== undefined;\n const handler: ToolHandler = {\n async execute(input: unknown, ctx: AiToolCtx): Promise<GenuiToolOutput> {\n const resolved = await catalogFor(catalog, options, scopeOf(ctx));\n const result = await validateShow(resolved, input, dynamic ? 'input' : 'output');\n if (!result.ok) {\n throw new Error(`invalid ${name} call: ${formatIssues(result.issues)}`);\n }\n return push(ctx, result.definition.name, result.props, result.definition.version);\n },\n };\n handler.describe = async (scope: ToolDescribeScope): Promise<ToolDescription> => {\n const resolved = negotiateCatalog(\n await catalogFor(catalog, options, scopeOf(scope)),\n scope.uiCapabilities,\n );\n return {\n available: flatComponents(resolved).length > 0,\n description: describeFor(resolved),\n inputSchema: permissiveSchema(showToolJsonSchema(resolved)),\n };\n };\n return {\n spec: {\n name,\n kind: 'read',\n description: describeFor(catalog),\n inputSchema: dynamic\n ? permissiveSchema(showToolJsonSchema(catalog))\n : asyncJsonStandardSchema(showToolJsonSchema(catalog), async (value) => {\n const result = await validateShow(catalog, value);\n return result.ok\n ? { value: { component: result.definition.name, props: result.props } }\n : { issues: result.issues };\n }),\n presentation,\n ...common(options),\n },\n handler,\n };\n}\n\n/** A component a flat tool may push: offered to the model, and not a layout (see {@link flatComponents}). */\nfunction flatComponent(catalog: Catalog, name: string): ComponentDefinition<any> | undefined {\n const definition = catalog.get(name);\n return definition === undefined || definition.internal === true || definition.children === true\n ? undefined\n : definition;\n}\n\nasync function push(\n ctx: AiToolCtx,\n component: string,\n props: Record<string, unknown>,\n version?: number,\n): Promise<GenuiToolOutput> {\n const { id } = await ctx.emitUi(component, props, version !== undefined ? { version } : {});\n return { shown: component, id };\n}\n\nfunction lowerFirst(text: string): string {\n return text.length > 0 ? `${text[0]?.toLowerCase()}${text.slice(1)}` : text;\n}\n\ntype JsonStandardSchema = StandardSchemaV1 & StandardJSONSchemaV1;\n\n/**\n * A JSON Schema presented as a Standard Schema WITH the Standard JSON Schema extension, so the lib\n * validates tool input through `~standard.validate` and the AI SDK adapter hands the model the\n * schema itself (it reads `~standard.jsonSchema.input`).\n */\nexport function jsonStandardSchema(\n schema: JsonSchema,\n validate: (value: unknown) => GenuiIssue[],\n): JsonStandardSchema {\n return asyncJsonStandardSchema(schema, (value) => {\n const issues = validate(value);\n return issues.length > 0 ? { issues } : { value };\n });\n}\n\n/** Shows the model `schema`, accepts any value: validation happens in `execute`, per request. */\nfunction permissiveSchema(schema: JsonSchema): JsonStandardSchema {\n return asyncJsonStandardSchema(schema, (value) => ({ value }));\n}\n\nfunction asyncJsonStandardSchema(\n schema: JsonSchema,\n validate: (\n value: unknown,\n ) =>\n | { value: unknown; issues?: undefined }\n | { issues: GenuiIssue[] }\n | Promise<{ value: unknown; issues?: undefined } | { issues: GenuiIssue[] }>,\n): JsonStandardSchema {\n const toResult = (\n outcome: { value: unknown; issues?: undefined } | { issues: GenuiIssue[] },\n ): StandardSchemaV1.Result<unknown> =>\n outcome.issues !== undefined\n ? {\n issues: outcome.issues.map((issue) => ({ message: issue.message, path: issue.path })),\n }\n : { value: (outcome as { value: unknown }).value };\n return {\n '~standard': {\n version: 1,\n vendor: 'nestjs-agent-genui',\n validate(value) {\n const outcome = validate(value);\n return outcome instanceof Promise ? outcome.then(toResult) : toResult(outcome);\n },\n jsonSchema: {\n input: () => schema,\n output: () => schema,\n },\n },\n } as JsonStandardSchema;\n}\n","/**\n * Optional builtin component DEFINITIONS — names, props schemas, model descriptions and plain-text\n * fallbacks for the components most chat apps want. No visuals: an app renders each with its own\n * look, keyed by name. Use them as-is, pick some, or extend them:\n *\n * ```ts\n * const catalog = defineCatalog([...BUILTIN_COMPONENTS, ...LAYOUT_COMPONENTS, myDealCard]);\n * ```\n */\nimport { type ComponentDefinition, defineComponent } from './catalog.js';\nimport type { JsonSchema } from './schema.js';\n\ntype Props = Record<string, any>;\n\nconst str = (description?: string, extra: JsonSchema = {}): JsonSchema => ({\n type: 'string',\n ...(description !== undefined ? { description } : {}),\n ...extra,\n});\nconst obj = (properties: Record<string, JsonSchema>, required: string[] = []): JsonSchema => ({\n type: 'object',\n properties,\n required,\n additionalProperties: false,\n});\nconst arr = (items: JsonSchema, extra: JsonSchema = {}): JsonSchema => ({\n type: 'array',\n items,\n ...extra,\n});\nconst cell: JsonSchema = { type: ['string', 'number', 'boolean', 'null'] };\nconst row: JsonSchema = { type: 'object', additionalProperties: cell };\n\nconst s = (value: unknown): string => (value === null || value === undefined ? '' : String(value));\nconst heading = (props: Props): string => (props.title ? `*${s(props.title)}*\\n` : '');\n\n/** A fixed-width text table in a code block, at most `max` rows. */\nexport function textTable(\n columns: readonly { key: string; label: string }[],\n rows: readonly Props[],\n max = 15,\n): string {\n const shown = rows.slice(0, max);\n const widths = columns.map((column) =>\n Math.min(28, Math.max(column.label.length, ...shown.map((r) => s(r[column.key]).length))),\n );\n const format = (values: string[]) =>\n values\n .map((value, index) => value.slice(0, widths[index]).padEnd(widths[index] ?? 0))\n .join(' ');\n const lines = [\n format(columns.map((column) => column.label)),\n widths.map((width) => '-'.repeat(width)).join(' '),\n ...shown.map((r) => format(columns.map((column) => s(r[column.key])))),\n ];\n if (rows.length > max) lines.push(`… ${rows.length - max} more rows`);\n return `\\`\\`\\`\\n${lines.join('\\n')}\\n\\`\\`\\``;\n}\n\nexport interface DiffLine {\n op: 'same' | 'add' | 'del';\n text: string;\n}\n\n/** Line diff (LCS) — good enough for snippets up to a few hundred lines. */\nexport function lineDiff(before: string, after: string): DiffLine[] {\n const a = before.split('\\n');\n const b = after.split('\\n');\n if (a.length * b.length > 250_000) {\n return [\n ...a.map((text) => ({ op: 'del' as const, text })),\n ...b.map((text) => ({ op: 'add' as const, text })),\n ];\n }\n const dp: number[][] = Array.from({ length: a.length + 1 }, () =>\n new Array<number>(b.length + 1).fill(0),\n );\n const at = (i: number, j: number): number => dp[i]?.[j] ?? 0;\n for (let i = a.length - 1; i >= 0; i--) {\n for (let j = b.length - 1; j >= 0; j--) {\n (dp[i] as number[])[j] =\n a[i] === b[j] ? at(i + 1, j + 1) + 1 : Math.max(at(i + 1, j), at(i, j + 1));\n }\n }\n const out: DiffLine[] = [];\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length) {\n if (a[i] === b[j]) {\n out.push({ op: 'same', text: a[i] as string });\n i++;\n j++;\n } else if (at(i + 1, j) >= at(i, j + 1)) {\n out.push({ op: 'del', text: a[i++] as string });\n } else {\n out.push({ op: 'add', text: b[j++] as string });\n }\n }\n while (i < a.length) out.push({ op: 'del', text: a[i++] as string });\n while (j < b.length) out.push({ op: 'add', text: b[j++] as string });\n return out;\n}\n\nfunction bar(value: number, max: number, width = 20): string {\n const n = max > 0 ? Math.round((Math.abs(value) / max) * width) : 0;\n return '█'.repeat(n) || '▏';\n}\n\nexport const DataTable = defineComponent<Props>({\n name: 'DataTable',\n title: 'Data table',\n description:\n 'Tabular data (records with the same fields) as a sortable table. Prefer it over markdown tables for more than 3 rows.',\n props: obj(\n {\n title: str('Short caption'),\n columns: arr(\n obj(\n {\n key: str('Field name in each row'),\n label: str('Column header'),\n align: str(undefined, { enum: ['left', 'right', 'center'] }),\n format: str('How to format values', {\n enum: ['text', 'number', 'currency', 'percent', 'date', 'link'],\n }),\n },\n ['key', 'label'],\n ),\n { minItems: 1, maxItems: 12 },\n ),\n rows: arr(row, { maxItems: 500 }),\n },\n ['columns', 'rows'],\n ),\n fallbackText: (props) => `${heading(props)}${textTable(props.columns ?? [], props.rows ?? [])}`,\n});\n\nexport const Chart = defineComponent<Props>({\n name: 'Chart',\n title: 'Chart',\n description:\n '`bar` to compare categories, `line` for a trend over time. `data` is a list of points; `xKey` names the category/time field and each series names a numeric field.',\n props: obj(\n {\n type: str('Chart type', { enum: ['bar', 'line'] }),\n title: str(),\n xKey: str('Field of each point used for the x axis'),\n series: arr(obj({ key: str('Numeric field'), label: str() }, ['key']), {\n minItems: 1,\n maxItems: 6,\n }),\n data: arr(row, { minItems: 1, maxItems: 200 }),\n unit: str('Unit shown after values, e.g. `KB` or `%`'),\n },\n ['type', 'xKey', 'series', 'data'],\n ),\n fallbackText: (props) => chartText(props),\n});\n\n/**\n * A chart as text. `line` → a table (x, then one column per series), which keeps every value\n * readable; `bar` → one bar per point, and per series when there are several, all on one scale so\n * bars of different series compare.\n */\nfunction chartText(props: Props): string {\n const series: { key: string; label?: string }[] = (props.series ?? []).filter(\n (each: unknown) => typeof (each as { key?: unknown })?.key === 'string',\n );\n const data: Props[] = props.data ?? [];\n const unit = props.unit ? ` ${s(props.unit)}` : '';\n const labelOf = (each: { key: string; label?: string }) => s(each.label) || each.key;\n if (props.type === 'line') {\n const columns = [\n { key: s(props.xKey), label: s(props.xKey) },\n ...series.map((each) => ({ key: each.key, label: `${labelOf(each)}${unit}` })),\n ];\n return `${heading(props)}${textTable(columns, data, 20)}`;\n }\n const max = Math.max(\n 0,\n ...data.flatMap((point) => series.map((each) => Math.abs(Number(point[each.key]) || 0))),\n );\n const shown = data.slice(0, 20);\n const lines: string[] = [];\n if (series.length <= 1) {\n const key = series[0]?.key ?? '';\n for (const point of shown) {\n lines.push(\n `${s(point[props.xKey]).slice(0, 18).padEnd(18)} ${bar(Number(point[key]) || 0, max)} ${s(point[key])}${unit}`,\n );\n }\n } else {\n const width = Math.min(18, Math.max(...series.map((each) => labelOf(each).length)));\n for (const point of shown) {\n lines.push(s(point[props.xKey]).slice(0, 18));\n for (const each of series) {\n lines.push(\n ` ${labelOf(each).slice(0, width).padEnd(width)} ${bar(Number(point[each.key]) || 0, max)} ${s(point[each.key])}${unit}`,\n );\n }\n }\n }\n if (data.length > shown.length) lines.push(`… ${data.length - shown.length} more points`);\n return `${heading(props)}\\`\\`\\`\\n${lines.join('\\n')}\\n\\`\\`\\``;\n}\n\nexport const KpiCards = defineComponent<Props>({\n name: 'KpiCards',\n title: 'KPI cards',\n description: 'A few key numbers (metrics, totals, counts) as cards.',\n props: obj(\n {\n title: str(),\n items: arr(\n obj(\n {\n label: str(),\n value: { type: ['string', 'number'] },\n delta: str('Change, e.g. `+12%`'),\n trend: str(undefined, { enum: ['up', 'down', 'flat'] }),\n hint: str(),\n },\n ['label', 'value'],\n ),\n { minItems: 1, maxItems: 8 },\n ),\n },\n ['items'],\n ),\n fallbackText: (props) =>\n `${heading(props)}${(props.items ?? [])\n .map(\n (item: Props) =>\n `• *${s(item.label)}:* ${s(item.value)}${item.delta ? ` (${s(item.delta)})` : ''}`,\n )\n .join('\\n')}`,\n});\n\nexport const SourceCards = defineComponent<Props>({\n name: 'SourceCards',\n title: 'Sources',\n description: 'The documents, pages or links an answer is based on, as cards.',\n props: obj(\n {\n title: str(),\n items: arr(\n obj({ title: str(), url: str(), snippet: str(), source: str('e.g. Wiki, GitHub') }, [\n 'title',\n ]),\n { minItems: 1, maxItems: 12 },\n ),\n },\n ['items'],\n ),\n fallbackText: (props) =>\n `${heading(props)}${(props.items ?? [])\n .map(\n (item: Props) =>\n `• ${item.url ? `<${s(item.url)}|${s(item.title)}>` : s(item.title)}${item.source ? ` — ${s(item.source)}` : ''}`,\n )\n .join('\\n')}`,\n});\n\nexport const Checklist = defineComponent<Props>({\n name: 'Checklist',\n title: 'Checklist',\n description: 'Steps or a to-do list with done/not-done state.',\n props: obj(\n {\n title: str(),\n items: arr(obj({ label: str(), done: { type: 'boolean' }, note: str() }, ['label']), {\n minItems: 1,\n maxItems: 50,\n }),\n },\n ['items'],\n ),\n fallbackText: (props) =>\n `${heading(props)}${(props.items ?? [])\n .map(\n (item: Props) =>\n `${item.done ? '☑' : '☐'} ${s(item.label)}${item.note ? ` — _${s(item.note)}_` : ''}`,\n )\n .join('\\n')}`,\n});\n\nexport const Timeline = defineComponent<Props>({\n name: 'Timeline',\n title: 'Timeline',\n description: 'Events in chronological order (the history of a project, an incident, a deal).',\n props: obj(\n {\n title: str(),\n events: arr(obj({ date: str(), title: str(), description: str() }, ['title']), {\n minItems: 1,\n maxItems: 50,\n }),\n },\n ['events'],\n ),\n fallbackText: (props) =>\n `${heading(props)}${(props.events ?? [])\n .map(\n (event: Props) =>\n `• ${event.date ? `*${s(event.date)}* ` : ''}${s(event.title)}${event.description ? ` — ${s(event.description)}` : ''}`,\n )\n .join('\\n')}`,\n});\n\nexport const CodeBlock = defineComponent<Props>({\n name: 'CodeBlock',\n title: 'Code',\n description: 'A code snippet or file excerpt with syntax highlighting.',\n props: obj({ title: str(), language: str(), code: str() }, ['code']),\n fallbackText: (props) => `${heading(props)}\\`\\`\\`\\n${s(props.code)}\\n\\`\\`\\``,\n});\n\nexport const Diff = defineComponent<Props>({\n name: 'Diff',\n title: 'Diff',\n description: 'A before/after change to a text or code file, as a line diff.',\n props: obj({ title: str(), language: str(), before: str(), after: str() }, ['before', 'after']),\n fallbackText: (props) =>\n `${heading(props)}\\`\\`\\`\\n${lineDiff(s(props.before), s(props.after))\n .map((line) => `${line.op === 'add' ? '+' : line.op === 'del' ? '-' : ' '} ${line.text}`)\n .join('\\n')}\\n\\`\\`\\``,\n});\n\nexport const Callout = defineComponent<Props>({\n name: 'Callout',\n title: 'Callout',\n description: 'A short note, warning or success message, emphasized.',\n props: obj(\n {\n tone: str(undefined, { enum: ['info', 'success', 'warning', 'danger'] }),\n title: str(),\n text: str(),\n },\n ['text'],\n ),\n fallbackText: (props) =>\n `${props.tone === 'warning' || props.tone === 'danger' ? ':warning: ' : ':information_source: '}${heading(props)}${s(props.text)}`,\n});\n\nexport const Stack = defineComponent<Props>({\n name: 'Stack',\n title: 'Stack',\n description: 'Lays its children out vertically (or horizontally with direction=row).',\n props: obj({ direction: str(undefined, { enum: ['column', 'row'] }), gap: { type: 'number' } }),\n children: true,\n fallbackText: () => '',\n});\n\nexport const Card = defineComponent<Props>({\n name: 'Card',\n title: 'Card',\n description: 'A box with an optional title around its children.',\n props: obj({ title: str(), subtitle: str() }),\n children: true,\n fallbackText: (props) =>\n props.title ? `*${s(props.title)}*${props.subtitle ? ` — ${s(props.subtitle)}` : ''}` : '',\n});\n\nexport const Heading = defineComponent<Props>({\n name: 'Heading',\n title: 'Heading',\n description: 'A heading.',\n props: obj({ text: str() }, ['text']),\n fallbackText: (props) => `*${s(props.text)}*`,\n});\n\nexport const Text = defineComponent<Props>({\n name: 'Text',\n title: 'Text',\n description: 'A paragraph of plain text (no markdown).',\n props: obj({ text: str(), muted: { type: 'boolean' } }, ['text']),\n fallbackText: (props) => s(props.text),\n});\n\nexport const Badge = defineComponent<Props>({\n name: 'Badge',\n title: 'Badge',\n description: 'A small label.',\n props: obj(\n {\n text: str(),\n tone: str(undefined, { enum: ['neutral', 'brand', 'success', 'warning', 'danger'] }),\n },\n ['text'],\n ),\n fallbackText: (props) => `[${s(props.text)}]`,\n});\n\nexport const Link = defineComponent<Props>({\n name: 'Link',\n title: 'Link',\n description: 'A link to an http(s) URL.',\n props: obj({ text: str(), url: str(undefined, { pattern: '^https?://' }) }, ['text', 'url']),\n fallbackText: (props) => `<${s(props.url)}|${s(props.text || props.url)}>`,\n});\n\nexport const Image = defineComponent<Props>({\n name: 'Image',\n title: 'Image',\n description: 'An image from an https URL.',\n props: obj({ url: str(undefined, { pattern: '^https://' }), alt: str() }, ['url']),\n fallbackText: (props) => s(props.url),\n});\n\n/** Content components: data a model shows. */\nexport const BUILTIN_COMPONENTS: readonly ComponentDefinition<Props>[] = [\n DataTable,\n Chart,\n KpiCards,\n SourceCards,\n Checklist,\n Timeline,\n CodeBlock,\n Diff,\n Callout,\n];\n\n/** Layout and text primitives, mostly for composing trees (`Stack`, `Card` take children). */\nexport const LAYOUT_COMPONENTS: readonly ComponentDefinition<Props>[] = [\n Stack,\n Card,\n Heading,\n Text,\n Badge,\n Link,\n Image,\n];\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { Chart, DataTable } from './builtins.js';\nimport {\n type Catalog,\n type CatalogOptions,\n type ComponentDefinition,\n defineCatalog,\n defineComponent,\n} from './catalog.js';\nimport { type JsonSchema, formatIssues, validateProps } from './schema.js';\nimport { componentToText } from './text.js';\n\n/** Plain, durable data. Renderer functions and binary attachments never enter a UI frame. */\nexport interface ComponentPresentation<P = Record<string, unknown>> {\n component: string;\n props: P;\n version: number;\n fallbackText: string;\n}\n\nexport interface ComponentFactory<Input, Output = Input> {\n (props: Input): Promise<ComponentPresentation<Output>>;\n readonly definition: ComponentDefinition<Output>;\n}\n\n/** Reject values JSON would silently discard/coerce, and detach from caller-owned objects. */\nexport function snapshotComponentPresentation<T>(value: T): T {\n const seen = new Set<object>();\n const check = (entry: unknown): void => {\n if (entry === null || typeof entry === 'string' || typeof entry === 'boolean') return;\n if (typeof entry === 'number' && Number.isFinite(entry)) return;\n if (typeof entry !== 'object' || entry === null)\n throw new TypeError('genui: presentation must contain only JSON values');\n if (seen.has(entry))\n throw new TypeError('genui: presentation must contain acyclic JSON values');\n if (\n !Array.isArray(entry) &&\n Object.getPrototypeOf(entry) !== Object.prototype &&\n Object.getPrototypeOf(entry) !== null\n )\n throw new TypeError('genui: presentation must contain plain JSON objects');\n seen.add(entry);\n for (const item of Object.values(entry)) check(item);\n seen.delete(entry);\n };\n check(value);\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\nexport function createComponent<S extends StandardSchemaV1>(\n definition: Omit<ComponentDefinition<StandardSchemaV1.InferOutput<S>>, 'props'> & { props: S },\n options?: CatalogOptions,\n): ComponentFactory<StandardSchemaV1.InferInput<S>, StandardSchemaV1.InferOutput<S>>;\nexport function createComponent<P = Record<string, unknown>>(\n definition: ComponentDefinition<P>,\n options?: CatalogOptions,\n): ComponentFactory<P>;\nexport function createComponent<P>(\n definition: ComponentDefinition<P>,\n options: CatalogOptions = {},\n): unknown {\n defineComponent(definition);\n const catalog = defineCatalog([definition], options);\n const factory = async (props: unknown): Promise<ComponentPresentation> => {\n const result = await validateProps(definition.props, props, catalog.validator);\n if (!result.ok)\n throw new Error(`genui: invalid ${definition.name} props: ${formatIssues(result.issues)}`);\n const normalized = snapshotComponentPresentation(result.value);\n if (typeof normalized !== 'object' || normalized === null || Array.isArray(normalized))\n throw new TypeError('genui: component props must be a JSON object');\n const portable = await catalog.validate(definition.name, normalized);\n if (\n !portable.ok ||\n canonicalJson(snapshotComponentPresentation(portable.value)) !== canonicalJson(normalized)\n ) {\n throw new Error(\n `genui: ${definition.name} requires outputProps accepting stable normalized JSON props`,\n );\n }\n return {\n component: definition.name,\n props: normalized as Record<string, unknown>,\n version: definition.version ?? 1,\n fallbackText: componentToText(\n catalog,\n definition.name,\n normalized as Record<string, unknown>,\n ),\n };\n };\n return Object.assign(factory, { definition });\n}\n\nexport type ComponentRenderer<P = Record<string, unknown>, Context = unknown> = (\n props: P,\n context?: Context,\n) => unknown | Promise<unknown>;\n\nexport interface ComponentManifest {\n name: string;\n title: string;\n description: string;\n version: number;\n props?: JsonSchema;\n}\n\nexport interface ComponentRegistry<Context = unknown> {\n readonly catalog: Catalog;\n readonly manifest: readonly ComponentManifest[];\n register<P>(\n definition: ComponentDefinition<P>,\n renderers: Record<string, ComponentRenderer<P, Context>>,\n ): this;\n /** Revalidate against the app's authoritative definition and regenerate trusted fallback text. */\n prepare(presentation: ComponentPresentation): Promise<ComponentPresentation>;\n render(presentation: ComponentPresentation, channel: string, context?: Context): Promise<unknown>;\n}\n\n/** A registry is owned by one app/tenant; registering never mutates a shared singleton. */\nexport function createComponentRegistry<Context = unknown>(\n options: CatalogOptions = {},\n): ComponentRegistry<Context> {\n let catalog = defineCatalog([], options);\n const channels = new Map<string, Record<string, ComponentRenderer<never, Context>>>();\n const registry: ComponentRegistry<Context> = {\n get catalog() {\n return catalog;\n },\n get manifest() {\n return catalog.components.map((definition) => {\n const props = catalog.jsonSchemaFor(definition.name);\n return {\n name: definition.name,\n title: definition.title,\n description: definition.description,\n version: definition.version ?? 1,\n ...(props === undefined ? {} : { props: snapshotComponentPresentation(props) }),\n };\n });\n },\n register(definition, renderers) {\n if (catalog.has(definition.name))\n throw new Error(`genui: component \"${definition.name}\" is already registered`);\n catalog = catalog.extend([definition]);\n channels.set(definition.name, { ...renderers } as Record<\n string,\n ComponentRenderer<never, Context>\n >);\n return this;\n },\n async prepare(presentation) {\n const definition = catalog.get(presentation.component);\n if (definition === undefined)\n throw new Error(`genui: unknown component \"${presentation.component}\"`);\n if (presentation.version !== (definition.version ?? 1))\n throw new Error(`genui: component \"${presentation.component}\" version mismatch`);\n const validated = await catalog.validate(presentation.component, presentation.props);\n if (!validated.ok)\n throw new Error(\n `genui: invalid ${presentation.component} props: ${formatIssues(validated.issues)}`,\n );\n const props = snapshotComponentPresentation(validated.value);\n if (typeof props !== 'object' || props === null || Array.isArray(props))\n throw new TypeError('genui: component props must be a JSON object');\n return {\n component: definition.name,\n props,\n version: definition.version ?? 1,\n fallbackText: componentToText(catalog, definition.name, props),\n };\n },\n async render(presentation, channel, context) {\n const prepared = await this.prepare(presentation);\n const mapping = channels.get(prepared.component);\n const renderer =\n mapping === undefined\n ? undefined\n : Object.hasOwn(mapping, channel)\n ? mapping[channel]\n : Object.hasOwn(mapping, 'text')\n ? mapping.text\n : undefined;\n return renderer === undefined\n ? prepared.fallbackText\n : renderer(prepared.props as never, context);\n },\n };\n return registry;\n}\n\nexport type TableCell = string | number | boolean | null;\nexport interface TableProps {\n title?: string;\n columns: {\n key: string;\n label: string;\n align?: 'left' | 'right' | 'center';\n format?: 'text' | 'number' | 'currency' | 'percent' | 'date' | 'link';\n }[];\n rows: Record<string, TableCell>[];\n}\nexport interface ChartProps {\n type: 'bar' | 'line';\n title?: string;\n xKey: string;\n series: { key: string; label?: string }[];\n data: Record<string, TableCell>[];\n unit?: string;\n}\n\nexport const table = createComponent<TableProps>(DataTable);\nexport const chart = createComponent<ChartProps>(Chart);\n\n/** Prepare all JSON emissions before any sink receives a partial batch. Factories validate schemas. */\nexport function validatePresentationBatch(\n presentations: ComponentPresentation<object> | readonly ComponentPresentation<object>[],\n): ComponentPresentation[] {\n const batch = Array.isArray(presentations) ? presentations : [presentations];\n return batch.map((item: ComponentPresentation<object>) => {\n const presentation = snapshotComponentPresentation(item);\n if (\n typeof presentation !== 'object' ||\n presentation === null ||\n typeof presentation.component !== 'string' ||\n !/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(presentation.component) ||\n !Number.isSafeInteger(presentation.version) ||\n presentation.version <= 0 ||\n typeof presentation.fallbackText !== 'string' ||\n typeof presentation.props !== 'object' ||\n presentation.props === null ||\n Array.isArray(presentation.props)\n ) {\n throw new TypeError('genui: invalid component presentation');\n }\n return presentation as ComponentPresentation;\n });\n}\n\n/** Object order is immaterial; array order remains part of the portable contract. */\nfunction canonicalJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;\n if (typeof value === 'object' && value !== null) {\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)\n .join(',')}}`;\n }\n return JSON.stringify(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC2BO,SAASA,iBAAiBC,QAAe;AAC9C,SACE,OAAOA,WAAW,YAClBA,WAAW,QACX,eAAeA,UACf,OAAQA,OAA4B,WAAA,GAAcC,aAAa;AAEnE;AAPgBF;AAeT,SAASG,aAAaF,QAAmB;AAC9C,MAAI,CAACD,iBAAiBC,MAAAA,GAAS;AAC7B,WAAOA;EACT;AACA,QAAMG,WAAWH,OAAO,WAAA;AAExB,QAAMI,YAAYD,SAASE;AAC3B,MAAID,cAAcE,UAAa,OAAOF,UAAUG,UAAU,YAAY;AACpE,WAAOD;EACT;AACA,MAAI;AACF,WAAOF,UAAUG,MAAM;MAAEC,QAAQ;IAAW,CAAA;EAC9C,QAAQ;AACN,WAAOF;EACT;AACF;AAfgBJ;AAkBhB,eAAsBO,cACpBT,QACAU,OACAC,WAA8B;AAE9B,MAAIZ,iBAAiBC,MAAAA,GAAS;AAC5B,UAAMY,SAAS,MAAMZ,OAAO,WAAA,EAAaC,SAASS,KAAAA;AAClD,QAAIE,OAAOC,WAAWP,QA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nEJ,KAAK,GAAA,CAAA;EACV;AACA,SAAOhE,KAAKE,UAAUpB,KAAAA;AACxB;AAVSwC;","names":["isStandardSchema","schema","validate","toJsonSchema","standard","converter","jsonSchema","undefined","input","target","validateProps","value","validator","result","issues","ok","toGenuiIssues","length","validatePropsSync","Promise","catch","map","issue","path","segment","key","message","formatIssues","formatPath","join","index","ajvValidator","ajv","compiled","WeakMap","fn","get","compile","set","errors","error","instancePath","split","filter","decoded","replace","test","Number","builtinJsonSchemaValidator","check","MAX_DEPTH","typeOf","Array","isArray","matchesType","type","isInteger","isFinite","resolveRef","root","ref","startsWith","current","raw","slice","deepEqual","a","b","keysA","Object","keys","keysB","every","depth","push","s","$ref","types","some","enum","option","JSON","stringify","const","minLength","maxLength","pattern","RegExp","minimum","maximum","minItems","maxItems","items","forEach","item","record","properties","required","entry","entries","additionalProperties","allOf","sub","anyOf","oneOf","options","passing","nested","not","COMPONENT_NAME","defineComponent","definition","test","name","Error","version","undefined","Number","isSafeInteger","RangeError","fallbackText","TypeError","flatComponents","catalog","modelComponents","filter","component","children","defineCatalog","components","options","byName","Map","has","set","buildCatalog","jsonSchemaValidator","builtinJsonSchemaValidator","validator","list","Object","freeze","values","get","internal","validate","props","ok","issues","path","message","result","validateProps","outputProps","validateSync","validatePropsSync","jsonSchemaFor","toJsonSchema","extend","more","next","toSnakeCase","replace","toLowerCase","toolNameFor","prefix","GENUI_TREE_COMPONENT","validateTree","catalog","tree","limits","phase","maxDepth","maxNodes","issues","nodes","visit","node","path","depth","push","message","undefined","Array","isArray","element","type","definition","get","internal","modelComponents","map","component","name","join","validated","validateProps","props","validator","validate","ok","issue","value","rawChildren","parseChildrenIfStringified","children","length","index","child","entries","next","root","treeJsonSchema","properties","enum","description","items","$ref","required","treeToFlatSpec","elements","id","entry","trimmed","trim","startsWith","leadingJsonArray","text","inString","escaped","char","parsed","JSON","parse","slice","componentToText","catalog","component","props","GENUI_TREE_COMPONENT","root","undefined","treeToText","ownText","definition","get","fallback","fallbackText","failed","text","trim","length","children","jsonBlock","out","visit","node","depth","type","push","child","filter","line","join","title","JSON","stringify","catalogToModelText","options","mode","lines","components","modelComponents","flatComponents","schema","toJsonSchema","head","name","toolNameFor","namePrefix","description","summarizeSchema","s","$ref","split","pop","Array","isArray","enum","map","option","const","variants","anyOf","oneOf","variant","types","item","items","test","startsWith","properties","keys","Object","required","Set","fields","key","field","note","has","fillTemplate","template","replace","_match","path","value","getPath","String","source","current","part","Boolean","validateUiCapabilities","value","record","Object","keys","some","key","Array","isArray","components","TypeError","seen","Set","map","component","name","COMPONENT_NAME","test","Number","isSafeInteger","version","has","add","negotiateCatalog","catalog","capabilities","undefined","supported","defineCatalog","filter","entry","jsonSchemaValidator","validator","prepareUiEmission","props","drawable","GENUI_TREE_COMPONENT","Error","validated","validateTree","root","ok","formatIssues","issues","node","type","children","every","versions","Map","collectVersions","set","get","child","kind","fallbackText","treeToText","componentVersions","fromEntries","text","definition","currentVersion","validate","componentToText","GENUI_SHOW_TOOL","genuiTools","catalog","options","tools","mode","treeTool","flatComponents","map","component","componentTool","showTool","undefined","push","scopeOf","input","actor","threadId","tenantRef","tenant","agentName","catalogFor","scope","resolveCatalog","common","roles","terminal","presentation","name","label","title","running","lowerFirst","done","result","kind","describeFor","definition","description","dynamic","inputSchema","permissiveSchema","toJsonSchema","props","type","isStandardSchema","jsonStandardSchema","value","validator","validate","handler","execute","ctx","resolved","flatComponent","Error","validated","validateProps","outputProps","ok","formatIssues","issues","version","describe","negotiateCatalog","uiCapabilities","available","spec","toolNameFor","namePrefix","treeToolName","treeInstructions","catalogToModelText","join","validateTree","treeLimits","root","GENUI_TREE_COMPONENT","modelComponents","length","treeJsonSchema","asyncJsonStandardSchema","showToolJsonSchema","properties","enum","required","validateShow","phase","Array","isArray","path","message","allowed","each","issue","showInstructions","get","internal","children","id","emitUi","shown","text","toLowerCase","slice","schema","toResult","outcome","vendor","Promise","then","jsonSchema","output","str","description","extra","type","undefined","obj","properties","required","additionalProperties","arr","items","cell","row","s","value","String","heading","props","title","textTable","columns","rows","max","shown","slice","widths","map","column","Math","min","label","length","r","key","format","values","index","padEnd","join","lines","width","repeat","push","lineDiff","before","after","a","split","b","text","op","dp","Array","from","fill","at","i","j","out","bar","n","round","abs","DataTable","defineComponent","name","align","enum","minItems","maxItems","fallbackText","Chart","xKey","series","data","unit","chartText","filter","each","labelOf","flatMap","point","Number","KpiCards","delta","trend","hint","item","SourceCards","url","snippet","source","Checklist","done","note","Timeline","events","date","event","CodeBlock","language","code","Diff","line","Callout","tone","Stack","direction","gap","children","Card","subtitle","Heading","Text","muted","Badge","Link","pattern","Image","alt","snapshotComponentPresentation","value","seen","Set","check","entry","Number","isFinite","TypeError","has","Array","isArray","Object","getPrototypeOf","prototype","add","item","values","delete","JSON","parse","stringify","createComponent","definition","options","defineComponent","catalog","defineCatalog","factory","props","result","validateProps","validator","ok","Error","name","formatIssues","issues","normalized","portable","validate","canonicalJson","component","version","fallbackText","componentToText","assign","createComponentRegistry","channels","Map","registry","manifest","components","map","jsonSchemaFor","title","description","undefined","register","renderers","extend","set","prepare","presentation","get","validated","render","channel","context","prepared","mapping","renderer","hasOwn","text","table","DataTable","chart","Chart","validatePresentationBatch","presentations","batch","test","isSafeInteger","join","record","keys","sort","key"]}