Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

create-report-bindings.ts

1,344 lines40.5 KB

1import { z } from 'zod'
2import { convertSchemaToJsonSchema } from '@tanstack/ai'
3import {
4 generateTypeStubs,
5 type ToolBinding,
6 type ToolExecutionContext,
7} from '@tanstack/ai-code-mode'
8import type { UIEvent, ComponentType, WatcherSubscription } from './types'
9import {
10 applyReportUIEvent,
11 getSignalRegistry,
12 addWatcher,
13 removeWatcher,
14 getAllWatchers,
15} from './report-storage'
16import { createHandlerBindings } from './create-handler-bindings'
17​
18// Common schemas for subscription support
19const subscriptionsSchema = z
20 .array(z.string())
21 .optional()
22 .describe(
23 'Signal names this component subscribes to (e.g., ["balances", "transactions"])',
24 )
25const dataSourceSchema = z
26 .string()
27 .optional()
28 .describe(
29 'TypeScript code that fetches data and returns props to merge (e.g., "const b = await external_get_balances(); return { value: b.checking }")',
30 )
31​
32/**
33 * Helper to create a ToolBinding that emits a report:ui event
34 */
35function createReportBinding<T extends z.ZodType>(
36 name: string,
37 description: string,
38 inputSchema: T,
39 createEvent: (input: z.infer<T>) => UIEvent,
40): ToolBinding {
41 return {
42 name,
43 description,
44 inputSchema: convertSchemaToJsonSchema(inputSchema) || {
45 type: 'object',
46 properties: {},
47 },
48 outputSchema: convertSchemaToJsonSchema(z.object({ success: z.boolean() })),
49 execute: async (args: unknown, context?: ToolExecutionContext) => {
50 const parsed = inputSchema.parse(args)
51 const event = createEvent(parsed)
52 const emitCustomEvent = context?.emitCustomEvent || (() => {})
53​
54 // Extract reportId from the parsed input
55 const reportId = (parsed as { reportId: string }).reportId
56​
57 emitCustomEvent('report:ui', {
58 reportId,
59 event,
60 })
61​
62 applyReportUIEvent(reportId, event)
63​
64 return { success: true }
65 },
66 }
68​
69/**
70 * Generate a random ID for components that don't have one specified
71 */
72function generateId(prefix: string): string {
73 return `${prefix}-${Math.random().toString(36).slice(2, 10)}`
75​
76// Common schemas - using .catch() to gracefully handle invalid values from stored snippets
77const gapSchema = z.enum(['none', 'xs', 'sm', 'md', 'lg', 'xl']).catch('md')
78const alignSchema = z
79 .enum(['start', 'center', 'end', 'stretch'])
80 .catch('stretch')
81const paddingSchema = z.enum(['none', 'sm', 'md', 'lg']).catch('md')
82​
83const buttonVariantSchema = z
84 .enum(['primary', 'secondary', 'danger', 'ghost'])
85 .catch('primary')
86​
87const handlerBindingsForValidation = createHandlerBindings()
88const handlerBindingTypes = generateTypeStubs(handlerBindingsForValidation)
89const allowedHandlerBindings = new Set(
90 Object.keys(handlerBindingsForValidation),
92​
93// ============================================================================
94// Layout Bindings
95// ============================================================================
96​
97const vboxBinding = createReportBinding(
98 'external_report_vbox',
99 'Create a vertical stack container for other components',
100 z.object({
101 reportId: z.string().describe('ID of the report to add to'),
102 id: z.string().describe('Unique ID for this component'),
103 parentId: z
104 .string()
105 .optional()
106 .describe(
107 'Parent component ID (optional, adds to root if not specified)',
108 ),
109 gap: gapSchema.describe('Gap between children'),
110 align: alignSchema.describe('Cross-axis alignment'),
111 padding: paddingSchema.describe('Internal padding'),
112 }),
113 (input) => ({
114 op: 'add' as const,
115 id: input.id,
116 type: 'vbox' as ComponentType,
117 parentId: input.parentId,
118 props: {
119 gap: input.gap,
120 align: input.align,
121 padding: input.padding,
122 },
123 }),
125​
126const hboxBinding = createReportBinding(
127 'external_report_hbox',
128 'Create a horizontal stack container for other components',
129 z.object({
130 reportId: z.string().describe('ID of the report to add to'),
131 id: z.string().describe('Unique ID for this component'),
132 parentId: z.string().optional().describe('Parent component ID'),
133 gap: gapSchema.describe('Gap between children'),
134 align: alignSchema.describe('Cross-axis alignment'),
135 justify: z
136 .enum(['start', 'center', 'end', 'between', 'around'])
137 .catch('start')
138 .describe(
139 'Main-axis alignment. Must be one of: start, center, end, between, around',
140 ),
141 wrap: z
142 .boolean()
143 .optional()
144 .default(false)
145 .describe('Whether to wrap children'),
146 }),
147 (input) => ({
148 op: 'add' as const,
149 id: input.id,
150 type: 'hbox' as ComponentType,
151 parentId: input.parentId,
152 props: {
153 gap: input.gap,
154 align: input.align,
155 justify: input.justify,
156 wrap: input.wrap,
157 },
158 }),
160​
161const gridBinding = createReportBinding(
162 'external_report_grid',
163 'Create a CSS grid container with responsive columns',
164 z.object({
165 reportId: z.string().describe('ID of the report to add to'),
166 id: z.string().describe('Unique ID for this component'),
167 parentId: z.string().optional().describe('Parent component ID'),
168 cols: z
169 .union([
170 z.number(),
171 z.object({
172 sm: z.number().optional(),
173 md: z.number().optional(),
174 lg: z.number().optional(),
175 }),
176 ])
177 .optional()
178 .default(3)
179 .describe('Number of columns or responsive breakpoints'),
180 gap: gapSchema.describe('Gap between grid items'),
181 }),
182 (input) => ({
183 op: 'add' as const,
184 id: input.id,
185 type: 'grid' as ComponentType,
186 parentId: input.parentId,
187 props: {
188 cols: input.cols,
189 gap: input.gap,
190 },
191 }),
193​
194const cardBinding = createReportBinding(
195 'external_report_card',
196 'Create a card container with optional title and subtitle',
197 z.object({
198 reportId: z.string().describe('ID of the report to add to'),
199 id: z.string().describe('Unique ID for this component'),
200 parentId: z.string().optional().describe('Parent component ID'),
201 title: z.string().optional().describe('Card title'),
202 subtitle: z.string().optional().describe('Card subtitle'),
203 variant: z
204 .enum(['default', 'outlined', 'elevated'])
205 .catch('default')
206 .describe(
207 'Card style variant. Must be one of: default, outlined, elevated',
208 ),
209 padding: paddingSchema.describe('Internal padding'),
210 }),
211 (input) => ({
212 op: 'add' as const,
213 id: input.id,
214 type: 'card' as ComponentType,
215 parentId: input.parentId,
216 props: {
217 title: input.title,
218 subtitle: input.subtitle,
219 variant: input.variant,
220 padding: input.padding,
221 },
222 }),
224​
225const sectionBinding = createReportBinding(
226 'external_report_section',
227 'Create a collapsible section with a title',
228 z.object({
229 reportId: z.string().describe('ID of the report to add to'),
230 id: z.string().describe('Unique ID for this component'),
231 parentId: z.string().optional().describe('Parent component ID'),
232 title: z.string().describe('Section title'),
233 defaultOpen: z
234 .boolean()
235 .optional()
236 .default(true)
237 .describe('Whether section is initially open'),
238 collapsible: z
239 .boolean()
240 .optional()
241 .default(true)
242 .describe('Whether section can be collapsed'),
243 }),
244 (input) => ({
245 op: 'add' as const,
246 id: input.id,
247 type: 'section' as ComponentType,
248 parentId: input.parentId,
249 props: {
250 title: input.title,
251 defaultOpen: input.defaultOpen,
252 collapsible: input.collapsible,
253 },
254 }),
256​
257// ============================================================================
258// Content Bindings
259// ============================================================================
260​
261const textBinding = createReportBinding(
262 'external_report_text',
263 'Add text content with typography variants',
264 z.object({
265 reportId: z.string().describe('ID of the report to add to'),
266 id: z
267 .string()
268 .optional()
269 .describe('Component ID (auto-generated if not specified)'),
270 parentId: z.string().optional().describe('Parent component ID'),
271 content: z.string().describe('Text content to display'),
272 variant: z
273 .enum(['h1', 'h2', 'h3', 'body', 'caption', 'code'])
274 .catch('body')
275 .describe(
276 'Typography variant. Must be one of: h1, h2, h3, body, caption, code',
277 ),
278 color: z
279 .enum(['default', 'muted', 'accent', 'success', 'warning', 'error'])
280 .catch('default')
281 .describe(
282 'Text color. Must be one of: default, muted, accent, success, warning, error',
283 ),
284 align: z
285 .enum(['left', 'center', 'right'])
286 .catch('left')
287 .describe('Text alignment. Must be one of: left, center, right'),
288 }),
289 (input) => ({
290 op: 'add' as const,
291 id: input.id || generateId('text'),
292 type: 'text' as ComponentType,
293 parentId: input.parentId,
294 props: {
295 content: input.content,
296 variant: input.variant,
297 color: input.color,
298 align: input.align,
299 },
300 }),
302​
303const metricBindingSchema = z.object({
304 reportId: z.string().describe('ID of the report to add to'),
305 id: z
306 .string()
307 .optional()
308 .describe('Component ID (auto-generated if not specified)'),
309 parentId: z.string().optional().describe('Parent component ID'),
310 value: z.union([z.number(), z.string()]).describe('The metric value'),
311 label: z.string().describe('Label describing the metric'),
312 trend: z.string().optional().describe('Trend indicator (e.g., "+8%")'),
313 trendDirection: z
314 .enum(['up', 'down', 'neutral'])
315 .optional()
316 .describe('Direction of trend'),
317 format: z
318 .enum(['number', 'currency', 'percent', 'compact'])
319 .catch('number')
320 .describe(
321 'Number format. Must be one of: number, currency, percent, compact',
322 ),
323 prefix: z.string().optional().describe('Prefix (e.g., "$")'),
324 suffix: z.string().optional().describe('Suffix (e.g., "/week")'),
325 variant: z
326 .enum(['default', 'success', 'warning', 'error'])
327 .catch('default')
328 .describe(
329 'Color variant. Must be one of: default, success, warning, error',
330 ),
331 subscriptions: subscriptionsSchema,
332 dataSource: dataSourceSchema,
333})
334​
335const metricBinding: ToolBinding = {
336 name: 'external_report_metric',
337 description:
338 'Display a big number with label and optional trend indicator. Supports subscriptions for reactive updates.',
339 inputSchema: convertSchemaToJsonSchema(metricBindingSchema) || {
340 type: 'object',
341 properties: {},
342 },
343 outputSchema: convertSchemaToJsonSchema(z.object({ success: z.boolean() })),
344 execute: async (args, context) => {
345 const parsed = metricBindingSchema.parse(args)
346 const { reportId, parentId, subscriptions, dataSource } = parsed
347 const id = parsed.id || generateId('metric')
348 const emitCustomEvent = context?.emitCustomEvent || (() => {})
349​
350 // Validate dataSource if provided
351 let validatedDataSource: string | undefined
352 if (dataSource) {
353 const { validateHandler } = await import('./validate-handler')
354 const validation = await validateHandler(
355 dataSource,
356 handlerBindingTypes,
357 allowedHandlerBindings,
358 )
359 if (!validation.valid) {
360 return {
361 success: false,
362 error: `dataSource validation failed: ${validation.error}`,
363 }
364 }
365 validatedDataSource = validation.strippedCode || dataSource
366 }
367​
368 // Register subscriptions with the signal registry
369 if (subscriptions && subscriptions.length > 0) {
370 const registry = getSignalRegistry(reportId)
371 if (registry) {
372 for (const signal of subscriptions) {
373 registry.subscribe(id, signal)
374 }
375 }
376 }
377​
378 const event: UIEvent = {
379 op: 'add',
380 id,
381 type: 'metric',
382 parentId,
383 props: {
384 value: parsed.value,
385 label: parsed.label,
386 trend: parsed.trend,
387 trendDirection: parsed.trendDirection,
388 format: parsed.format,
389 prefix: parsed.prefix,
390 suffix: parsed.suffix,
391 variant: parsed.variant,
392 },
393 subscriptions,
394 dataSource: validatedDataSource,
395 }
396​
397 emitCustomEvent('report:ui', { reportId, event })
398 applyReportUIEvent(reportId, event)
399​
400 return { success: true }
401 },
403​
404const badgeBinding = createReportBinding(
405 'external_report_badge',
406 'Add a status pill/badge indicator',
407 z.object({
408 reportId: z.string().describe('ID of the report to add to'),
409 id: z
410 .string()
411 .optional()
412 .describe('Component ID (auto-generated if not specified)'),
413 parentId: z.string().optional().describe('Parent component ID'),
414 label: z.string().describe('Badge text'),
415 variant: z
416 .enum(['default', 'success', 'warning', 'error', 'info'])
417 .catch('default')
418 .describe(
419 'Badge color variant. Must be one of: default, success, warning, error, info',
420 ),
421 size: z
422 .enum(['sm', 'md'])
423 .catch('md')
424 .describe('Badge size. Must be one of: sm, md'),
425 }),
426 (input) => ({
427 op: 'add' as const,
428 id: input.id || generateId('badge'),
429 type: 'badge' as ComponentType,
430 parentId: input.parentId,
431 props: {
432 label: input.label,
433 variant: input.variant,
434 size: input.size,
435 },
436 }),
438​
439const markdownBinding = createReportBinding(
440 'external_report_markdown',
441 'Render markdown content with GFM support',
442 z.object({
443 reportId: z.string().describe('ID of the report to add to'),
444 id: z
445 .string()
446 .optional()
447 .describe('Component ID (auto-generated if not specified)'),
448 parentId: z.string().optional().describe('Parent component ID'),
449 content: z.string().describe('Markdown content'),
450 }),
451 (input) => ({
452 op: 'add' as const,
453 id: input.id || generateId('markdown'),
454 type: 'markdown' as ComponentType,
455 parentId: input.parentId,
456 props: {
457 content: input.content,
458 },
459 }),
461​
462const dividerBinding = createReportBinding(
463 'external_report_divider',
464 'Add a horizontal divider line',
465 z.object({
466 reportId: z.string().describe('ID of the report to add to'),
467 id: z
468 .string()
469 .optional()
470 .describe('Component ID (auto-generated if not specified)'),
471 parentId: z.string().optional().describe('Parent component ID'),
472 variant: z
473 .enum(['solid', 'dashed'])
474 .catch('solid')
475 .describe('Line style. Must be one of: solid, dashed'),
476 spacing: z
477 .enum(['sm', 'md', 'lg'])
478 .catch('md')
479 .describe('Vertical spacing. Must be one of: sm, md, lg'),
480 }),
481 (input) => ({
482 op: 'add' as const,
483 id: input.id || generateId('divider'),
484 type: 'divider' as ComponentType,
485 parentId: input.parentId,
486 props: {
487 variant: input.variant,
488 spacing: input.spacing,
489 },
490 }),
492​
493const spacerBinding = createReportBinding(
494 'external_report_spacer',
495 'Add empty space between components',
496 z.object({
497 reportId: z.string().describe('ID of the report to add to'),
498 id: z
499 .string()
500 .optional()
501 .describe('Component ID (auto-generated if not specified)'),
502 parentId: z.string().optional().describe('Parent component ID'),
503 size: z
504 .enum(['sm', 'md', 'lg', 'xl', 'flex'])
505 .catch('md')
506 .describe('Space size. Must be one of: sm, md, lg, xl, flex'),
507 }),
508 (input) => ({
509 op: 'add' as const,
510 id: input.id || generateId('spacer'),
511 type: 'spacer' as ComponentType,
512 parentId: input.parentId,
513 props: {
514 size: input.size,
515 },
516 }),
518​
519const buttonBinding: ToolBinding = {
520 name: 'external_report_button',
521 description: 'Add a button with optional event handlers and subscriptions',
522 inputSchema: convertSchemaToJsonSchema(
523 z.object({
524 reportId: z.string().describe('ID of the report to add to'),
525 id: z.string().describe('Unique ID for this component'),
526 parentId: z
527 .string()
528 .optional()
529 .describe('Parent component ID (optional)'),
530 label: z.string().describe('Button label'),
531 variant: buttonVariantSchema.describe(
532 'Button style variant. Must be one of: primary, secondary, danger, ghost',
533 ),
534 disabled: z.boolean().optional().describe('Disable the button'),
535 handlers: z
536 .record(z.string(), z.string())
537 .optional()
538 .describe(
539 'Event handlers as TypeScript strings (e.g. { onPress: "..." })',
540 ),
541 subscriptions: subscriptionsSchema,
542 dataSource: dataSourceSchema,
543 }),
544 ) || { type: 'object', properties: {} },
545 outputSchema: convertSchemaToJsonSchema(z.object({ success: z.boolean() })),
546 execute: async (args, context) => {
547 const parsed = z
548 .object({
549 reportId: z.string(),
550 id: z.string(),
551 parentId: z.string().optional(),
552 label: z.string(),
553 variant: buttonVariantSchema,
554 disabled: z.boolean().optional(),
555 handlers: z.record(z.string(), z.string()).optional(),
556 subscriptions: subscriptionsSchema,
557 dataSource: dataSourceSchema,
558 })
559 .parse(args)
560​
561 const {
562 reportId,
563 id,
564 parentId,
565 label,
566 variant,
567 disabled,
568 handlers,
569 subscriptions,
570 dataSource,
571 } = parsed
572 const emitCustomEvent = context?.emitCustomEvent || (() => {})
573​
574 let validatedHandlers: Record<string, string> | undefined
575 if (handlers) {
576 // Dynamic import to avoid RSC module runner issues with esbuild
577 const { validateHandler } = await import('./validate-handler')
578 validatedHandlers = {}
579 for (const [handlerName, handlerCode] of Object.entries(handlers)) {
580 const validation = await validateHandler(
581 handlerCode,
582 handlerBindingTypes,
583 allowedHandlerBindings,
584 )
585 if (!validation.valid) {
586 return {
587 success: false,
588 error: `Handler '${handlerName}' validation failed: ${validation.error}`,
589 }
590 }
591 validatedHandlers[handlerName] = validation.strippedCode || handlerCode
592 }
593 }
594​
595 // Validate dataSource if provided
596 let validatedDataSource: string | undefined
597 if (dataSource) {
598 const { validateHandler } = await import('./validate-handler')
599 const validation = await validateHandler(
600 dataSource,
601 handlerBindingTypes,
602 allowedHandlerBindings,
603 )
604 if (!validation.valid) {
605 return {
606 success: false,
607 error: `dataSource validation failed: ${validation.error}`,
608 }
609 }
610 validatedDataSource = validation.strippedCode || dataSource
611 }
612​
613 // Register subscriptions with the signal registry
614 if (subscriptions && subscriptions.length > 0) {
615 const registry = getSignalRegistry(reportId)
616 if (registry) {
617 for (const signal of subscriptions) {
618 registry.subscribe(id, signal)
619 }
620 }
621 }
622​
623 const event: UIEvent = {
624 op: 'add',
625 id,
626 type: 'button',
627 parentId,
628 props: {
629 label,
630 variant,
631 disabled,
632 },
633 handlers: validatedHandlers,
634 subscriptions,
635 dataSource: validatedDataSource,
636 }
637​
638 emitCustomEvent('report:ui', {
639 reportId,
640 event,
641 })
642​
643 applyReportUIEvent(reportId, event)
644​
645 return { success: true }
646 },
648​
649// ============================================================================
650// Data Bindings
651// ============================================================================
652​
653const chartBindingSchema = z.object({
654 reportId: z.string().describe('ID of the report to add to'),
655 id: z.string().describe('Unique ID for this component'),
656 parentId: z.string().optional().describe('Parent component ID'),
657 type: z.enum(['line', 'bar', 'area', 'pie', 'donut']).describe('Chart type'),
658 data: z.array(z.record(z.string(), z.unknown())).describe('Chart data array'),
659 xKey: z.string().describe('Key for X axis values'),
660 yKey: z
661 .union([z.string(), z.array(z.string())])
662 .describe('Key(s) for Y axis values'),
663 height: z.number().optional().default(300).describe('Chart height in pixels'),
664 showLegend: z.boolean().optional().default(true).describe('Show legend'),
665 showGrid: z.boolean().optional().default(true).describe('Show grid lines'),
666 showTooltip: z
667 .boolean()
668 .optional()
669 .default(true)
670 .describe('Show tooltips on hover'),
671 colors: z.array(z.string()).optional().describe('Custom colors array'),
672 animate: z.boolean().optional().default(true).describe('Enable animations'),
673 subscriptions: subscriptionsSchema,
674 dataSource: dataSourceSchema,
675})
676​
677const chartBinding: ToolBinding = {
678 name: 'external_report_chart',
679 description:
680 'Create an interactive chart (line, bar, area, pie, donut). Supports subscriptions for reactive updates.',
681 inputSchema: convertSchemaToJsonSchema(chartBindingSchema) || {
682 type: 'object',
683 properties: {},
684 },
685 outputSchema: convertSchemaToJsonSchema(z.object({ success: z.boolean() })),
686 execute: async (args, context) => {
687 const parsed = chartBindingSchema.parse(args)
688 const { reportId, id, parentId, subscriptions, dataSource } = parsed
689 const emitCustomEvent = context?.emitCustomEvent || (() => {})
690​
691 // Validate dataSource if provided
692 let validatedDataSource: string | undefined
693 if (dataSource) {
694 const { validateHandler } = await import('./validate-handler')
695 const validation = await validateHandler(
696 dataSource,
697 handlerBindingTypes,
698 allowedHandlerBindings,
699 )
700 if (!validation.valid) {
701 return {
702 success: false,
703 error: `dataSource validation failed: ${validation.error}`,
704 }
705 }
706 validatedDataSource = validation.strippedCode || dataSource
707 }
708​
709 // Register subscriptions with the signal registry
710 if (subscriptions && subscriptions.length > 0) {
711 const registry = getSignalRegistry(reportId)
712 if (registry) {
713 for (const signal of subscriptions) {
714 registry.subscribe(id, signal)
715 }
716 }
717 }
718​
719 const event: UIEvent = {
720 op: 'add',
721 id,
722 type: 'chart',
723 parentId,
724 props: {
725 type: parsed.type,
726 data: parsed.data,
727 xKey: parsed.xKey,
728 yKey: parsed.yKey,
729 height: parsed.height,
730 showLegend: parsed.showLegend,
731 showGrid: parsed.showGrid,
732 showTooltip: parsed.showTooltip,
733 colors: parsed.colors,
734 animate: parsed.animate,
735 },
736 dataSource: validatedDataSource,
737 }
738​
739 emitCustomEvent('report:ui', {
740 reportId,
741 event,
742 })
743​
744 applyReportUIEvent(reportId, event)
745​
746 return { success: true }
747 },
749​
750const sparklineBinding = createReportBinding(
751 'external_report_sparkline',
752 'Add a mini inline chart',
753 z.object({
754 reportId: z.string().describe('ID of the report to add to'),
755 id: z
756 .string()
757 .optional()
758 .describe('Component ID (auto-generated if not specified)'),
759 parentId: z.string().optional().describe('Parent component ID'),
760 data: z.array(z.number()).describe('Array of numeric values'),
761 type: z
762 .enum(['line', 'bar', 'area'])
763 .catch('line')
764 .describe('Sparkline type. Must be one of: line, bar, area'),
765 color: z.string().optional().describe('Line/bar color'),
766 height: z.number().optional().default(32).describe('Height in pixels'),
767 width: z.number().optional().default(100).describe('Width in pixels'),
768 showEndValue: z
769 .boolean()
770 .optional()
771 .default(false)
772 .describe('Show the last value'),
773 }),
774 (input) => ({
775 op: 'add' as const,
776 id: input.id || generateId('sparkline'),
777 type: 'sparkline' as ComponentType,
778 parentId: input.parentId,
779 props: {
780 data: input.data,
781 type: input.type,
782 color: input.color,
783 height: input.height,
784 width: input.width,
785 showEndValue: input.showEndValue,
786 },
787 }),
789​
790const dataTableBindingSchema = z.object({
791 reportId: z.string().describe('ID of the report to add to'),
792 id: z.string().describe('Unique ID for this component'),
793 parentId: z.string().optional().describe('Parent component ID'),
794 columns: z
795 .array(
796 z.object({
797 key: z.string().describe('Data key for this column'),
798 label: z.string().describe('Column header label'),
799 align: z
800 .enum(['left', 'center', 'right'])
801 .catch('left')
802 .describe('Column alignment. Must be one of: left, center, right'),
803 format: z
804 .enum(['text', 'number', 'currency', 'percent', 'date'])
805 .catch('text')
806 .describe(
807 'Data format. Must be one of: text, number, currency, percent, date',
808 ),
809 sortable: z.boolean().optional().default(true),
810 width: z.union([z.number(), z.string()]).optional(),
811 }),
812 )
813 .describe('Column definitions'),
814 rows: z.array(z.record(z.string(), z.unknown())).describe('Row data'),
815 pageSize: z.number().optional().default(10).describe('Rows per page'),
816 showPagination: z
817 .boolean()
818 .optional()
819 .default(true)
820 .describe('Show pagination controls'),
821 striped: z
822 .boolean()
823 .optional()
824 .default(true)
825 .describe('Alternating row colors'),
826 compact: z.boolean().optional().default(false).describe('Compact row height'),
827 sortBy: z.string().optional().describe('Initial sort column'),
828 sortDirection: z
829 .enum(['asc', 'desc'])
830 .catch('asc')
831 .describe('Initial sort direction. Must be one of: asc, desc'),
832 subscriptions: subscriptionsSchema,
833 dataSource: dataSourceSchema,
834})
835​
836const dataTableBinding: ToolBinding = {
837 name: 'external_report_dataTable',
838 description:
839 'Create a sortable, paginated data table. Supports subscriptions for reactive updates.',
840 inputSchema: convertSchemaToJsonSchema(dataTableBindingSchema) || {
841 type: 'object',
842 properties: {},
843 },
844 outputSchema: convertSchemaToJsonSchema(z.object({ success: z.boolean() })),
845 execute: async (args, context) => {
846 const parsed = dataTableBindingSchema.parse(args)
847 const { reportId, parentId, subscriptions, dataSource } = parsed
848 const id = parsed.id || generateId('dataTable')
849 const emitCustomEvent = context?.emitCustomEvent || (() => {})
850​
851 // Validate dataSource if provided
852 let validatedDataSource: string | undefined
853 if (dataSource) {
854 const { validateHandler } = await import('./validate-handler')
855 const validation = await validateHandler(
856 dataSource,
857 handlerBindingTypes,
858 allowedHandlerBindings,
859 )
860 if (!validation.valid) {
861 return {
862 success: false,
863 error: `dataSource validation failed: ${validation.error}`,
864 }
865 }
866 validatedDataSource = validation.strippedCode || dataSource
867 }
868​
869 // Register subscriptions with the signal registry
870 if (subscriptions && subscriptions.length > 0) {
871 const registry = getSignalRegistry(reportId)
872 if (registry) {
873 for (const signal of subscriptions) {
874 registry.subscribe(id, signal)
875 }
876 }
877 }
878​
879 const event: UIEvent = {
880 op: 'add',
881 id,
882 type: 'dataTable' as ComponentType,
883 parentId,
884 props: {
885 columns: parsed.columns,
886 rows: parsed.rows,
887 pageSize: parsed.pageSize,
888 showPagination: parsed.showPagination,
889 striped: parsed.striped,
890 compact: parsed.compact,
891 sortBy: parsed.sortBy,
892 sortDirection: parsed.sortDirection,
893 },
894 subscriptions,
895 dataSource: validatedDataSource,
896 }
897​
898 emitCustomEvent('report:ui', { reportId, event })
899 applyReportUIEvent(reportId, event)
900​
901 return { success: true, id }
902 },
904​
905const progressBinding = createReportBinding(
906 'external_report_progress',
907 'Add a progress bar',
908 z.object({
909 reportId: z.string().describe('ID of the report to add to'),
910 id: z
911 .string()
912 .optional()
913 .describe('Component ID (auto-generated if not specified)'),
914 parentId: z.string().optional().describe('Parent component ID'),
915 value: z.number().describe('Current progress value'),
916 max: z.number().optional().default(100).describe('Maximum value'),
917 label: z.string().optional().describe('Progress label'),
918 showValue: z.boolean().optional().default(true).describe('Show percentage'),
919 variant: z
920 .enum(['default', 'success', 'warning', 'error'])
921 .catch('default')
922 .describe(
923 'Color variant. Must be one of: default, success, warning, error',
924 ),
925 size: z
926 .enum(['sm', 'md', 'lg'])
927 .catch('md')
928 .describe('Bar size. Must be one of: sm, md, lg'),
929 }),
930 (input) => ({
931 op: 'add' as const,
932 id: input.id || generateId('progress'),
933 type: 'progress' as ComponentType,
934 parentId: input.parentId,
935 props: {
936 value: input.value,
937 max: input.max,
938 label: input.label,
939 showValue: input.showValue,
940 variant: input.variant,
941 size: input.size,
942 },
943 }),
945​
946// ============================================================================
947// Special Bindings
948// ============================================================================
949​
950const placeholderBinding = createReportBinding(
951 'external_report_placeholder',
952 'Add a loading placeholder with skeleton animation',
953 z.object({
954 reportId: z.string().describe('ID of the report to add to'),
955 id: z.string().describe('Unique ID for this component'),
956 parentId: z.string().optional().describe('Parent component ID'),
957 height: z
958 .union([z.number(), z.string()])
959 .optional()
960 .default(100)
961 .describe('Placeholder height'),
962 label: z.string().optional().describe('Loading label'),
963 }),
964 (input) => ({
965 op: 'add' as const,
966 id: input.id,
967 type: 'placeholder' as ComponentType,
968 parentId: input.parentId,
969 props: {
970 height: input.height,
971 label: input.label,
972 },
973 }),
975​
976const errorBinding = createReportBinding(
977 'external_report_error',
978 'Display an error message',
979 z.object({
980 reportId: z.string().describe('ID of the report to add to'),
981 id: z
982 .string()
983 .optional()
984 .describe('Component ID (auto-generated if not specified)'),
985 parentId: z.string().optional().describe('Parent component ID'),
986 message: z.string().describe('Error message'),
987 details: z.string().optional().describe('Additional error details'),
988 variant: z
989 .enum(['inline', 'card'])
990 .catch('inline')
991 .describe('Display variant. Must be one of: inline, card'),
992 }),
993 (input) => ({
994 op: 'add' as const,
995 id: input.id || generateId('error'),
996 type: 'error' as ComponentType,
997 parentId: input.parentId,
998 props: {
999 message: input.message,
1000 details: input.details,
1001 variant: input.variant,
1002 },
1003 }),
1005​
1006const emptyBinding = createReportBinding(
1007 'external_report_empty',
1008 'Display an empty state message',
1009 z.object({
1010 reportId: z.string().describe('ID of the report to add to'),
1011 id: z
1012 .string()
1013 .optional()
1014 .describe('Component ID (auto-generated if not specified)'),
1015 parentId: z.string().optional().describe('Parent component ID'),
1016 title: z.string().optional().describe('Empty state title'),
1017 description: z.string().optional().describe('Empty state description'),
1018 icon: z.string().optional().describe('Icon name'),
1019 }),
1020 (input) => ({
1021 op: 'add' as const,
1022 id: input.id || generateId('empty'),
1023 type: 'empty' as ComponentType,
1024 parentId: input.parentId,
1025 props: {
1026 title: input.title,
1027 description: input.description,
1028 icon: input.icon,
1029 },
1030 }),
1032​
1033// ============================================================================
1034// Operation Bindings
1035// ============================================================================
1036​
1037const updateInputSchema = z.object({
1038 reportId: z.string().describe('ID of the report'),
1039 componentId: z.string().describe('ID of the component to update'),
1040 props: z
1041 .record(z.string(), z.unknown())
1042 .describe('Props to merge with existing'),
1044​
1045const updateBinding: ToolBinding = {
1046 name: 'external_report_update',
1047 description: 'Update the props of an existing component',
1048 inputSchema: convertSchemaToJsonSchema(updateInputSchema) || {
1049 type: 'object',
1050 properties: {},
1051 },
1052 outputSchema: convertSchemaToJsonSchema(z.object({ success: z.boolean() })),
1053 execute: async (args, context) => {
1054 const { reportId, componentId, props } = updateInputSchema.parse(args)
1055​
1056 const emitCustomEvent = context?.emitCustomEvent || (() => {})
1057 const event: UIEvent = {
1058 op: 'update',
1059 id: componentId,
1060 props,
1062 emitCustomEvent('report:ui', { reportId, event })
1063 applyReportUIEvent(reportId, event)
1064​
1065 return { success: true }
1066 },
1068​
1069const removeInputSchema = z.object({
1070 reportId: z.string().describe('ID of the report'),
1071 componentId: z.string().describe('ID of the component to remove'),
1073​
1074const removeBinding: ToolBinding = {
1075 name: 'external_report_remove',
1076 description: 'Remove a component from the report',
1077 inputSchema: convertSchemaToJsonSchema(removeInputSchema) || {
1078 type: 'object',
1079 properties: {},
1080 },
1081 outputSchema: convertSchemaToJsonSchema(z.object({ success: z.boolean() })),
1082 execute: async (args, context) => {
1083 const { reportId, componentId } = removeInputSchema.parse(args)
1084​
1085 // Unsubscribe component from all signals before removal
1086 const registry = getSignalRegistry(reportId)
1087 if (registry) {
1088 registry.unsubscribeAll(componentId)
1090​
1091 const emitCustomEvent = context?.emitCustomEvent || (() => {})
1092 const event: UIEvent = {
1093 op: 'remove',
1094 id: componentId,
1096 emitCustomEvent('report:ui', { reportId, event })
1097 applyReportUIEvent(reportId, event)
1098​
1099 return { success: true }
1100 },
1102​
1103const reorderInputSchema = z.object({
1104 reportId: z.string().describe('ID of the report'),
1105 parentId: z
1106 .string()
1107 .optional()
1108 .describe('Parent container ID (root if not specified)'),
1109 childIds: z.array(z.string()).describe('Ordered array of child IDs'),
1111​
1112const reorderBinding: ToolBinding = {
1113 name: 'external_report_reorder',
1114 description: 'Reorder children of a container',
1115 inputSchema: convertSchemaToJsonSchema(reorderInputSchema) || {
1116 type: 'object',
1117 properties: {},
1118 },
1119 outputSchema: convertSchemaToJsonSchema(z.object({ success: z.boolean() })),
1120 execute: async (args, context) => {
1121 const { reportId, parentId, childIds } = reorderInputSchema.parse(args)
1122​
1123 const emitCustomEvent = context?.emitCustomEvent || (() => {})
1124 const event: UIEvent = {
1125 op: 'reorder',
1126 parentId,
1127 childIds,
1129 emitCustomEvent('report:ui', { reportId, event })
1130 applyReportUIEvent(reportId, event)
1131​
1132 return { success: true }
1133 },
1135​
1136// ============================================================================
1137// Watcher Subscription Bindings
1138// ============================================================================
1139​
1140const subscribeWatcherSchema = z.object({
1141 reportId: z.string().describe('ID of the report'),
1142 id: z.string().describe('Unique ID for this watcher'),
1143 description: z
1144 .string()
1145 .describe(
1146 'Human-readable description (e.g., "Alert when savings below $50")',
1147 ),
1148 signals: z
1149 .array(z.string())
1150 .describe('Signal names to watch (e.g., ["balances"])'),
1151 condition: z
1152 .string()
1153 .describe(
1154 'TypeScript code that returns true/false (e.g., "const b = await external_get_balances(); return b.savings < 50")',
1155 ),
1156 action: z
1157 .string()
1158 .describe(
1159 "TypeScript code to run when condition is true (e.g., \"await external_ui_toast({ message: 'Low savings!', variant: 'error' })\")",
1160 ),
1161 once: z
1162 .boolean()
1163 .optional()
1164 .default(false)
1165 .describe('If true, watcher fires once then is removed'),
1167​
1168const subscribeWatcherBinding: ToolBinding = {
1169 name: 'external_subscribe_watcher',
1170 description:
1171 'Register a watcher that runs code when signals change and a condition is met. Use for alerts like "notify if savings falls below $50".',
1172 inputSchema: convertSchemaToJsonSchema(subscribeWatcherSchema) || {
1173 type: 'object',
1174 properties: {},
1175 },
1176 outputSchema: convertSchemaToJsonSchema(
1177 z.object({ success: z.boolean(), watcherId: z.string().optional() }),
1178 ),
1179 execute: async (args, _context) => {
1180 const parsed = subscribeWatcherSchema.parse(args)
1181 const { reportId, id, description, signals, condition, action, once } =
1182 parsed
1183​
1184 // Validate condition code
1185 const { validateHandler } = await import('./validate-handler')
1186 const conditionValidation = await validateHandler(
1187 condition,
1188 handlerBindingTypes,
1189 allowedHandlerBindings,
1191 if (!conditionValidation.valid) {
1192 return {
1193 success: false,
1194 error: `Condition validation failed: ${conditionValidation.error}`,
1197​
1198 // Validate action code
1199 const actionValidation = await validateHandler(
1200 action,
1201 handlerBindingTypes,
1202 allowedHandlerBindings,
1204 if (!actionValidation.valid) {
1205 return {
1206 success: false,
1207 error: `Action validation failed: ${actionValidation.error}`,
1210​
1211 const watcher: WatcherSubscription = {
1212 id,
1213 description,
1214 signals,
1215 condition: conditionValidation.strippedCode || condition,
1216 action: actionValidation.strippedCode || action,
1217 once,
1218 fired: false,
1220​
1221 const success = addWatcher(reportId, watcher)
1222 if (!success) {
1223 return { success: false, error: 'Report not found' }
1225​
1226 return { success: true, watcherId: id }
1227 },
1229​
1230const unsubscribeWatcherSchema = z.object({
1231 reportId: z.string().describe('ID of the report'),
1232 watcherId: z.string().describe('ID of the watcher to remove'),
1234​
1235const unsubscribeWatcherBinding: ToolBinding = {
1236 name: 'external_unsubscribe_watcher',
1237 description: 'Remove a previously registered watcher',
1238 inputSchema: convertSchemaToJsonSchema(unsubscribeWatcherSchema) || {
1239 type: 'object',
1240 properties: {},
1241 },
1242 outputSchema: convertSchemaToJsonSchema(z.object({ success: z.boolean() })),
1243 execute: async (args) => {
1244 const { reportId, watcherId } = unsubscribeWatcherSchema.parse(args)
1245 const success = removeWatcher(reportId, watcherId)
1246 return { success }
1247 },
1249​
1250const listWatchersSchema = z.object({
1251 reportId: z.string().describe('ID of the report'),
1253​
1254const listWatchersBinding: ToolBinding = {
1255 name: 'external_list_watchers',
1256 description: 'List all active watchers for a report',
1257 inputSchema: convertSchemaToJsonSchema(listWatchersSchema) || {
1258 type: 'object',
1259 properties: {},
1260 },
1261 outputSchema: convertSchemaToJsonSchema(
1262 z.object({
1263 watchers: z.array(
1264 z.object({
1265 id: z.string(),
1266 description: z.string(),
1267 signals: z.array(z.string()),
1268 fired: z.boolean().optional(),
1269 }),
1270 ),
1271 }),
1272 ),
1273 execute: async (args) => {
1274 const { reportId } = listWatchersSchema.parse(args)
1275 const watchers = getAllWatchers(reportId)
1276 return {
1277 watchers: watchers.map((w) => ({
1278 id: w.id,
1279 description: w.description,
1280 signals: w.signals,
1281 fired: w.fired,
1282 })),
1284 },
1286​
1287// ============================================================================
1288// Export All Bindings
1289// ============================================================================
1290​
1291/**
1292 * All report bindings to be added to the sandbox.
1293 * These become available as external_report_* functions inside execute_typescript.
1294 */
1295export const reportBindings: Record<string, ToolBinding> = {
1296 // Layout
1297 external_report_vbox: vboxBinding,
1298 external_report_hbox: hboxBinding,
1299 external_report_grid: gridBinding,
1300 external_report_card: cardBinding,
1301 external_report_section: sectionBinding,
1302 // Content
1303 external_report_text: textBinding,
1304 external_report_metric: metricBinding,
1305 external_report_badge: badgeBinding,
1306 external_report_markdown: markdownBinding,
1307 external_report_divider: dividerBinding,
1308 external_report_spacer: spacerBinding,
1309 external_report_button: buttonBinding,
1310 // Data
1311 external_report_chart: chartBinding,
1312 external_report_sparkline: sparklineBinding,
1313 external_report_dataTable: dataTableBinding,
1314 external_report_progress: progressBinding,
1315 // Special
1316 external_report_placeholder: placeholderBinding,
1317 external_report_error: errorBinding,
1318 external_report_empty: emptyBinding,
1319 // Operations
1320 external_report_update: updateBinding,
1321 external_report_remove: removeBinding,
1322 external_report_reorder: reorderBinding,
1323 // Watchers
1324 external_subscribe_watcher: subscribeWatcherBinding,
1325 external_unsubscribe_watcher: unsubscribeWatcherBinding,
1326 external_list_watchers: listWatchersBinding,
1328​
1329// Banking bindings for demo - available during report building
1330const bankingBindings = createHandlerBindings()
1331​
1332/**
1333 * Create report bindings function for use with getSnippetBindings
1334 * Returns a fresh copy of the bindings record
1335 */
1336export function createReportBindings(): Record<string, ToolBinding> {
1337 return {
1338 ...reportBindings,
1339 // Include banking bindings for demo
1340 external_get_balances: bankingBindings.external_get_balances,
1341 external_transfer: bankingBindings.external_transfer,
1342 external_get_transactions: bankingBindings.external_get_transactions,