Open History to see the last commit
1import { toolDefinition } from '@tanstack/ai'
2import { z } from 'zod'
3
4export interface CodeExecution {
5 typescriptCode: string
6 success: boolean
7 result?: unknown
8 logs?: Array<string>
9 error?: { message: string; name?: string }
10}
11
12export interface ExecutePromptLogEntry {
13 id: string
14 timestamp: number
15 phase: 'request' | 'response' | 'error'
16 prompt: string
17 durationMs?: number
18 status?: number
19 data?: unknown
20 error?: string
21 executions?: Array<CodeExecution>
22}
23
24type LogListener = (entry: ExecutePromptLogEntry) => void
25
26let listeners: Array<LogListener> = []
27
28export function onExecutePromptLog(fn: LogListener): () => void {
29 listeners.push(fn)
30 return () => {
31 listeners = listeners.filter((l) => l !== fn)
32 }
33}
34
35function emit(entry: ExecutePromptLogEntry) {
36 for (const fn of listeners) fn(entry)
37}
38
39let logSeq = 0
40function nextId() {
41 return `ep-${++logSeq}-${Date.now()}`
42}
43
44/** Client tool calling POST /api/execute-prompt; server uses local createExecutePromptTool (see lib/create-execute-prompt-tool.ts). */
45export const executePromptShoeCatalogTool = toolDefinition({
46 name: 'execute_prompt',
47 description:
48 'Run a code-mode analysis over the shoe product catalog. Use this whenever the user asks about shoes, prices, brands, categories, comparisons, or inventory-style questions. Pass a clear natural-language prompt describing what data to compute or retrieve.',
49 inputSchema: z.object({
50 prompt: z
51 .string()
52 .describe(
53 'What to compute or look up (e.g. "average price of Nike shoes", "list all running shoes under $150")',
54 ),
55 }),
56 outputSchema: z.object({
57 data: z.unknown(),
58 }),
59}).client(async (input) => {
60 const prompt = resolveExecutePromptArg(input)
61 const id = nextId()
62 const startMs = Date.now()
63
64 emit({ id, timestamp: startMs, phase: 'request', prompt })
65
66 const res = await fetch('/api/execute-prompt', {
67 method: 'POST',
68 headers: { 'Content-Type': 'application/json' },
69 body: JSON.stringify({ prompt }),
70 })
71
72 const durationMs = Date.now() - startMs
73
74 if (!res.ok) {
75 const errBody = await res.json().catch(() => ({}))
76 const msg =
77 typeof errBody === 'object' && errBody !== null && 'error' in errBody
78 ? String((errBody as { error?: string }).error)
79 : res.statusText
80 const errorStr = msg || `execute_prompt failed (${res.status})`
81
82 emit({
83 id,
84 timestamp: Date.now(),
85 phase: 'error',
86 prompt,
87 durationMs,
88 status: res.status,
89 error: errorStr,
90 })
91
92 throw new Error(errorStr)
93 }
94
95 const result = (await res.json()) as {
96 data: unknown
97 executions?: Array<CodeExecution>
98 }
99
100 emit({
101 id,
102 timestamp: Date.now(),
103 phase: 'response',
104 prompt,
105 durationMs,
106 status: res.status,
107 data: result.data,
108 executions: result.executions,
109 })
110
111 return { data: result.data }
112})
113
114export const executePromptRealtimeTools = [
115 executePromptShoeCatalogTool,
116] as const
117
118function resolveExecutePromptArg(input: unknown): string {
119 if (typeof input === 'string') {
120 const t = input.trim()
121 if (!t) {
122 throw new Error(
123 'execute_prompt: model sent empty arguments; use { "prompt": "..." }',
124 )
125 }
126 try {
127 const parsed = JSON.parse(t) as Record<string, unknown>
128 const p = firstString(
129 parsed.prompt,
130 parsed.query,
131 parsed.question,
132 parsed.instruction,
133 parsed.task,
134 )
135 if (p) return p
136 } catch {
137 /* treat whole string as the prompt */
138 }
139 return t
140 }
141
142 if (input && typeof input === 'object') {
143 const o = input as Record<string, unknown>
144 const p = firstString(o.prompt, o.query, o.question, o.instruction, o.task)
145 if (p) return p
146 }
147
148 throw new Error(
149 'execute_prompt: expected a prompt string (property: prompt, query, question, instruction, or task)',
150 )
151}
152
153function firstString(...candidates: Array<unknown>): string | undefined {
154 for (const c of candidates) {
155 if (typeof c === 'string' && c.trim()) return c.trim()
156 }
157 return undefined
158}