@deepagents/text2sql 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1121 -453
- package/dist/index.js.map +4 -4
- package/dist/lib/adapters/mysql/column-stats.mysql.grounding.d.ts +14 -0
- package/dist/lib/adapters/mysql/column-stats.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/column-values.mysql.grounding.d.ts +22 -0
- package/dist/lib/adapters/mysql/column-values.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/constraint.mysql.grounding.d.ts +13 -0
- package/dist/lib/adapters/mysql/constraint.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/index.d.ts +44 -0
- package/dist/lib/adapters/mysql/index.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/indexes.mysql.grounding.d.ts +13 -0
- package/dist/lib/adapters/mysql/indexes.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/info.mysql.grounding.d.ts +13 -0
- package/dist/lib/adapters/mysql/info.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/mysql.d.ts +33 -0
- package/dist/lib/adapters/mysql/mysql.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/row-count.mysql.grounding.d.ts +13 -0
- package/dist/lib/adapters/mysql/row-count.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/table.mysql.grounding.d.ts +21 -0
- package/dist/lib/adapters/mysql/table.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/adapters/mysql/view.mysql.grounding.d.ts +18 -0
- package/dist/lib/adapters/mysql/view.mysql.grounding.d.ts.map +1 -0
- package/dist/lib/agents/bi.agent.d.ts +14 -0
- package/dist/lib/agents/bi.agent.d.ts.map +1 -0
- package/dist/lib/agents/chat1.agent.d.ts.map +1 -1
- package/dist/lib/agents/chat2.agent.d.ts.map +1 -1
- package/dist/lib/agents/developer.agent.d.ts +31 -0
- package/dist/lib/agents/developer.agent.d.ts.map +1 -0
- package/dist/lib/agents/question.agent.d.ts +1 -1
- package/dist/lib/agents/question.agent.d.ts.map +1 -1
- package/dist/lib/agents/sql.agent.d.ts +14 -32
- package/dist/lib/agents/sql.agent.d.ts.map +1 -1
- package/dist/lib/agents/text2sql.agent.d.ts.map +1 -1
- package/dist/lib/checkpoint.d.ts.map +1 -1
- package/dist/lib/sql.d.ts +42 -0
- package/dist/lib/sql.d.ts.map +1 -1
- package/dist/lib/synthesis/extractors/sql-extractor.d.ts.map +1 -1
- package/dist/lib/synthesis/index.js +267 -164
- package/dist/lib/synthesis/index.js.map +3 -3
- package/dist/lib/synthesis/synthesizers/breadth-evolver.d.ts.map +1 -1
- package/dist/lib/synthesis/synthesizers/depth-evolver.d.ts.map +1 -1
- package/dist/lib/synthesis/synthesizers/schema-synthesizer.d.ts.map +1 -1
- package/dist/lib/synthesis/synthesizers/styles.d.ts +2 -2
- package/dist/lib/synthesis/synthesizers/styles.d.ts.map +1 -1
- package/dist/lib/teach/teachings.d.ts.map +1 -1
- package/package.json +9 -3
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/adapters/groundings/context.ts", "../src/lib/adapters/adapter.ts", "../src/lib/agents/
|
|
4
|
-
"sourcesContent": ["import type { AdapterInfo, ColumnStats, Relationship, Table } from '../adapter.ts';\nimport type { View } from './view.grounding.ts';\n\n/**\n * Column type for grounding operations.\n * Common interface between Table.columns and View.columns.\n */\nexport interface Column {\n name: string;\n type: string;\n kind?: 'LowCardinality' | 'Enum';\n values?: string[];\n stats?: ColumnStats;\n}\n\n/**\n * Entity with columns (Table or View).\n */\nexport interface ColumnContainer {\n name: string;\n columns: Column[];\n}\n\n/**\n * Shared context object passed to all groundings.\n * Groundings read from and write to this context.\n */\nexport interface GroundingContext {\n /** Tables discovered by TableGrounding */\n tables: Table[];\n\n /** Views discovered by ViewGrounding */\n views: View[];\n\n /** Relationships discovered by TableGrounding */\n relationships: Relationship[];\n\n /** Database info collected by InfoGrounding */\n info?: AdapterInfo;\n\n /** Business context report generated by ReportGrounding */\n report?: string;\n}\n\n/**\n * Create a new empty grounding context.\n */\nexport function createGroundingContext(): GroundingContext {\n return {\n tables: [],\n views: [],\n relationships: [],\n info: undefined,\n };\n}\n", "import type { AbstractGrounding } from './groundings/abstract.grounding.ts';\nimport { createGroundingContext } from './groundings/context.ts';\n\n/**\n * Filter type for view/table names.\n * - string[]: explicit list of view names\n * - RegExp: pattern to match view names\n * - function: predicate to filter view names\n */\nexport type Filter = string[] | RegExp | ((viewName: string) => boolean);\n\nexport interface Table {\n name: string;\n schema?: string;\n rawName?: string;\n columns: {\n name: string;\n type: string;\n kind?: 'LowCardinality' | 'Enum';\n values?: string[];\n isIndexed?: boolean;\n stats?: ColumnStats;\n }[];\n rowCount?: number;\n sizeHint?: 'tiny' | 'small' | 'medium' | 'large' | 'huge';\n indexes?: TableIndex[];\n constraints?: TableConstraint[];\n}\n\nexport interface TableIndex {\n name: string;\n columns: string[];\n unique?: boolean;\n type?: string;\n}\n\nexport interface TableConstraint {\n name: string;\n type:\n | 'CHECK'\n | 'UNIQUE'\n | 'NOT_NULL'\n | 'DEFAULT'\n | 'PRIMARY_KEY'\n | 'FOREIGN_KEY';\n columns?: string[];\n definition?: string;\n defaultValue?: string;\n referencedTable?: string;\n referencedColumns?: string[];\n}\n\nexport interface ColumnStats {\n min?: string;\n max?: string;\n nullFraction?: number;\n}\n\nexport type Relationship = {\n table: string;\n from: string[];\n referenced_table: string;\n to: string[];\n};\n\nexport type TablesFilter = string[] | RegExp;\n\nexport interface Introspection {\n tables: Table[];\n relationships: Relationship[];\n}\n\nexport interface AdapterInfo {\n dialect: string;\n version?: string;\n database?: string;\n details?: Record<string, unknown>;\n}\n\nexport type AdapterInfoProvider =\n | AdapterInfo\n | (() => Promise<AdapterInfo> | AdapterInfo);\n\nexport type IntrospectionPhase =\n | 'tables'\n | 'row_counts'\n | 'primary_keys'\n | 'indexes'\n | 'column_stats'\n | 'low_cardinality'\n | 'relationships';\n\nexport interface IntrospectionProgress {\n phase: IntrospectionPhase;\n message: string;\n current?: number;\n total?: number;\n}\n\nexport type OnProgress = (progress: IntrospectionProgress) => void;\n\nexport interface IntrospectOptions {\n onProgress?: OnProgress;\n}\n\nexport type GroundingFn = (adapter: Adapter) => AbstractGrounding;\n\nexport type ExecuteFunction = (sql: string) => Promise<any> | any;\nexport type ValidateFunction = (\n sql: string,\n) => Promise<string | void> | string | void;\n\nexport abstract class Adapter {\n abstract grounding: GroundingFn[];\n\n /**\n * Default schema name for this database.\n * PostgreSQL: 'public', SQL Server: 'dbo', SQLite: undefined\n */\n abstract readonly defaultSchema: string | undefined;\n\n /**\n * System schemas to exclude from introspection by default.\n */\n abstract readonly systemSchemas: string[];\n\n async introspect(ctx = createGroundingContext()) {\n const lines: { tag: string; fn: () => string | null }[] = [];\n for (const fn of this.grounding) {\n const grounding = fn(this);\n lines.push({\n tag: grounding.tag,\n fn: await grounding.execute(ctx),\n });\n }\n return lines\n .map(({ fn, tag }) => {\n const description = fn();\n if (description === null) {\n return '';\n }\n return `<${tag}>\\n${description}\\n</${tag}>`;\n })\n .join('\\n');\n }\n abstract execute(sql: string): Promise<any[]> | any[];\n abstract validate(sql: string): Promise<string | void> | string | void;\n abstract runQuery<Row>(sql: string): Promise<Row[]> | Row[];\n\n /**\n * Quote an identifier (table/column name) for safe use in SQL.\n * Each database uses different quoting styles.\n */\n abstract quoteIdentifier(name: string): string;\n\n /**\n * Escape a string value for safe use in SQL.\n * Each database escapes different characters.\n */\n abstract escape(value: string): string;\n\n /**\n * Build a SELECT query to sample rows from a table.\n * Each database uses different syntax for limiting rows (LIMIT vs TOP).\n */\n abstract buildSampleRowsQuery(\n tableName: string,\n columns: string[] | undefined,\n limit: number,\n ): string;\n\n /**\n * Convert unknown database value to number.\n * Handles number, bigint, and string types.\n */\n toNumber(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'bigint') {\n return Number(value);\n }\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n }\n\n /**\n * Parse a potentially qualified table name into schema and table parts.\n */\n parseTableName(name: string): { schema: string; table: string } {\n if (name.includes('.')) {\n const [schema, ...rest] = name.split('.');\n return { schema, table: rest.join('.') };\n }\n return { schema: this.defaultSchema ?? '', table: name };\n }\n\n /**\n * Escape a string value for use in SQL string literals (single quotes).\n * Used in WHERE clauses like: WHERE name = '${escapeString(value)}'\n */\n escapeString(value: string): string {\n return value.replace(/'/g, \"''\");\n }\n\n /**\n * Build a SQL filter clause to include/exclude schemas.\n * @param columnName - The schema column name (e.g., 'TABLE_SCHEMA')\n * @param allowedSchemas - If provided, filter to these schemas only\n */\n buildSchemaFilter(columnName: string, allowedSchemas?: string[]): string {\n if (allowedSchemas && allowedSchemas.length > 0) {\n const values = allowedSchemas\n .map((s) => `'${this.escapeString(s)}'`)\n .join(', ');\n return `AND ${columnName} IN (${values})`;\n }\n if (this.systemSchemas.length > 0) {\n const values = this.systemSchemas\n .map((s) => `'${this.escapeString(s)}'`)\n .join(', ');\n return `AND ${columnName} NOT IN (${values})`;\n }\n return '';\n }\n}\n\nexport function filterTablesByName<T extends { name: string }>(\n tables: T[],\n filter: TablesFilter | undefined,\n): T[] {\n if (!filter) return tables;\n return tables.filter((table) => matchesFilter(table.name, filter));\n}\n\nexport function filterRelationshipsByTables(\n relationships: Relationship[],\n tableNames: Set<string> | undefined,\n): Relationship[] {\n if (tableNames === undefined) {\n return relationships;\n }\n if (tableNames.size === 0) {\n return [];\n }\n return relationships.filter(\n (it) => tableNames.has(it.table) || tableNames.has(it.referenced_table),\n );\n}\n\nexport function applyTablesFilter(\n tables: Table[],\n relationships: Relationship[],\n filter: TablesFilter | undefined,\n): { tables: Table[]; relationships: Relationship[] } {\n if (!filter) {\n return { tables, relationships };\n }\n\n const allowedNames = new Set(\n getTablesWithRelated(tables, relationships, filter),\n );\n\n return {\n tables: tables.filter((table) => allowedNames.has(table.name)),\n relationships: filterRelationshipsByTables(relationships, allowedNames),\n };\n}\n\nexport function matchesFilter(\n tableName: string,\n filter: TablesFilter,\n): boolean {\n if (Array.isArray(filter)) {\n return filter.includes(tableName);\n }\n return filter.test(tableName);\n}\n\nexport function getTablesWithRelated(\n allTables: Table[],\n relationships: Relationship[],\n filter: TablesFilter,\n): string[] {\n const matchedTables = filterTablesByName(allTables, filter).map(\n (it) => it.name,\n );\n\n if (matchedTables.length === 0) {\n return [];\n }\n\n const adjacency = new Map<string, Set<string>>();\n\n for (const rel of relationships) {\n if (!adjacency.has(rel.table)) {\n adjacency.set(rel.table, new Set());\n }\n if (!adjacency.has(rel.referenced_table)) {\n adjacency.set(rel.referenced_table, new Set());\n }\n adjacency.get(rel.table)!.add(rel.referenced_table);\n adjacency.get(rel.referenced_table)!.add(rel.table);\n }\n\n const result = new Set<string>(matchedTables);\n const queue = [...matchedTables];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n const neighbors = adjacency.get(current);\n\n if (!neighbors) {\n continue;\n }\n\n for (const neighbor of neighbors) {\n if (!result.has(neighbor)) {\n result.add(neighbor);\n queue.push(neighbor);\n }\n }\n }\n\n return Array.from(result);\n}\n", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent, thirdPersonPrompt } from '@deepagents/agent';\n\nimport type { Introspection } from '../adapters/adapter.ts';\nimport { databaseSchemaPrompt } from '../prompt.ts';\n\ntype SuggestionsAgentContext = {\n context?: string;\n adapterInfo?: string;\n};\ntype SuggestionsAgentOutput = {\n suggestions: {\n question: string;\n sql: string;\n businessValue: string;\n }[];\n};\n\nexport const suggestionsAgent = agent<\n SuggestionsAgentOutput,\n SuggestionsAgentContext\n>({\n name: 'text2sql-suggestions',\n model: groq('openai/gpt-oss-20b'),\n output: z.object({\n suggestions: z\n .array(\n z.object({\n question: z\n .string()\n .describe('A complex, high-impact business question.'),\n sql: z\n .string()\n .describe('The SQL statement needed to answer the question.'),\n businessValue: z\n .string()\n .describe('Why the question matters to stakeholders.'),\n }),\n )\n .min(1)\n .max(5)\n .describe('A set of up to two advanced question + SQL pairs.'),\n }),\n prompt: (state) => {\n return dedent`\n ${thirdPersonPrompt()}\n\n <identity>\n You are a senior analytics strategist who proposes ambitious business questions\n and drafts the SQL needed to answer them. You specialize in identifying ideas\n that combine multiple tables, apply segmentation or time analysis, and surface\n metrics that drive executive decisions.\n </identity>\n\n\n <instructions>\n - Recommend one or two UNIQUE questions that go beyond simple counts or listings.\n - Favor questions that require joins, aggregates, time comparisons, cohort analysis,\n or window functions.\n - For each question, explain the business reason stakeholders care about it.\n - Provide the complete SQL query that could answer the question in the given schema.\n - Keep result sets scoped with LIMIT clauses (max 50 rows) when returning raw rows.\n - Ensure table/column names match the provided schema exactly.\n - Use columns marked [LowCardinality: ...] to identify meaningful categorical filters or segmentations.\n - Leverage table [rows / size] hints to determine whether to aggregate (large tables) or inspect detailed data (tiny tables).\n - Reference PK/Indexed annotations and the Indexes list to recommend queries that use efficient join/filter paths.\n - Column annotations may expose ranges/null percentages\u2014use them to suggest realistic thresholds or quality checks.\n - Consult <relationship_examples> to anchor your recommendations in the actual join paths between tables.\n - Output only information grounded in the schema/context provided.\n </instructions>\n\n <response-format>\n Return valid JSON that satisfies the defined output schema.\n </response-format>\n `;\n },\n});\n", "import { groq } from '@ai-sdk/groq';\nimport { type Tool, tool } from 'ai';\nimport z from 'zod';\n\nimport { agent, toState } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport memoryPrompt from '../memory/memory.prompt.ts';\nimport type { TeachablesStore } from '../memory/store.ts';\nimport type { GeneratedTeachable } from '../teach/teachables.ts';\n\nexport type RenderingTools = Record<string, Tool<unknown, never>>;\n\nconst tools = {\n validate_query: tool({\n description: `Validate SQL query syntax before execution. Use this to check if your SQL is valid before running db_query. This helps catch errors early and allows you to correct the query if needed.`,\n inputSchema: z.object({\n sql: z.string().describe('The SQL query to validate.'),\n }),\n execute: async ({ sql }, options) => {\n const state = toState<{ adapter: Adapter }>(options);\n const result = await state.adapter.validate(sql);\n if (typeof result === 'string') {\n return `Validation Error: ${result}`;\n }\n return 'Query is valid.';\n },\n }),\n get_sample_rows: tool({\n description: `Sample rows from a table to understand data formatting, codes, and value patterns. Use BEFORE writing queries when:\n- Column types in schema don't reveal format (e.g., \"status\" could be 'active'/'inactive' or 1/0)\n- Date/time formats are unclear (ISO, Unix timestamp, locale-specific)\n- You need to understand lookup table codes or enum values\n- Column names are ambiguous (e.g., \"type\", \"category\", \"code\")`,\n inputSchema: z.object({\n tableName: z.string().describe('The name of the table to sample.'),\n columns: z\n .array(z.string())\n .optional()\n .describe(\n 'Specific columns to sample. If omitted, samples all columns.',\n ),\n limit: z\n .number()\n .min(1)\n .max(10)\n .default(3)\n .optional()\n .describe('Number of rows to sample (1-10, default 3).'),\n }),\n execute: ({ tableName, columns, limit = 3 }, options) => {\n const safeLimit = Math.min(Math.max(1, limit), 10);\n const state = toState<{ adapter: Adapter }>(options);\n const sql = state.adapter.buildSampleRowsQuery(\n tableName,\n columns,\n safeLimit,\n );\n return state.adapter.execute(sql);\n },\n }),\n db_query: tool({\n description: `Internal tool to fetch data from the store's database. Write a SQL query to retrieve the information needed to answer the user's question. The results will be returned as data that you can then present to the user in natural language.`,\n inputSchema: z.object({\n reasoning: z\n .string()\n .describe(\n 'Your reasoning for why this SQL query is relevant to the user request.',\n ),\n sql: z\n .string()\n .min(1, { message: 'SQL query cannot be empty.' })\n .refine(\n (sql) =>\n sql.trim().toUpperCase().startsWith('SELECT') ||\n sql.trim().toUpperCase().startsWith('WITH'),\n {\n message: 'Only read-only SELECT or WITH queries are allowed.',\n },\n )\n .describe('The SQL query to execute against the database.'),\n }),\n execute: ({ sql }, options) => {\n const state = toState<{ adapter: Adapter }>(options);\n return state.adapter.execute(sql);\n },\n }),\n scratchpad: scratchpad_tool,\n};\n\nconst userMemoryTypes = [\n 'identity',\n 'alias',\n 'preference',\n 'context',\n 'correction',\n] as const;\n\nconst userMemorySchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('identity'),\n description: z.string().describe(\"The user's identity: role or/and name\"),\n }),\n z.object({\n type: z.literal('alias'),\n term: z.string().describe('The term the user uses'),\n meaning: z.string().describe('What the user means by this term'),\n }),\n z.object({\n type: z.literal('preference'),\n aspect: z\n .string()\n .describe('What aspect of output this preference applies to'),\n value: z.string().describe(\"The user's preference\"),\n }),\n z.object({\n type: z.literal('context'),\n description: z.string().describe('What the user is currently working on'),\n }),\n z.object({\n type: z.literal('correction'),\n subject: z.string().describe('What was misunderstood'),\n clarification: z.string().describe('The correct understanding'),\n }),\n]);\n\nexport const memoryTools = {\n remember_memory: tool({\n description:\n 'Store something about the user for future conversations. Use silently when user shares facts, preferences, vocabulary, corrections, or context.',\n inputSchema: z.object({ memory: userMemorySchema }),\n execute: async ({ memory }, options) => {\n const state = toState<{ memory: TeachablesStore; userId: string }>(\n options,\n );\n await state.memory.remember(state.userId, memory as GeneratedTeachable);\n return 'Remembered.';\n },\n }),\n forget_memory: tool({\n description:\n 'Forget a specific memory. Use when user asks to remove something.',\n inputSchema: z.object({\n id: z.string().describe('The ID of the teachable to forget'),\n }),\n execute: async ({ id }, options) => {\n const state = toState<{ memory: TeachablesStore }>(options);\n await state.memory.forget(id);\n return 'Forgotten.';\n },\n }),\n recall_memory: tool({\n description:\n 'List stored memories for the current user. Use when user asks what you remember about them or wants to see their stored preferences.',\n inputSchema: z.object({\n type: z\n .enum(userMemoryTypes)\n .optional()\n .catch(undefined)\n .describe('Optional: filter by memory type'),\n }),\n execute: async ({ type }, options) => {\n const state = toState<{ memory: TeachablesStore; userId: string }>(\n options,\n );\n const memories = await state.memory.recall(state.userId, type);\n if (memories.length === 0) {\n return type ? `No ${type} memories stored.` : 'No memories stored.';\n }\n return memories.map((m) => ({\n id: m.id,\n type: m.type,\n data: m.data,\n createdAt: m.createdAt,\n }));\n },\n }),\n update_memory: tool({\n description:\n 'Update an existing memory. Use when user wants to modify something you previously stored.',\n inputSchema: z.object({\n memory: userMemorySchema,\n id: z.string().describe('The ID of the memory to update'),\n }),\n execute: async ({ id, memory }, options) => {\n const state = toState<{ memory: TeachablesStore }>(options);\n await state.memory.update(id, memory as GeneratedTeachable);\n return 'Updated.';\n },\n }),\n};\n\n/**\n * An agent that does Table Augmented Generation for Text-to-SQL tasks.\n */\nexport const t_a_g = agent<\n { sql: string },\n {\n // FIXME: this should not be here after creating the context package\n introspection: string;\n teachings: string;\n memory?: TeachablesStore;\n userId?: string;\n }\n>({\n model: groq('openai/gpt-oss-20b'),\n tools,\n name: 'text2sql',\n prompt: (state) => {\n const hasMemory = !!state?.memory;\n\n return `\n\n ${state?.teachings || ''}\n ${state?.introspection || ''}\n\n ${hasMemory ? memoryPrompt : ''}\n `;\n },\n});\n", "export function wrapBlock(tag: string, children: string[]): string {\n const content = children\n .filter((child): child is string => Boolean(child))\n .join('\\n');\n if (!content) {\n return '';\n }\n return `<${tag}>\\n${indentBlock(content, 2)}\\n</${tag}>`;\n}\n\nexport function list(tag: string, values: string[], childTag: string): string {\n if (!values.length) {\n return '';\n }\n const children = values.map((value) => leaf(childTag, value)).join('\\n');\n return `<${tag}>\\n${indentBlock(children, 2)}\\n</${tag}>`;\n}\n\nexport function leaf(tag: string, value: string): string {\n const safe = escapeXml(value);\n if (safe.includes('\\n')) {\n return `<${tag}>\\n${indentBlock(safe, 2)}\\n</${tag}>`;\n }\n return `<${tag}>${safe}</${tag}>`;\n}\n\nexport function indentBlock(text: string, spaces: number): string {\n if (!text.trim()) {\n return '';\n }\n const padding = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.length ? padding + line : padding))\n .join('\\n');\n}\n\nexport function escapeXml(value: string): string {\n if (value == null) {\n return '';\n }\n return value\n .replaceAll(/&/g, '&')\n .replaceAll(/</g, '<')\n .replaceAll(/>/g, '>')\n .replaceAll(/\"/g, '"')\n .replaceAll(/'/g, ''');\n}\n", "import { indentBlock, leaf, list, wrapBlock } from './xml.ts';\n\nexport interface Teachables {\n type: GeneratedTeachable['type'] | 'user_profile';\n /** Serialize to GeneratedTeachable for storage */\n encode: () => GeneratedTeachable;\n /** Render to XML string for prompts */\n decode: () => string;\n}\nexport type GeneratedTeachable =\n | { type: 'term'; name: string; definition: string }\n | { type: 'hint'; text: string }\n | { type: 'guardrail'; rule: string; reason?: string; action?: string }\n | {\n type: 'explain';\n concept: string;\n explanation: string;\n therefore?: string;\n }\n | { type: 'example'; question: string; answer: string; note?: string }\n | { type: 'clarification'; when: string; ask: string; reason: string }\n | {\n type: 'workflow';\n task: string;\n steps: string[];\n triggers?: string[];\n notes?: string;\n }\n | { type: 'quirk'; issue: string; workaround: string }\n | { type: 'styleGuide'; prefer: string; never?: string; always?: string }\n | {\n type: 'analogy';\n concept: string[];\n relationship: string;\n insight?: string;\n therefore?: string;\n pitfall?: string;\n }\n | { type: 'glossary'; entries: Record<string, string> }\n // User-specific teachable types\n | { type: 'identity'; name?: string; role?: string }\n | { type: 'persona'; name: string; role: string; tone: string }\n | { type: 'alias'; term: string; meaning: string }\n | { type: 'preference'; aspect: string; value: string }\n | { type: 'context'; description: string }\n | { type: 'correction'; subject: string; clarification: string };\n\n/**\n * Teach the system domain-specific vocabulary and business terminology.\n *\n * Use this to define simple, direct mappings between business terms and their meanings.\n * The system will understand these terms when users mention them in queries.\n *\n * @param name - The business term or acronym to define\n * @param definition - What the term means in your domain\n *\n * @example\n * // Logistics/Transportation dataset\n * term(\"deadhead miles\", \"distance driven with empty truck between deliveries\")\n * term(\"dwell time\", \"total time a truck spends at a loading dock or warehouse\")\n * term(\"LTL\", \"less than truckload - shipment that doesn't fill entire truck\")\n *\n * @example\n * // Education/University dataset\n * term(\"matriculation\", \"students who completed enrollment and started classes\")\n * term(\"DFW rate\", \"percentage of students receiving D, F, or Withdrawal in a course\")\n * term(\"cohort\", \"group of students who entered the same semester or academic year\")\n *\n * @example\n * // Finance/Banking dataset\n * term(\"NPL\", \"non-performing loan - loan past due 90+ days\")\n * term(\"basis points\", \"one hundredth of a percentage point (1% = 100 bps)\")\n * term(\"AUM\", \"assets under management - total market value of client investments\")\n */\nexport function term(name: string, definition: string): Teachables {\n return {\n type: 'term',\n encode: () => ({ type: 'term', name, definition }),\n decode: () =>\n wrapBlock('term', [leaf('name', name), leaf('definition', definition)]),\n };\n}\n\n/**\n * Teach the system behavioral rules and constraints that should always apply.\n *\n * Use this for business logic, data quality rules, or query preferences that should\n * be automatically applied to all relevant queries. Hints are injected as constraints\n * in the system prompt.\n *\n * @param text - The rule or constraint to follow (use imperative language)\n *\n * @example\n * // Manufacturing/Supply Chain dataset\n * hint(\"Always exclude work orders with status = 'simulation' from production metrics\")\n * hint(\"When calculating OEE (overall equipment effectiveness), only count scheduled production time\")\n * hint(\"Defect rates should be calculated per batch, not per individual unit, for consistency\")\n *\n * @example\n * // Real Estate/Property dataset\n * hint(\"Never include properties with listing_status = 'draft' in market analysis\")\n * hint(\"Always filter out duplicate MLS listings - use the earliest listing_date for each property_id\")\n * hint(\"Square footage comparisons must specify if including or excluding basement/garage\")\n *\n * @example\n * // Social Media/Content Platform dataset\n * hint(\"Engagement metrics should exclude bot accounts identified by is_verified_human = false\")\n * hint(\"View counts reset daily - always use cumulative_views for historical analysis\")\n * hint(\"Default content filters to published_status = 'public' unless analyzing drafts\")\n */\nexport function hint(text: string): Teachables {\n return {\n type: 'hint',\n encode: () => ({ type: 'hint', text }),\n decode: () => leaf('hint', text),\n };\n}\n\n/**\n * Define hard guardrails, safety rules, and compliance boundaries the system must enforce.\n *\n * Use this for \"never do\" rules, sensitive data handling, and required behaviors when\n * certain conditions occur. Guardrails should be explicit and action oriented.\n *\n * @param input.rule - The guardrail or restriction to enforce\n * @param input.reason - Why this guardrail exists (compliance, security, performance)\n * @param input.action - What to do when this guardrail is triggered (block, ask, sanitize)\n *\n * @example\n * // Healthcare dataset\n * guardrail({\n * rule: \"Never return PHI like SSN, MRN, or full address in query results\",\n * reason: \"HIPAA compliance\",\n * action: \"If asked, state that identifiable patient data cannot be shared; offer de-identified aggregates instead\"\n * })\n *\n * @example\n * // Finance dataset\n * guardrail({\n * rule: \"Block any query exposing employee-level compensation by name\",\n * reason: \"Confidential payroll data\",\n * action: \"Provide ranges grouped by department or level instead of individual salaries\"\n * })\n *\n * @example\n * // E-commerce dataset\n * guardrail({\n * rule: \"Warn when a query would scan more than 10 million rows; require a narrower date range\",\n * reason: \"Performance and cost control\",\n * action: \"Ask the user to add filters (recent timeframe, specific categories) before proceeding\"\n * })\n */\nexport function guardrail(input: {\n rule: string;\n reason?: string;\n action?: string;\n}): Teachables {\n const { rule, reason, action } = input;\n return {\n type: 'guardrail',\n encode: () => ({ type: 'guardrail', rule, reason, action }),\n decode: () =>\n wrapBlock('guardrail', [\n leaf('rule', rule),\n reason ? leaf('reason', reason) : '',\n action ? leaf('action', action) : '',\n ]),\n };\n}\n\n/**\n * Teach the system a rich understanding of a single concept using metaphors and explanations.\n *\n * Use this when a simple term definition isn't enough - when you need to convey deeper\n * understanding about how to think about and calculate a metric or concept.\n *\n * @param input.concept - The concept being explained\n * @param input.explanation - A metaphor or detailed explanation (often using real-world comparisons)\n * @param input.therefore - Optional actionable instruction based on this understanding\n *\n * @example\n * // Gaming/Entertainment dataset\n * explain({\n * concept: \"daily active users to monthly active users ratio\",\n * explanation: \"like measuring how many club members visit daily vs just once a month - shows stickiness\",\n * therefore: \"Calculate as DAU / MAU, where higher ratio (closer to 1) means more engaged user base\"\n * })\n *\n * @example\n * // HR/Employee Management dataset\n * explain({\n * concept: \"time to fill\",\n * explanation: \"like measuring how long a house sits on the market - from posting job to accepting offer\",\n * therefore: \"Calculate as days between job_posted_date and offer_accepted_date, exclude cancelled requisitions\"\n * })\n *\n * @example\n * // Telecommunications dataset\n * explain({\n * concept: \"network congestion ratio\",\n * explanation: \"like rush hour traffic density - measures actual usage vs total capacity at peak times\",\n * therefore: \"Calculate as (peak_hour_bandwidth_used / total_bandwidth_capacity) during busiest hour of day\"\n * })\n */\nexport function explain(input: {\n concept: string;\n explanation: string;\n therefore?: string;\n}): Teachables {\n const { concept, explanation, therefore } = input;\n return {\n type: 'explain',\n encode: () => ({ type: 'explain', concept, explanation, therefore }),\n decode: () =>\n wrapBlock('explanation', [\n leaf('concept', concept),\n leaf('details', explanation),\n therefore ? leaf('therefore', therefore) : '',\n ]),\n };\n}\n\n/**\n * Teach the system through concrete examples of question \u2192 SQL pairs.\n *\n * Use this for few-shot learning - show the system exactly how to translate\n * specific types of questions into SQL queries. Great for establishing patterns\n * and handling domain-specific query structures.\n *\n * @param input.question - The natural language question or request\n * @param input.answer - The correct answer that responds to the question\n * @param input.note - Optional note or explanation about the example\n *\n * @example\n * // Energy/Utilities dataset\n * example({\n * question: \"show me peak demand hours for the last week\",\n * answer: \"SELECT DATE_TRUNC('hour', reading_timestamp) as hour, MAX(consumption_kwh) as peak_demand FROM meter_readings WHERE reading_timestamp >= CURRENT_DATE - INTERVAL '7 days' GROUP BY hour ORDER BY peak_demand DESC LIMIT 10\"\n * })\n *\n * @example\n * // Agriculture/Farm Management dataset\n * example({\n * question: \"what is the average yield per acre by crop type this season\",\n * answer: \"SELECT crop_type, AVG(harvest_quantity / field_acres) as yield_per_acre FROM harvests WHERE harvest_date >= '2024-01-01' GROUP BY crop_type ORDER BY yield_per_acre DESC\"\n * })\n *\n * @example\n * // Travel/Hospitality dataset\n * example({\n * question: \"show me hotel occupancy rate for this month\",\n * answer: \"SELECT hotel_name, (SUM(occupied_rooms) / SUM(total_rooms)) * 100 as occupancy_rate FROM daily_occupancy WHERE date >= DATE_TRUNC('month', CURRENT_DATE) GROUP BY hotel_id, hotel_name ORDER BY occupancy_rate DESC\",\n * note: \"Occupancy rate is a percentage - multiply by 100 for readable output\"\n * })\n */\nexport function example(input: {\n question: string;\n answer: string;\n note?: string;\n}): Teachables {\n const { question, answer, note } = input;\n return {\n type: 'example',\n encode: () => ({ type: 'example', question, answer, note }),\n decode: () =>\n wrapBlock('example', [\n leaf('question', question),\n leaf('answer', answer),\n note ? leaf('note', note) : '',\n ]),\n };\n}\n\n/**\n * Teach the system when and what to ask for clarification.\n *\n * Use this to handle ambiguous terms or situations where the system should\n * proactively ask the user for more information before generating a query.\n * Makes the system more conversational and precise.\n *\n * @param input.when - The condition or trigger that should prompt clarification\n * @param input.ask - The question to ask the user\n * @param input.reason - Why this clarification is necessary (helps system understand importance)\n *\n * @example\n * // Marketing/Advertising dataset\n * clarification({\n * when: \"user asks for 'conversion rate'\",\n * ask: \"Which conversion: click-to-lead, lead-to-opportunity, or opportunity-to-customer?\",\n * reason: \"Conversion rate means different things at each funnel stage - need to specify which metric\"\n * })\n *\n * @example\n * // Food Delivery dataset\n * clarification({\n * when: \"user asks about 'delivery time'\",\n * ask: \"Do you mean estimated time at order, actual delivery time, or time from kitchen to door?\",\n * reason: \"Multiple time metrics exist - estimated vs actual impacts customer satisfaction differently\"\n * })\n *\n * @example\n * // Fitness/Gym Management dataset\n * clarification({\n * when: \"user mentions 'active members'\",\n * ask: \"Do you mean paid memberships or members who actually visited in last 30 days?\",\n * reason: \"Many paid members don't use facilities - different metrics for revenue vs utilization\"\n * })\n */\nexport function clarification(input: {\n when: string;\n ask: string;\n reason: string;\n}): Teachables {\n const { when, ask, reason } = input;\n return {\n type: 'clarification',\n encode: () => ({ type: 'clarification', when, ask, reason }),\n decode: () =>\n wrapBlock('clarification', [\n leaf('when', when),\n leaf('ask', ask),\n leaf('reason', reason),\n ]),\n };\n}\n\n/**\n * Teach the system multi-step analytical processes that can't be solved with a single query.\n *\n * Use this for complex analytical tasks that require multiple CTEs, sequential logic,\n * or specific methodologies. Workflows teach the system HOW to approach a type of analysis.\n *\n * @param input.task - Name of the analytical task\n * @param input.steps - Sequential steps to execute (can include SQL snippets or descriptions)\n * @param input.triggers - Optional phrases that should activate this workflow\n * @param input.notes - Optional additional context, warnings, or guidance\n *\n * @example\n * // Insurance dataset\n * workflow({\n * task: \"Claims Loss Ratio Analysis\",\n * triggers: [\"loss ratio\", \"claims ratio\", \"underwriting performance\"],\n * steps: [\n * \"Calculate total claims paid for each policy period\",\n * \"Calculate total premiums earned for same period\",\n * \"Compute loss ratio as (claims_paid / premiums_earned) * 100\",\n * \"Segment by policy type, geography, and underwriter\",\n * \"Identify policies with loss ratio > 100% (losing money)\",\n * \"Calculate trend over time using rolling 12-month windows\"\n * ],\n * notes: \"Use incurred date for claims, not paid date. Exclude reinsurance recoveries from claims total.\"\n * })\n *\n * @example\n * // Media/Publishing dataset\n * workflow({\n * task: \"Content Performance Funnel\",\n * triggers: [\"content funnel\", \"engagement funnel\", \"content performance\"],\n * steps: [\n * \"Count total impressions (articles shown) per content piece\",\n * \"Count click-throughs (articles opened)\",\n * \"Count scroll depth > 50% (meaningful engagement)\",\n * \"Count shares, comments, or saves (viral actions)\",\n * \"Calculate conversion rate at each funnel stage\",\n * \"Identify top-performing content by final conversion rate\"\n * ],\n * notes: \"Requires multiple event types. Join events table multiple times or use conditional aggregation.\"\n * })\n *\n * @example\n * // Sports Analytics dataset\n * workflow({\n * task: \"Player Performance Rating Calculation\",\n * triggers: [\"player rating\", \"performance score\", \"player analytics\"],\n * steps: [\n * \"Aggregate per-game stats: points, assists, rebounds, turnovers\",\n * \"Calculate efficiency metrics: shooting percentage, plus/minus\",\n * \"Normalize each metric using z-scores vs league average\",\n * \"Apply position-specific weights to each metric\",\n * \"Combine weighted scores into overall performance rating (0-100)\",\n * \"Rank players within position group and overall\"\n * ],\n * notes: \"Requires league-wide statistics for normalization. Update weights each season based on game trends.\"\n * })\n */\nexport function workflow(input: {\n task: string;\n steps: string[];\n triggers?: string[];\n notes?: string;\n}): Teachables {\n const { task, steps, triggers, notes } = input;\n return {\n type: 'workflow',\n encode: () => ({ type: 'workflow', task, steps, triggers, notes }),\n decode: () =>\n wrapBlock('workflow', [\n leaf('task', task),\n triggers?.length ? list('triggers', triggers, 'trigger') : '',\n list('steps', steps, 'step'),\n notes ? leaf('notes', notes) : '',\n ]),\n };\n}\n\n/**\n * Teach the system about data quirks, edge cases, or database-specific issues and their workarounds.\n *\n * Use this to document weird data patterns, database limitations, or special handling\n * required for specific scenarios. Helps the system navigate real-world messiness.\n *\n * @param input.issue - Description of the quirk, edge case, or problem\n * @param input.workaround - How to handle or work around this issue\n *\n * @example\n * // Government/Public Services dataset\n * quirk({\n * issue: \"Citizen IDs contain leading zeros but are stored as integers, losing the zeros\",\n * workaround: \"Always cast to VARCHAR and use LPAD(citizen_id::VARCHAR, 10, '0') to restore leading zeros\"\n * })\n *\n * @example\n * // Aviation dataset\n * quirk({\n * issue: \"Flight times crossing midnight show as negative duration (landing before takeoff)\",\n * workaround: \"Add 24 hours when calculated duration < 0: CASE WHEN duration < 0 THEN duration + INTERVAL '24 hours' ELSE duration END\"\n * })\n *\n * @example\n * // Automotive/Dealership dataset\n * quirk({\n * issue: \"VIN numbers with letter 'O' were incorrectly entered as zero '0' in legacy data\",\n * workaround: \"When searching by VIN, use REPLACE(vin, '0', 'O') or fuzzy matching to handle both cases\"\n * })\n */\nexport function quirk(input: {\n issue: string;\n workaround: string;\n}): Teachables {\n const { issue, workaround } = input;\n return {\n type: 'quirk',\n encode: () => ({ type: 'quirk', issue, workaround }),\n decode: () =>\n wrapBlock('quirk', [\n leaf('issue', issue),\n leaf('workaround', workaround),\n ]),\n };\n}\n\n/**\n * Teach the system SQL style preferences and coding standards for generated queries.\n *\n * Use this to enforce consistent SQL formatting, naming conventions, and best practices\n * specific to your team or organization. Improves readability and maintainability.\n *\n * @param input.prefer - Preferred SQL style or pattern\n * @param input.never - Optional anti-pattern to avoid\n * @param input.always - Optional rule that must always be followed\n *\n * @example\n * // Non-profit/Charity dataset\n * styleGuide({\n * prefer: \"Use donor-centric language in column aliases: 'donor_name' not 'customer_name'\",\n * never: \"Never expose internal donor IDs in external reports - use public gift IDs\",\n * always: \"Always include fiscal year in date-based aggregations (FY starts July 1)\"\n * })\n *\n * @example\n * // Legal/Law Firm dataset\n * styleGuide({\n * prefer: \"Use billable_hours with 2 decimal precision for accurate client billing\",\n * never: \"Never include attorney_rate in queries visible to paralegals - confidential data\",\n * always: \"Always filter by matter_status = 'open' unless specifically analyzing closed cases\"\n * })\n *\n * @example\n * // Inventory/Warehouse dataset\n * styleGuide({\n * prefer: \"Use location_id in joins rather than location_name (duplicates exist across warehouses)\",\n * never: \"Never aggregate inventory without grouping by warehouse_id first\",\n * always: \"Always use inventory_on_hand - inventory_reserved for available stock calculations\"\n * })\n */\nexport function styleGuide(input: {\n prefer: string;\n never?: string;\n always?: string;\n}): Teachables {\n const { prefer, never, always } = input;\n return {\n type: 'styleGuide',\n encode: () => ({ type: 'styleGuide', prefer, never, always }),\n decode: () =>\n wrapBlock('style_guide', [\n leaf('prefer', prefer),\n always ? leaf('always', always) : '',\n never ? leaf('never', never) : '',\n ]),\n };\n}\n\n/**\n * Teach the system by comparing related concepts through real-world analogies.\n *\n * Use this to teach relational understanding between two concepts by drawing comparisons\n * to familiar real-world scenarios. Helps the system understand WHY concepts differ and\n * when to use each one appropriately.\n *\n * @param input.concept - Array of two related concepts to compare\n * @param input.relationship - The comparison/analogy using real-world examples\n * @param input.insight - Optional key insight the analogy reveals\n * @param input.therefore - Optional actionable instruction based on this understanding\n * @param input.pitfall - Optional common mistake to avoid\n *\n * @example\n * // E-commerce dataset\n * analogy({\n * concept: [\"cart abandonment\", \"browse abandonment\"],\n * relationship: \"Cart abandonment is like leaving items at a checkout counter, browse abandonment is like window shopping without picking anything up\",\n * insight: \"Cart abandonment shows purchase intent (added to cart), browse abandonment shows only interest\",\n * therefore: \"Prioritize cart abandonment recovery campaigns - higher conversion potential than browse\",\n * pitfall: \"Don't combine both into generic 'abandonment rate' - they need different marketing strategies\"\n * })\n *\n * @example\n * // SaaS dataset\n * analogy({\n * concept: [\"logo churn\", \"revenue churn\"],\n * relationship: \"Logo churn is like counting how many customers left the store, revenue churn is how much money walked out\",\n * insight: \"Losing 10 small customers (high logo churn) might hurt less than losing 1 enterprise customer (high revenue churn)\",\n * therefore: \"Always report both metrics - logo churn for customer satisfaction, revenue churn for financial health\",\n * pitfall: \"Don't use logo churn to predict revenue impact - customer size distribution matters\"\n * })\n *\n * @example\n * // Healthcare dataset\n * analogy({\n * concept: [\"incident\", \"prevalence\"],\n * relationship: \"Incidence is like new house sales this month, prevalence is total houses currently occupied\",\n * insight: \"Incidence measures new cases over time, prevalence measures all existing cases at a point in time\",\n * therefore: \"For tracking disease outbreaks use incidence rate, for resource planning use prevalence\",\n * pitfall: \"Don't sum incidence rates across time periods - it's a rate not a count\"\n * })\n */\nexport function analogy(input: {\n concept: string[];\n relationship: string;\n insight?: string;\n therefore?: string;\n pitfall?: string;\n}): Teachables {\n const { concept, relationship, insight, therefore, pitfall } = input;\n return {\n type: 'analogy',\n encode: () => ({\n type: 'analogy',\n concept,\n relationship,\n insight,\n therefore,\n pitfall,\n }),\n decode: () =>\n wrapBlock('analogy', [\n list('concepts', concept, 'concept'),\n leaf('relationship', relationship),\n insight ? leaf('insight', insight) : '',\n therefore ? leaf('therefore', therefore) : '',\n pitfall ? leaf('pitfall', pitfall) : '',\n ]),\n };\n}\n\n/**\n * Map business terms directly to SQL expressions or fragments.\n *\n * Use this to teach the system how to CALCULATE or QUERY specific business concepts.\n * The system will substitute these SQL patterns when users mention the term.\n *\n * **Glossary vs Alias:**\n * - `alias` = user vocabulary \u2192 table/column name (\"the big table\" \u2192 \"orders table\")\n * - `glossary` = business term \u2192 SQL expression (\"revenue\" \u2192 \"SUM(orders.total_amount)\")\n *\n * In short: alias renames, glossary computes.\n *\n * @param entries - Record mapping business terms to their SQL expressions\n *\n * @example\n * glossary({\n * \"revenue\": \"SUM(orders.total_amount)\",\n * \"average order value\": \"AVG(orders.total_amount)\",\n * \"active user\": \"last_login > NOW() - INTERVAL '30 days'\",\n * \"churned\": \"status = 'churned'\",\n * \"power user\": \"order_count > 10\",\n * \"net revenue\": \"SUM(orders.total_amount) - SUM(refunds.amount)\",\n * })\n */\nexport function glossary(entries: Record<string, string>): Teachables {\n return {\n type: 'glossary',\n encode: () => ({ type: 'glossary', entries }),\n decode: () =>\n wrapBlock(\n 'glossary',\n Object.entries(entries).map(([term, sql]) =>\n wrapBlock('entry', [leaf('term', term), leaf('sql', sql)]),\n ),\n ),\n };\n}\n\n// =============================================================================\n// User-Specific Teachable Types\n// =============================================================================\n\n/**\n * Define the user's identity including name and/or role.\n *\n * Use this to capture who the user is and what lens they view data through.\n * Helps tailor explanations, terminology, and focus areas.\n *\n * @param input.name - The user's name (optional)\n * @param input.role - The user's role or position (optional)\n *\n * @example\n * identity({ name: \"John\", role: \"VP of Sales\" })\n * identity({ role: \"Data analyst in the marketing team\" })\n * identity({ name: \"Sarah\" })\n * identity({ role: \"Finance manager focused on cost optimization\" })\n */\nexport function identity(input: { name?: string; role?: string }): Teachables {\n const { name, role } = input;\n return {\n type: 'identity',\n encode: () => ({ type: 'identity', name, role }),\n decode: () =>\n wrapBlock('identity', [\n name ? leaf('name', name) : '',\n role ? leaf('role', role) : '',\n ]),\n };\n}\n\n/**\n * Define an AI persona with a name, role, and communication tone.\n *\n * Use this to customize the assistant's personality and how it communicates.\n * The persona influences the style and approach of responses.\n *\n * @param input.name - The persona's name\n * @param input.role - The persona's role or expertise\n * @param input.tone - The communication style (e.g., friendly, professional, concise)\n *\n * @example\n * persona({ name: \"DataBot\", role: \"SQL Expert\", tone: \"friendly and encouraging\" })\n * persona({ name: \"QueryMaster\", role: \"Database Analyst\", tone: \"professional and concise\" })\n * persona({ name: \"SQLHelper\", role: \"Data Assistant\", tone: \"casual and approachable\" })\n */\nexport function persona(input: {\n name: string;\n role: string;\n tone?: string;\n}): Teachables {\n const { name, role, tone } = input;\n return {\n type: 'persona',\n encode: () => ({ type: 'persona', name, role, tone: tone ?? '' }),\n decode: () =>\n wrapBlock('persona', [\n leaf('name', name),\n leaf('role', role),\n tone ? leaf('tone', tone) : '',\n ]),\n };\n}\n\n/**\n * Define user-specific term meanings and vocabulary.\n *\n * Use this when the user has their own definitions for terms that might\n * differ from standard or domain definitions. Like `term()` but personal.\n *\n * @param termName - The term the user uses\n * @param meaning - What the user means by this term\n *\n * @example\n * alias(\"revenue\", \"gross revenue before deductions, not net\")\n * alias(\"active users\", \"users who logged in within the last 30 days\")\n * alias(\"the big table\", \"the orders table\")\n * alias(\"Q4\", \"October through December, not fiscal Q4\")\n */\nexport function alias(termName: string, meaning: string): Teachables {\n return {\n type: 'alias',\n encode: () => ({ type: 'alias', term: termName, meaning }),\n decode: () =>\n wrapBlock('alias', [leaf('term', termName), leaf('meaning', meaning)]),\n };\n}\n\n/**\n * Define how the user prefers results presented.\n *\n * Use this to capture output formatting, style, and behavioral preferences\n * that should apply to all interactions with this user.\n *\n * @param aspect - What aspect of output this preference applies to\n * @param value - The user's preference\n *\n * @example\n * preference(\"date format\", \"YYYY-MM-DD\")\n * preference(\"output style\", \"tables over charts unless trend data\")\n * preference(\"detail level\", \"always show the SQL query in responses\")\n * preference(\"row limit\", \"default to 50 rows unless I ask for more\")\n * preference(\"explanation style\", \"brief and to the point\")\n */\nexport function preference(aspect: string, value: string): Teachables {\n return {\n type: 'preference',\n encode: () => ({ type: 'preference', aspect, value }),\n decode: () =>\n wrapBlock('preference', [leaf('aspect', aspect), leaf('value', value)]),\n };\n}\n\n/**\n * Define the user's current working focus or project.\n *\n * Use this to capture temporary context that helps inform defaults,\n * assumptions, and suggestions. Should be updated as focus changes.\n *\n * @param description - What the user is currently working on\n *\n * @example\n * context(\"Preparing Q4 board presentation\")\n * context(\"Investigating drop in signups last week\")\n * context(\"Working on EMEA regional analysis for strategy meeting\")\n * context(\"Debugging discrepancy in revenue numbers\")\n */\nexport function context(description: string): Teachables {\n return {\n type: 'context',\n encode: () => ({ type: 'context', description }),\n decode: () => leaf('context', description),\n };\n}\n\n/**\n * Record a correction the user made to previous understanding.\n *\n * Use this when the user corrects a misunderstanding about data, columns,\n * or business logic. Prevents repeating the same mistake.\n *\n * @param subject - What was misunderstood\n * @param clarification - The correct understanding\n *\n * @example\n * correction(\"status column\", \"1 = active, 0 = inactive, not boolean true/false\")\n * correction(\"orders table\", \"Use orders_v2, not the deprecated legacy_orders table\")\n * correction(\"date field\", \"order_date is when order was placed, ship_date is when shipped\")\n * correction(\"revenue calculation\", \"Must exclude refunds and chargebacks\")\n */\nexport function correction(subject: string, clarification: string): Teachables {\n return {\n type: 'correction',\n encode: () => ({ type: 'correction', subject, clarification }),\n decode: () =>\n wrapBlock('correction', [\n leaf('subject', subject),\n leaf('clarification', clarification),\n ]),\n };\n}\n\nexport function teachable(\n tag: string,\n ...teachables: Teachables[]\n): Teachables {\n return {\n type: 'user_profile',\n encode: () => teachables[0]?.encode() ?? ({ type: 'context', description: '' }),\n decode: () => toInstructions(tag, ...teachables),\n };\n}\n\nexport function toInstructions(\n tag: string,\n ...teachables: Teachables[]\n): string {\n if (!teachables.length) {\n return '';\n }\n\n const grouped = new Map<Teachables['type'], Teachables[]>();\n for (const teachable of teachables) {\n const existing = grouped.get(teachable.type) ?? [];\n existing.push(teachable);\n grouped.set(teachable.type, existing);\n }\n\n const definedTypes = new Set(SECTION_ORDER.map((s) => s.type));\n\n const sections = SECTION_ORDER.map(({ type, tag }) => {\n const items = grouped.get(type);\n if (!items?.length) {\n return '';\n }\n const renderedItems = items\n .map((item) => item.decode().trim())\n .filter(Boolean)\n .map((item) => indentBlock(item, 2))\n .join('\\n');\n if (!renderedItems.length) {\n return '';\n }\n return `<${tag}>\\n${renderedItems}\\n</${tag}>`;\n }).filter((section): section is string => Boolean(section));\n\n // Render types not defined in SECTION_ORDER at the end\n for (const [type, items] of grouped) {\n if (definedTypes.has(type)) {\n continue;\n }\n const renderedItems = items\n .map((item) => item.decode().trim())\n .filter(Boolean)\n .map((item) => indentBlock(item, 2))\n .join('\\n');\n if (renderedItems.length) {\n sections.push(renderedItems);\n }\n }\n\n if (!sections.length) {\n return '';\n }\n\n const content = indentBlock(sections.join('\\n'), 2);\n return `<${tag}>\\n${content}\\n</${tag}>`;\n}\n\nconst SECTION_ORDER: Array<{ type: Teachables['type']; tag: string }> = [\n // User context (render first - most important for personalization)\n { type: 'identity', tag: 'identity' },\n { type: 'persona', tag: 'persona' },\n { type: 'context', tag: 'user_context' },\n { type: 'preference', tag: 'user_preferences' },\n { type: 'alias', tag: 'user_vocabulary' },\n { type: 'correction', tag: 'user_corrections' },\n // Domain knowledge\n { type: 'guardrail', tag: 'guardrails' },\n { type: 'styleGuide', tag: 'style_guides' },\n { type: 'hint', tag: 'hints' },\n { type: 'clarification', tag: 'clarifications' },\n { type: 'workflow', tag: 'workflows' },\n { type: 'quirk', tag: 'quirks' },\n { type: 'term', tag: 'terminology' },\n { type: 'explain', tag: 'explanations' },\n { type: 'analogy', tag: 'analogies' },\n { type: 'glossary', tag: 'glossary' },\n { type: 'example', tag: 'examples' },\n];\n\nexport function toTeachables(generated: GeneratedTeachable[]): Teachables[] {\n return generated.map((item) => {\n switch (item.type) {\n case 'persona':\n return persona({ name: item.name, role: item.role, tone: item.tone });\n case 'term':\n return term(item.name, item.definition);\n case 'hint':\n return hint(item.text);\n case 'guardrail':\n return guardrail({\n rule: item.rule,\n reason: item.reason,\n action: item.action,\n });\n case 'explain':\n return explain({\n concept: item.concept,\n explanation: item.explanation,\n therefore: item.therefore,\n });\n case 'example':\n return example({\n question: item.question,\n answer: item.answer,\n note: item.note,\n });\n case 'clarification':\n return clarification({\n when: item.when,\n ask: item.ask,\n reason: item.reason,\n });\n case 'workflow':\n return workflow({\n task: item.task,\n steps: item.steps,\n triggers: item.triggers,\n notes: item.notes,\n });\n case 'quirk':\n return quirk({\n issue: item.issue,\n workaround: item.workaround,\n });\n case 'styleGuide':\n return styleGuide({\n prefer: item.prefer,\n never: item.never,\n always: item.always,\n });\n case 'analogy':\n return analogy({\n concept: item.concept,\n relationship: item.relationship,\n insight: item.insight,\n therefore: item.therefore,\n pitfall: item.pitfall,\n });\n case 'glossary':\n return glossary(item.entries);\n // User-specific teachable types\n case 'identity':\n return identity({ name: item.name, role: item.role });\n case 'alias':\n return alias(item.term, item.meaning);\n case 'preference':\n return preference(item.aspect, item.value);\n case 'context':\n return context(item.description);\n case 'correction':\n return correction(item.subject, item.clarification);\n }\n });\n}\n\n/**\n * Convert Teachables back to GeneratedTeachable format for storage.\n *\n * @param teachables - Array of Teachables to convert\n * @returns Array of GeneratedTeachable objects suitable for storage\n *\n * @example\n * const teachings = [term('NPL', 'non-performing loan'), hint('Always filter by status')];\n * const forStorage = fromTeachables(teachings);\n * // [{ type: 'term', name: 'NPL', definition: 'non-performing loan' }, { type: 'hint', text: 'Always filter by status' }]\n */\nexport function fromTeachables(teachables: Teachables[]): GeneratedTeachable[] {\n return teachables.map((t) => t.encode());\n}\n\n/**\n * Default export containing all system teachable factory functions.\n * Excludes user-specific teachables (identity, alias, preference, context, correction).\n */\nexport default {\n persona,\n term,\n hint,\n guardrail,\n explain,\n example,\n clarification,\n workflow,\n quirk,\n styleGuide,\n analogy,\n glossary,\n teachable,\n};\n", "import {\n clarification,\n example,\n explain,\n guardrail,\n hint,\n toInstructions,\n workflow,\n} from '../teach/teachables.ts';\n\nexport default toInstructions(\n 'memory_guidelines',\n\n // Section 1: Core behavior\n guardrail({\n rule: 'Silently store user information when revealed. Respond to memory-related requests.',\n reason: 'Memory enables personalized responses across conversations',\n action:\n 'Store silently on reveal. Respond explicitly when asked about memories.',\n }),\n\n // Section 2: Workflows for memory operations\n\n workflow({\n task: 'Store user identity silently',\n triggers: [\"I'm a\", 'I work as', 'my name is', 'my role is'],\n steps: [\n 'Extract name and/or role from the statement',\n 'Call remember_memory() with type: \"identity\" and name/role fields',\n 'Do NOT announce or confirm - continue conversation naturally',\n ],\n notes:\n 'This should happen silently without disrupting the conversation flow.',\n }),\n\n workflow({\n task: 'Store user preferences and context silently',\n triggers: ['When I say', 'I prefer', \"I'm working on\"],\n steps: [\n 'Identify the memory type (alias/preference/context/correction)',\n 'Extract the relevant information',\n 'Call remember_memory() with appropriate type and fields',\n 'Do NOT announce or confirm - continue conversation naturally',\n ],\n notes:\n 'This should happen silently without disrupting the conversation flow.',\n }),\n\n workflow({\n task: 'Forget a memory',\n triggers: ['forget that', 'remove my', 'delete the', \"don't remember that\"],\n steps: [\n 'Call recall_memory() to list relevant memories',\n 'Find the memory ID that matches user request',\n 'Call forget_memory({ id }) with the found ID',\n 'Confirm to user what was forgotten',\n ],\n }),\n\n workflow({\n task: 'Update a memory',\n triggers: ['actually now I', 'I changed', 'update my', 'no longer'],\n steps: [\n 'Call recall_memory() to find the existing memory',\n 'Get the memory ID from results',\n 'Call update_memory({ id, memory }) with new data',\n 'Confirm the update to user',\n ],\n }),\n\n // Section 3: Type disambiguation\n\n explain({\n concept: 'identity vs context',\n explanation:\n 'Identity = WHO the user is (name and/or role, permanent). Context = WHAT they are working on (temporary focus).',\n therefore: 'Identity rarely changes. Context changes per project/task.',\n }),\n\n explain({\n concept: 'alias vs correction',\n explanation:\n 'Alias = user defines their own term/shorthand. Correction = user fixes a misunderstanding about existing data/schema.',\n therefore: 'Alias is vocabulary. Correction is data clarification.',\n }),\n\n explain({\n concept: 'preference memory type',\n explanation:\n 'Stores output/style/format preferences. Fields: { aspect: string, value: string }',\n therefore: 'Use for formatting, limits, display style, data scope filters',\n }),\n\n // Section 4: Clarifications for ambiguous situations\n\n clarification({\n when: 'user says something like \"X actually means Y\" but unclear if defining their term or correcting data',\n ask: 'Are you defining your own shorthand for this term, or correcting how the data/schema actually works?',\n reason:\n 'Alias is personal vocabulary. Correction is a data/schema clarification that applies universally.',\n }),\n\n clarification({\n when: 'user mentions a project or task that could be their identity or current focus',\n ask: 'Is this your ongoing identity (name/role), or a specific project you are currently working on?',\n reason:\n 'Identity is permanent. Context is temporary focus that may change.',\n }),\n\n // Section 5: Examples\n\n // Identity - role\n example({\n question: \"I'm the VP of Sales\",\n answer: 'remember_memory({ memory: { type: \"identity\", role: \"VP of Sales\" }})',\n note: 'Identity stores role',\n }),\n\n // Identity - name\n example({\n question: 'My name is Sarah',\n answer: 'remember_memory({ memory: { type: \"identity\", name: \"Sarah\" }})',\n note: 'Identity stores name',\n }),\n\n // Context\n example({\n question: \"I'm analyzing Q4 performance\",\n answer: 'remember_memory({ memory: { type: \"context\", description: \"Analyzing Q4 performance\" }})',\n note: 'Current task = context',\n }),\n\n // Alias\n example({\n question: 'When I say \"big customers\", I mean revenue > $1M',\n answer: 'remember_memory({ memory: { type: \"alias\", term: \"big customers\", meaning: \"revenue > $1M\" }})',\n note: 'User defining their vocabulary = alias',\n }),\n\n // Correction\n example({\n question:\n 'No, the status column uses 1 for active, not the string \"active\"',\n answer: 'remember_memory({ memory: { type: \"correction\", subject: \"status column values\", clarification: \"Uses 1 for active, not string\" }})',\n note: 'Correcting schema/data assumption = correction',\n }),\n\n // Preference\n example({\n question: 'Always show dates as YYYY-MM-DD',\n answer: 'remember_memory({ memory: { type: \"preference\", aspect: \"date format\", value: \"YYYY-MM-DD\" }})',\n }),\n\n // Recall\n example({\n question: 'What do you remember about me?',\n answer: 'recall_memory({})',\n note: 'List all stored memories',\n }),\n\n // Section 6: What NOT to remember\n hint('Do NOT remember one-time query details like \"show last 10 orders\"'),\n hint(\n 'Do NOT remember information already stored - use recall_memory to check first',\n ),\n hint('Do NOT remember obvious or universal facts'),\n);\n", "import { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport pLimit from 'p-limit';\n\nexport interface CheckpointOptions {\n /** Path to the checkpoint file */\n path: string;\n /** Hash to detect config changes - if changed, checkpoint is invalidated */\n configHash?: string;\n}\n\n/**\n * Codec for encoding/decoding values during checkpoint operations.\n * Use this when storing objects with methods (like Teachables) that need\n * to be serialized to plain JSON and restored with their methods.\n */\nexport interface Codec<T, TSerialized = unknown> {\n /** Convert runtime value to JSON-serializable format */\n encode: (value: T) => TSerialized;\n /** Convert stored JSON back to runtime value */\n decode: (serialized: TSerialized) => T;\n}\n\ninterface PointEntry {\n inputHash: string;\n output: unknown;\n}\n\ninterface PointData {\n committed: boolean;\n entries: PointEntry[];\n}\n\ninterface CheckpointFile {\n configHash?: string;\n points: Record<string, PointData>;\n}\n\nexport class Checkpoint {\n private points: Record<string, PointData>;\n\n private constructor(\n private path: string,\n private configHash: string | undefined,\n points: Record<string, PointData>,\n ) {\n this.points = points;\n }\n\n /**\n * Load checkpoint from file, or return empty checkpoint if none exists.\n * Handles corrupted files and config changes gracefully.\n */\n static async load(options: CheckpointOptions): Promise<Checkpoint> {\n const { path, configHash } = options;\n\n if (existsSync(path)) {\n try {\n const content = readFileSync(path, 'utf-8');\n const file: CheckpointFile = JSON.parse(content);\n\n // Check if config changed\n if (configHash && file.configHash && file.configHash !== configHash) {\n console.log('\u26A0 Config changed, starting fresh');\n return new Checkpoint(path, configHash, {});\n }\n\n const points = file.points ?? {};\n const totalEntries = Object.values(points).reduce(\n (sum, p) => sum + p.entries.length,\n 0,\n );\n console.log(`\u2713 Resuming from checkpoint (${totalEntries} entries)`);\n return new Checkpoint(path, configHash, points);\n } catch {\n console.log('\u26A0 Checkpoint corrupted, starting fresh');\n return new Checkpoint(path, configHash, {});\n }\n }\n\n console.log('Starting new checkpoint');\n return new Checkpoint(path, configHash, {});\n }\n\n /**\n * Run a single computation with checkpointing.\n * If already completed, returns cached value.\n *\n * @param key - Unique identifier for this computation\n * @param computation - Async function that produces the value\n * @param codec - Optional codec for encoding/decoding non-primitive values\n */\n async run<T>(\n key: string,\n computation: () => Promise<T>,\n codec?: Codec<T>,\n ): Promise<T> {\n const point = this.point<T>(key);\n\n // Use fixed input hash for single-value runs\n return point.through(\n 'single',\n async () => {\n const result = await computation();\n return codec ? (codec.encode(result) as T) : result;\n },\n codec,\n );\n }\n\n /**\n * Create a resumable checkpoint point for iterative operations.\n *\n * @param step - Unique identifier for this checkpoint point\n */\n point<T>(step: string): Point<T> {\n if (!this.points[step]) {\n this.points[step] = { committed: false, entries: [] };\n }\n return new Point<T>(this.points[step], () => this.save());\n }\n\n /**\n * Process each input with automatic checkpointing and concurrency.\n *\n * @param step - Unique identifier for this checkpoint\n * @param inputs - Items to process\n * @param process - Function to process each input\n * @param options - Optional settings like concurrency\n * @returns All outputs (use `.flat()` if outputs are arrays)\n */\n async each<I, O>(\n step: string,\n inputs: Iterable<I>,\n process: (input: I) => Promise<O>,\n options?: { concurrency?: number },\n ): Promise<O[]> {\n const point = this.point<O>(step);\n const limit = pLimit(options?.concurrency ?? 1);\n\n const inputArray = Array.from(inputs);\n await Promise.all(\n inputArray.map((input) =>\n limit(() => point.through(input, () => process(input))),\n ),\n );\n\n await point.commit();\n return point.values();\n }\n\n /**\n * Get clean output from all completed points.\n * Single-entry points return the value directly, multi-entry return arrays.\n */\n getOutput(): Record<string, unknown> {\n const output: Record<string, unknown> = {};\n for (const [key, pointData] of Object.entries(this.points)) {\n if (pointData.entries.length === 1) {\n output[key] = pointData.entries[0].output;\n } else {\n output[key] = pointData.entries.map((e) => e.output);\n }\n }\n return output;\n }\n\n /** Get the file path where checkpoint is stored */\n getPath(): string {\n return this.path;\n }\n\n private async save(): Promise<void> {\n const file: CheckpointFile = {\n configHash: this.configHash,\n points: this.points,\n };\n const content = JSON.stringify(file, null, 2);\n\n // Atomic write: write to temp file, then rename\n const tempPath = `${this.path}.tmp`;\n writeFileSync(tempPath, content);\n renameSync(tempPath, this.path);\n }\n}\n\nfunction hash(value: unknown): string {\n return createHash('md5').update(JSON.stringify(value)).digest('hex');\n}\n\n/**\n * A checkpoint point for tracking iterative operations.\n * Uses input hashing to determine if an operation was already processed.\n */\nexport class Point<T> {\n #cache: Map<string, T>;\n\n constructor(\n private data: PointData,\n private persist: () => Promise<void>,\n ) {\n this.#cache = new Map(\n data.entries.map((e) => [e.inputHash, e.output as T]),\n );\n }\n\n /**\n * Execute computation if input wasn't processed before.\n * Returns cached output if input hash exists, otherwise executes, saves, and returns.\n */\n async through<I, O>(\n input: I,\n compute: () => Promise<O>,\n codec?: Codec<O>,\n ): Promise<O> {\n const inputHash = hash(input);\n\n if (this.#cache.has(inputHash)) {\n const cached = this.#cache.get(inputHash) as O;\n return codec ? codec.decode(cached) : cached;\n }\n\n const output = await compute();\n this.data.entries.push({ inputHash, output });\n this.#cache.set(inputHash, output as T);\n await this.persist();\n return codec ? codec.decode(output) : output;\n }\n\n /** Mark this point as complete. */\n async commit(): Promise<void> {\n this.data.committed = true;\n await this.persist();\n }\n\n /** Check if this point has been committed. */\n isCommitted(): boolean {\n return this.data.committed;\n }\n\n /** Get all outputs from this point. */\n values(): T[] {\n return this.data.entries.map((e) => e.output as T);\n }\n}\n\n/**\n * Generate a hash from a config object for checkpoint invalidation.\n * If config changes, the checkpoint will be invalidated and pipeline restarts.\n */\nexport function hashConfig(config: Record<string, unknown>): string {\n return createHash('md5').update(JSON.stringify(config)).digest('hex');\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport path from 'node:path';\n\nexport class FileCache {\n public path: string;\n constructor(watermark: string, extension = '.txt') {\n const hash = createHash('md5').update(watermark).digest('hex');\n this.path = path.join(tmpdir(), `text2sql-${hash}${extension}`);\n }\n\n async get() {\n if (existsSync(this.path)) {\n return readFile(this.path, 'utf-8');\n }\n return null;\n }\n\n set(content: string) {\n return writeFile(this.path, content, 'utf-8');\n }\n}\n\nexport class JsonCache<T> extends FileCache {\n constructor(watermark: string) {\n super(watermark, '.json');\n }\n\n async read(): Promise<T | null> {\n const content = await this.get();\n if (content) {\n return JSON.parse(content) as T;\n }\n return null;\n }\n\n write(data: T) {\n return this.set(JSON.stringify(data));\n }\n}\n", "import type { UIMessage } from 'ai';\n\nexport interface Message {\n id: string;\n chatId: string;\n role: string;\n createdAt: string | Date;\n content: UIMessage;\n}\n\nexport interface Chat {\n id: string;\n userId: string;\n title?: string | null;\n messages: Message[];\n}\n\nexport interface CreateChatParams {\n id: string;\n userId: string;\n title?: string;\n}\n\nexport interface UpdateChatParams {\n title?: string;\n}\n\nexport interface CreateMessageParams {\n id: string;\n chatId: string;\n role: string;\n content: UIMessage;\n createdAt?: Date;\n}\n\nexport abstract class History {\n abstract listChats(userId: string): Promise<Chat[]>;\n abstract getChat(chatId: string): Promise<Chat | null>;\n abstract createChat(chat: CreateChatParams): Promise<Chat>;\n abstract upsertChat(chat: CreateChatParams): Promise<Chat>;\n abstract deleteChat(chatId: string): Promise<void>;\n abstract updateChat(chatId: string, updates: UpdateChatParams): Promise<void>;\n abstract addMessage(message: CreateMessageParams): Promise<void>;\n abstract upsertMessage(message: CreateMessageParams): Promise<Message>;\n abstract deleteMessage(messageId: string): Promise<void>;\n}\n", "import { DatabaseSync } from 'node:sqlite';\n\nimport historyDDL from './history.sqlite.sql';\nimport {\n type Chat,\n type CreateChatParams,\n type CreateMessageParams,\n History,\n type Message,\n type UpdateChatParams,\n} from './history.ts';\n\nexport class SqliteHistory extends History {\n #db: DatabaseSync;\n\n constructor(path: string) {\n super();\n this.#db = new DatabaseSync(path);\n this.#db.exec(historyDDL);\n }\n\n async listChats(userId: string): Promise<Chat[]> {\n return this.#db\n .prepare(`SELECT * FROM chats WHERE \"userId\" = ?`)\n .all(userId) as unknown as Chat[];\n }\n\n async getChat(chatId: string): Promise<Chat | null> {\n const rows = this.#db\n .prepare(\n `SELECT\n c.id as chatId, c.\"userId\", c.title,\n m.id as messageId, m.role, m.\"createdAt\", m.content\n FROM chats c\n LEFT JOIN messages m ON m.\"chatId\" = c.id\n WHERE c.id = ?\n ORDER BY m.\"createdAt\" ASC`,\n )\n .all(chatId) as unknown as Array<{\n chatId: string;\n userId: string;\n title: string | null;\n messageId: string | null;\n role: string;\n createdAt: string;\n content: string;\n }>;\n\n if (!rows.length) return null;\n\n const firstRow = rows[0];\n const chat: Chat = {\n id: firstRow.chatId,\n userId: firstRow.userId,\n title: firstRow.title,\n messages: [],\n };\n\n for (const row of rows) {\n if (row.messageId) {\n chat.messages.push({\n id: row.messageId,\n chatId: firstRow.chatId,\n role: row.role as string,\n createdAt: row.createdAt as string,\n content: JSON.parse(row.content),\n });\n }\n }\n\n return chat;\n }\n\n async createChat(chat: CreateChatParams): Promise<Chat> {\n this.#db\n .prepare(`INSERT INTO chats (id, \"userId\", title) VALUES (?, ?, ?)`)\n .run(chat.id, chat.userId, chat.title || null);\n return chat as Chat;\n }\n\n async upsertChat(chat: CreateChatParams) {\n this.#db\n .prepare(\n `INSERT INTO chats (id, \"userId\", title) VALUES (?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET title = excluded.title, \"userId\" = excluded.\"userId\"`,\n )\n .run(chat.id, chat.userId, chat.title || null);\n return this.getChat(chat.id) as Promise<Chat>;\n }\n\n async deleteChat(chatId: string): Promise<void> {\n this.#db.prepare(`DELETE FROM chats WHERE id = ?`).run(chatId);\n }\n\n async updateChat(chatId: string, updates: UpdateChatParams): Promise<void> {\n if (updates.title !== undefined) {\n this.#db\n .prepare(`UPDATE chats SET title = ? WHERE id = ?`)\n .run(updates.title, chatId);\n }\n }\n\n async addMessage(message: CreateMessageParams): Promise<void> {\n const createdAt = message.createdAt\n ? message.createdAt.toISOString()\n : new Date().toISOString();\n this.#db\n .prepare(\n `INSERT INTO messages (id, \"chatId\", role, \"createdAt\", content) VALUES (?, ?, ?, ?, ?)`,\n )\n .run(\n message.id,\n message.chatId,\n message.role,\n createdAt,\n JSON.stringify(message.content),\n );\n }\n\n async upsertMessage(message: CreateMessageParams): Promise<Message> {\n const createdAt = message.createdAt\n ? message.createdAt.toISOString()\n : new Date().toISOString();\n this.#db\n .prepare(\n `INSERT INTO messages (id, \"chatId\", role, \"createdAt\", content) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET \"chatId\" = excluded.\"chatId\", role = excluded.role, \"createdAt\" = excluded.\"createdAt\", content = excluded.content`,\n )\n .run(\n message.id,\n message.chatId,\n message.role,\n createdAt,\n JSON.stringify(message.content),\n );\n return {\n ...message,\n createdAt,\n };\n }\n\n async deleteMessage(messageId: string): Promise<void> {\n this.#db.prepare(`DELETE FROM messages WHERE id = ?`).run(messageId);\n }\n}\n", "CREATE TABLE IF NOT EXISTS \"chats\" (\n\t\"id\" VARCHAR PRIMARY KEY,\n\t\"title\" VARCHAR,\n\t\"userId\" VARCHAR\n);\n\nCREATE TABLE IF NOT EXISTS \"messages\" (\n\t\"id\" VARCHAR PRIMARY KEY,\n\t\"chatId\" VARCHAR NOT NULL REFERENCES \"chats\" (\"id\") ON DELETE CASCADE,\n\t\"createdAt\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\"role\" VARCHAR NOT NULL,\n\t\"content\" TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS \"messages_chat_id_idx\" ON \"messages\" (\"chatId\");\n\nCREATE INDEX IF NOT EXISTS \"messages_chat_id_created_at_idx\" ON \"messages\" (\"chatId\", \"createdAt\");\n", "import { SqliteHistory } from './sqlite.history.ts';\n\nexport class InMemoryHistory extends SqliteHistory {\n constructor() {\n super(':memory:');\n }\n}\n", "import { DatabaseSync } from 'node:sqlite';\nimport { v7 } from 'uuid';\n\nimport {\n type GeneratedTeachable,\n type Teachables,\n toTeachables,\n} from '../teach/teachables.ts';\nimport storeDDL from './store.sqlite.sql';\nimport { type StoredTeachable, TeachablesStore } from './store.ts';\n\ninterface TeachableRow {\n id: string;\n userId: string;\n type: string;\n data: string;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction rowToStoredTeachable(row: TeachableRow): StoredTeachable {\n return {\n id: row.id,\n userId: row.userId,\n type: row.type as GeneratedTeachable['type'],\n data: JSON.parse(row.data),\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nexport class SqliteTeachablesStore extends TeachablesStore {\n #db: DatabaseSync;\n\n constructor(path: string) {\n super();\n this.#db = new DatabaseSync(path);\n this.#db.exec(storeDDL);\n }\n\n async remember(\n userId: string,\n data: GeneratedTeachable,\n ): Promise<StoredTeachable> {\n const id = v7();\n const now = new Date().toISOString();\n\n this.#db\n .prepare(\n 'INSERT INTO teachables (id, userId, type, data, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)',\n )\n .run(id, userId, data.type, JSON.stringify(data), now, now);\n\n return (await this.get(id))!;\n }\n\n async recall(\n userId: string,\n type?: GeneratedTeachable['type'],\n ): Promise<StoredTeachable[]> {\n let rows: TeachableRow[];\n\n if (type === undefined) {\n rows = this.#db\n .prepare('SELECT * FROM teachables WHERE userId = ? ORDER BY createdAt')\n .all(userId) as unknown as TeachableRow[];\n } else {\n rows = this.#db\n .prepare(\n 'SELECT * FROM teachables WHERE userId = ? AND type = ? ORDER BY createdAt',\n )\n .all(userId, type) as unknown as TeachableRow[];\n }\n\n return rows.map(rowToStoredTeachable);\n }\n\n async get(id: string): Promise<StoredTeachable | null> {\n const row = this.#db\n .prepare('SELECT * FROM teachables WHERE id = ?')\n .get(id) as TeachableRow | undefined;\n\n if (!row) return null;\n return rowToStoredTeachable(row);\n }\n\n async update(id: string, data: GeneratedTeachable): Promise<StoredTeachable> {\n const now = new Date().toISOString();\n\n this.#db\n .prepare(\n 'UPDATE teachables SET data = ?, type = ?, updatedAt = ? WHERE id = ?',\n )\n .run(JSON.stringify(data), data.type, now, id);\n\n return (await this.get(id))!;\n }\n\n async forget(id: string): Promise<void> {\n this.#db.prepare('DELETE FROM teachables WHERE id = ?').run(id);\n }\n\n async forgetAll(userId: string): Promise<void> {\n this.#db.prepare('DELETE FROM teachables WHERE userId = ?').run(userId);\n }\n\n async toTeachables(userId: string): Promise<Teachables[]> {\n const stored = await this.recall(userId);\n return toTeachables(stored.map((s) => s.data));\n }\n}\n", "CREATE TABLE IF NOT EXISTS \"teachables\" (\n\t\"id\" VARCHAR PRIMARY KEY,\n\t\"userId\" VARCHAR,\n\t\"type\" VARCHAR NOT NULL,\n\t\"data\" TEXT NOT NULL,\n\t\"createdAt\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\"updatedAt\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX IF NOT EXISTS \"teachables_user_id_idx\" ON \"teachables\" (\"userId\");\n\nCREATE INDEX IF NOT EXISTS \"teachables_type_idx\" ON \"teachables\" (\"type\");\n\nCREATE INDEX IF NOT EXISTS \"teachables_user_type_idx\" ON \"teachables\" (\"userId\", \"type\");\n", "import type { GeneratedTeachable, Teachables } from '../teach/teachables.ts';\n\nexport interface StoredTeachable {\n id: string;\n userId: string;\n type: GeneratedTeachable['type'];\n data: GeneratedTeachable;\n createdAt: string;\n updatedAt: string;\n}\n\nexport abstract class TeachablesStore {\n /**\n * Remember a teachable for a user.\n */\n abstract remember(\n userId: string,\n data: GeneratedTeachable,\n ): Promise<StoredTeachable>;\n\n /**\n * Recall teachables for a user, optionally filtered by type.\n */\n abstract recall(\n userId: string,\n type?: GeneratedTeachable['type'],\n ): Promise<StoredTeachable[]>;\n\n /**\n * Get a specific teachable by ID.\n */\n abstract get(id: string): Promise<StoredTeachable | null>;\n\n /**\n * Update an existing teachable.\n */\n abstract update(\n id: string,\n data: GeneratedTeachable,\n ): Promise<StoredTeachable>;\n\n /**\n * Forget (remove) a specific teachable by ID.\n */\n abstract forget(id: string): Promise<void>;\n\n /**\n * Forget all teachables for a user.\n */\n abstract forgetAll(userId: string): Promise<void>;\n\n /**\n * Convert stored teachables to Teachables array for use with toInstructions().\n */\n abstract toTeachables(userId: string): Promise<Teachables[]>;\n}\n", "import { SqliteTeachablesStore } from './sqlite.store.ts';\n\nexport class InMemoryTeachablesStore extends SqliteTeachablesStore {\n constructor() {\n super(':memory:');\n }\n}\n", "import {\n InvalidToolInputError,\n NoSuchToolError,\n ToolCallRepairError,\n type UIMessage,\n generateId,\n} from 'ai';\nimport { v7 } from 'uuid';\n\nimport {\n type Agent,\n type AgentModel,\n generate,\n stream,\n user,\n} from '@deepagents/agent';\n\nimport type { Adapter, IntrospectOptions } from './adapters/adapter.ts';\nimport { chat1Agent, chat1Tools } from './agents/chat1.agent.ts';\nimport { chat2Agent, chat2Tools } from './agents/chat2.agent.ts';\nimport { chat3Agent, chat3Tools } from './agents/chat3.agent.ts';\nimport { chat4Agent, chat4Tools } from './agents/chat4.agent.ts';\nimport { explainerAgent } from './agents/explainer.agent.ts';\nimport { toSql as agentToSql } from './agents/sql.agent.ts';\nimport {\n type RenderingTools,\n memoryTools,\n t_a_g,\n} from './agents/text2sql.agent.ts';\nimport { FileCache } from './file-cache.ts';\nimport { History } from './history/history.ts';\nimport type { TeachablesStore } from './memory/store.ts';\nimport {\n type ExtractedPair,\n type PairProducer,\n toPairs as collectPairs,\n} from './synthesis/types.ts';\nimport {\n type Teachables,\n guardrail,\n hint,\n persona,\n styleGuide,\n teachable,\n toInstructions,\n} from './teach/teachables.ts';\nimport { type TeachingsOptions, guidelines } from './teach/teachings.ts';\n\nexport interface InspectionResult {\n /** The grounding/introspection data (database schema context as XML) */\n grounding: string;\n\n /** The full instructions XML that would be sent to the agent */\n instructions: string;\n\n /** User-specific teachables that were loaded */\n userTeachables: Teachables[];\n\n /** System teachings configured */\n systemTeachings: Teachables[];\n\n /** Tool names available to the agent */\n tools: string[];\n}\n\nexport class Text2Sql {\n #config: {\n model?: AgentModel;\n adapter: Adapter;\n history: History;\n tools?: RenderingTools;\n instructions: Teachables[];\n memory?: TeachablesStore;\n introspection: FileCache;\n };\n\n constructor(config: {\n adapter: Adapter;\n history: History;\n version: string;\n tools?: RenderingTools;\n instructions?: Teachables[];\n model?: AgentModel;\n memory?: TeachablesStore;\n /**\n * Configure teachings behavior\n * @see TeachingsOptions\n */\n teachingsOptions?: TeachingsOptions;\n }) {\n this.#config = {\n adapter: config.adapter,\n history: config.history,\n instructions: [\n ...guidelines(config.teachingsOptions),\n ...(config.instructions ?? []),\n ],\n tools: config.tools ?? {},\n model: config.model,\n memory: config.memory,\n introspection: new FileCache('introspection-' + config.version),\n };\n }\n\n public async explain(sql: string) {\n const { experimental_output } = await generate(\n explainerAgent,\n [user('Explain this SQL.')],\n { sql },\n );\n return experimental_output.explanation;\n }\n\n public async toSql(input: string): Promise<string> {\n const introspection = await this.index();\n\n const result = await agentToSql({\n input,\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n model: this.#config.model,\n });\n\n return result.sql;\n }\n\n public instruct(...dataset: Teachables[]) {\n this.#config.instructions.push(...dataset);\n }\n\n public async inspect(agent: Agent) {\n const [grounding] = await Promise.all([this.index() as Promise<string>]);\n\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const allInstructions = [\n ...this.#config.instructions,\n guardrail({\n rule: 'ALWAYS use `get_sample_rows` before writing queries that filter or compare against string columns.',\n reason: 'Prevents SQL errors from wrong value formats.',\n action:\n \"Target specific columns (e.g., get_sample_rows('table', ['status', 'type'])).\",\n }),\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n\n const tools = Object.keys({\n ...agent.handoff.tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n });\n\n return {\n tools,\n prompt: agent.instructions({\n introspection: grounding,\n teachings: toInstructions('instructions', ...allInstructions),\n }),\n };\n }\n\n public async index(options?: IntrospectOptions) {\n const cached = await this.#config.introspection.get();\n if (cached) {\n return cached;\n }\n const introspection = await this.#config.adapter.introspect();\n await this.#config.introspection.set(introspection);\n return introspection;\n }\n\n /**\n * Generate training data pairs using a producer factory.\n * The factory receives the configured adapter, so users don't need to pass it manually.\n *\n * @example\n * // Generate questions for existing SQL\n * const pairs = await text2sql.toPairs(\n * (adapter) => new SqlExtractor(sqls, adapter, { validateSql: true })\n * );\n *\n * @example\n * // Extract from chat history with validation\n * const pairs = await text2sql.toPairs(\n * (adapter) => new ValidatedProducer(\n * new MessageExtractor(messages),\n * adapter\n * )\n * );\n */\n public async toPairs<T extends PairProducer>(\n factory: (adapter: Adapter) => T,\n ): Promise<ExtractedPair[]> {\n const producer = factory(this.#config.adapter);\n return collectPairs(producer);\n }\n\n // public async suggest() {\n // const [introspection, adapterInfo] = await Promise.all([\n // this.index(),\n // this.#config.adapter.introspect(),\n // ]);\n // const { experimental_output: output } = await generate(\n // suggestionsAgent,\n // [\n // user(\n // 'Suggest high-impact business questions and matching SQL queries for this database.',\n // ),\n // ],\n // {\n // },\n // );\n // return output.suggestions;\n // }\n\n public async chat(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n // Build instructions with conditional rendering hint\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const instructions = [\n ...this.#config.instructions,\n guardrail({\n rule: 'ALWAYS use `get_sample_rows` before writing queries that filter or compare against string columns.',\n reason: 'Prevents SQL errors from wrong value formats.',\n action:\n \"Target specific columns (e.g., get_sample_rows('table', ['status', 'type'])).\",\n }),\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n const originalMessage = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n const result = stream(\n t_a_g.clone({\n model: this.#config.model,\n tools: {\n ...t_a_g.handoff.tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n },\n }),\n originalMessage,\n {\n teachings: toInstructions(\n 'instructions',\n persona({\n name: 'Freya',\n role: 'You are an expert SQL query generator, answering business questions with accurate queries.',\n tone: 'Your tone should be concise and business-friendly.',\n }),\n ...instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n memory: this.#config.memory,\n userId: params.userId,\n },\n );\n\n return result.toUIMessageStream({\n onError: (error) => {\n if (NoSuchToolError.isInstance(error)) {\n return 'The model tried to call a unknown tool.';\n } else if (InvalidToolInputError.isInstance(error)) {\n return 'The model called a tool with invalid arguments.';\n } else if (ToolCallRepairError.isInstance(error)) {\n return 'The model tried to call a tool with invalid arguments, but it was repaired.';\n } else {\n return 'An unknown error occurred.';\n }\n },\n sendStart: true,\n sendFinish: true,\n sendReasoning: true,\n sendSources: true,\n originalMessages: originalMessage,\n generateMessageId: generateId,\n onFinish: async ({ responseMessage, isContinuation }) => {\n // Get user message from the input array (already known before the call)\n // Don't save if this is a continuation of an existing message\n const userMessage = messages.at(-1);\n if (!isContinuation && userMessage) {\n console.log(\n 'Saving user message to history:',\n JSON.stringify(userMessage),\n );\n await this.#config.history.addMessage({\n id: v7(),\n chatId: params.chatId,\n role: userMessage.role,\n content: userMessage,\n });\n }\n\n // Use responseMessage directly - guaranteed to have the assistant's reply\n await this.#config.history.addMessage({\n id: v7(),\n chatId: params.chatId,\n role: responseMessage.role,\n content: responseMessage,\n });\n },\n });\n }\n\n /**\n * Chat1 - Combined tool, no peek.\n *\n * Uses a single `query_database` tool that:\n * 1. Takes a natural language question\n * 2. Internally calls toSql() to generate validated SQL\n * 3. Executes the SQL\n * 4. Returns both SQL and results\n *\n * The agent does NOT see the SQL before execution.\n */\n public async chat1(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const instructions = [\n ...this.#config.instructions,\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n\n const originalMessage = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n\n const result = stream(\n chat1Agent.clone({\n model: this.#config.model,\n tools: {\n ...chat1Tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n },\n }),\n originalMessage,\n {\n teachings: toInstructions(\n 'instructions',\n persona({\n name: 'Freya',\n role: 'You are an expert SQL query generator, answering business questions with accurate queries.',\n tone: 'Your tone should be concise and business-friendly.',\n }),\n ...instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n memory: this.#config.memory,\n userId: params.userId,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessage,\n );\n }\n\n /**\n * Chat2 - Separate generate + execute tools (with peek).\n *\n * Uses two separate tools:\n * 1. `generate_sql` - Takes a question, returns validated SQL\n * 2. `execute_sql` - Takes SQL, executes it\n *\n * The agent sees the SQL before execution and can review/refine.\n */\n public async chat2(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const instructions = [\n ...this.#config.instructions,\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n\n const originalMessage = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n\n const result = stream(\n chat2Agent.clone({\n model: this.#config.model,\n tools: {\n ...chat2Tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n },\n }),\n originalMessage,\n {\n teachings: toInstructions(\n 'instructions',\n persona({\n name: 'Freya',\n role: 'You are an expert SQL query generator, answering business questions with accurate queries.',\n tone: 'Your tone should be concise and business-friendly.',\n }),\n ...instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n memory: this.#config.memory,\n userId: params.userId,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessage,\n );\n }\n\n /**\n * Chat3 - Agent conversation/collaboration.\n *\n * Enables richer interaction where the SQL agent can:\n * - Surface confidence levels\n * - State assumptions\n * - Request clarification when uncertain\n */\n public async chat3(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const instructions = [\n ...this.#config.instructions,\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n\n const originalMessage = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n\n const result = stream(\n chat3Agent.clone({\n model: this.#config.model,\n tools: {\n ...chat3Tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n },\n }),\n originalMessage,\n {\n teachings: toInstructions(\n 'instructions',\n persona({\n name: 'Freya',\n role: 'You are an expert SQL query generator, answering business questions with accurate queries.',\n tone: 'Your tone should be concise and business-friendly.',\n }),\n ...instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n memory: this.#config.memory,\n userId: params.userId,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessage,\n );\n }\n\n /**\n * Chat4 - Question decomposition approach.\n *\n * Breaks down questions into semantic components before SQL generation:\n * - entities: Key concepts mentioned\n * - filters: Filtering criteria\n * - aggregation: Type of aggregation\n * - breakdown: Semantic parts of the question\n *\n * This helps ensure all aspects of the question are addressed.\n */\n public async chat4(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const instructions = [\n ...this.#config.instructions,\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n\n const originalMessage = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n\n const result = stream(\n chat4Agent.clone({\n model: this.#config.model,\n tools: {\n ...chat4Tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n },\n }),\n originalMessage,\n {\n teachings: toInstructions(\n 'instructions',\n persona({\n name: 'Freya',\n role: 'You are an expert SQL query generator, answering business questions with accurate queries.',\n tone: 'Your tone should be concise and business-friendly.',\n }),\n ...instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n memory: this.#config.memory,\n userId: params.userId,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessage,\n );\n }\n\n /**\n * Helper to create UI message stream with common error handling and persistence.\n */\n #createUIMessageStream(\n result: ReturnType<typeof stream>,\n messages: UIMessage[],\n params: { chatId: string; userId: string },\n originalMessage: UIMessage[],\n ) {\n return result.toUIMessageStream({\n onError: (error) => {\n if (NoSuchToolError.isInstance(error)) {\n return 'The model tried to call an unknown tool.';\n } else if (InvalidToolInputError.isInstance(error)) {\n return 'The model called a tool with invalid arguments.';\n } else if (ToolCallRepairError.isInstance(error)) {\n return 'The model tried to call a tool with invalid arguments, but it was repaired.';\n } else {\n return 'An unknown error occurred.';\n }\n },\n sendStart: true,\n sendFinish: true,\n sendReasoning: true,\n sendSources: true,\n originalMessages: originalMessage,\n generateMessageId: generateId,\n onFinish: async ({ responseMessage, isContinuation }) => {\n const userMessage = messages.at(-1);\n if (!isContinuation && userMessage) {\n console.log(\n 'Saving user message to history:',\n JSON.stringify(userMessage),\n );\n await this.#config.history.addMessage({\n id: v7(),\n chatId: params.chatId,\n role: userMessage.role,\n content: userMessage,\n });\n }\n\n await this.#config.history.addMessage({\n id: v7(),\n chatId: params.chatId,\n role: responseMessage.role,\n content: responseMessage,\n });\n },\n });\n }\n}\n", "/**\n * Chat1 Agent - Combined Tool, No Peek\n *\n * This variant uses a single `query_database` tool that:\n * 1. Takes a natural language question\n * 2. Internally calls toSql() to generate validated SQL\n * 3. Executes the SQL\n * 4. Returns both the SQL and results\n *\n * The agent does NOT see the SQL before execution - it's generated and executed in one step.\n */\nimport { groq } from '@ai-sdk/groq';\nimport { tool } from 'ai';\nimport z from 'zod';\n\nimport { agent, toState } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport type { TeachablesStore } from '../memory/store.ts';\nimport type { Teachables } from '../teach/teachables.ts';\nimport { type ToSqlOptions, toSql } from './sql.agent.ts';\n\nexport type Chat1State = {\n /** Database adapter for query execution */\n adapter: Adapter;\n /** Schema introspection XML */\n introspection: string;\n /** Teachings/instructions for SQL generation */\n instructions: Teachables[];\n /** Combined teachings string for the agent prompt */\n teachings: string;\n /** Optional memory store for user teachables */\n memory?: TeachablesStore;\n /** User ID for memory operations */\n userId?: string;\n};\n\n/**\n * Result returned by the query_database tool\n */\nexport interface QueryDatabaseResult {\n success: boolean;\n /** The generated SQL query */\n sql?: string;\n /** Query results as array of rows */\n data?: unknown[];\n /** Error message if generation or execution failed */\n error?: string;\n /** Number of attempts made during SQL generation */\n attempts?: number;\n}\n\nconst tools = {\n query_database: tool({\n description: `Query the database to answer a question. Provide your question in natural language and this tool will:\n1. Generate the appropriate SQL query\n2. Validate the SQL syntax\n3. Execute the query\n4. Return the results\n\nUse this tool when you need to retrieve data to answer the user's question.`,\n inputSchema: z.object({\n question: z\n .string()\n .min(1)\n .describe(\n 'The question to answer, expressed in natural language. Be specific about what data you need.',\n ),\n reasoning: z\n .string()\n .optional()\n .describe(\n 'Your reasoning for why this query is needed to answer the user.',\n ),\n }),\n execute: async ({ question }, options): Promise<QueryDatabaseResult> => {\n const state = toState<Chat1State>(options);\n\n try {\n // Generate SQL using the dedicated toSql function with validation and retry\n const sqlResult = await toSql({\n input: question,\n adapter: state.adapter,\n introspection: state.introspection,\n instructions: state.instructions,\n });\n\n // If SQL generation failed after all retries\n if (!sqlResult.sql) {\n return {\n success: false,\n error: sqlResult.errors?.join('; ') || 'Failed to generate SQL',\n attempts: sqlResult.attempts,\n };\n }\n\n // Execute the validated SQL\n const data = await state.adapter.execute(sqlResult.sql);\n\n return {\n success: true,\n sql: sqlResult.sql,\n data,\n attempts: sqlResult.attempts,\n };\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n },\n }),\n\n scratchpad: scratchpad_tool,\n};\n\n/**\n * Chat1 Agent - Table Augmented Generation with combined query tool.\n *\n * This agent receives user questions and uses the query_database tool\n * to fetch data. The SQL generation is delegated to the specialized\n * sqlQueryAgent via the toSql() function.\n */\nexport const chat1Agent = agent<never, Chat1State>({\n name: 'chat1-combined',\n model: groq('openai/gpt-oss-20b'),\n tools,\n prompt: (state) => {\n return `\n${state?.teachings || ''}\n${state?.introspection || ''}\n`;\n },\n});\n\nexport { tools as chat1Tools };\n", "import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { type AgentModel, agent, generate, user } from '@deepagents/agent';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport {\n type Teachables,\n persona,\n toInstructions,\n} from '../teach/teachables.ts';\n\ntype SqlGeneratorState = {\n // FIXME: this should not be here after creating the context package\n introspection: string;\n teachings: string;\n};\n\ntype SqlGeneratorOutput =\n | { sql: string; reasoning?: string }\n | { error: string };\n\n/**\n * Agent that generates SQL queries from introspection and natural language questions.\n * Used for creating synthetic training data for text-to-SQL models.\n */\n/** Temperature progression for retries: deterministic first, then increasingly exploratory */\nconst RETRY_TEMPERATURES = [0, 0.2, 0.3];\n\nconst sqlQueryAgent = agent<SqlGeneratorOutput, SqlGeneratorState>({\n name: 'text2sql',\n model: groq('openai/gpt-oss-20b'),\n logging: process.env.AGENT_LOGGING === 'true',\n output: z.union([\n z.object({\n sql: z.string().describe('The SQL query that answers the question'),\n reasoning: z\n .string()\n .optional()\n .describe('The reasoning steps taken to generate the SQL'),\n }),\n z.object({\n error: z\n .string()\n .describe(\n 'Error message explaining why the question cannot be answered with the given schema',\n ),\n }),\n ]),\n prompt: (state) => {\n return `\n ${state?.teachings || ''}\n ${state?.introspection || ''}\n `;\n },\n});\n\n/** Extract SQL from markdown fenced code block if present */\nfunction extractSql(output: string): string {\n const match = output.match(/```sql\\n?([\\s\\S]*?)```/);\n return match ? match[1].trim() : output.trim();\n}\n\nexport type GenerateSqlResult =\n | { success: true; sql: string }\n | { success: false; error: string; isUnanswerable?: boolean };\n\nexport type GenerateSqlParams = {\n input: string;\n model: AgentModel;\n temperature: number;\n introspection: string;\n instructions: Teachables[];\n previousError?: string;\n};\n\ntype StepResult =\n | { ok: true; sql: string }\n | { ok: false; error: string; isUnanswerable?: boolean };\n\n/**\n * Generate SQL from natural language using the SQL agent.\n * Handles JSON validation errors from the API by returning an error result.\n */\nasync function generateSql(\n params: GenerateSqlParams,\n): Promise<GenerateSqlResult> {\n const {\n input,\n model,\n temperature,\n introspection,\n instructions,\n previousError,\n } = params;\n\n const agentInstance = sqlQueryAgent.clone({\n model: wrapLanguageModel({\n model,\n middleware: defaultSettingsMiddleware({\n settings: { temperature, topP: 1 },\n }),\n }),\n });\n\n const messages = previousError\n ? [\n user(input),\n user(\n `<validation_error>Your previous SQL query had the following error: ${previousError}. Please fix the query.</validation_error>`,\n ),\n ]\n : [user(input)];\n\n try {\n const { experimental_output: output } = await generate(\n agentInstance,\n messages,\n {\n teachings: toInstructions(\n 'instructions',\n persona({\n name: 'Freya',\n role: 'You are an expert SQL query generator. You translate natural language questions into precise, efficient SQL queries based on the provided database schema.',\n }),\n ...instructions,\n ),\n introspection,\n },\n );\n\n // Handle error responses (question is unanswerable with given schema)\n if ('error' in output) {\n return { success: false, error: output.error, isUnanswerable: true };\n }\n\n return { success: true, sql: extractSql(output.sql) };\n } catch (error) {\n if (\n error instanceof Error &&\n (error.message.includes('Failed to validate JSON') ||\n error.message.includes('response did not match schema'))\n ) {\n return {\n success: false,\n error: `Schema validation failed: ${error.message}`,\n };\n }\n throw error;\n }\n}\n\n/**\n * Exported object for mockability in tests.\n * Use `mock.method(sqlGenerators, 'generateSql', ...)` to mock.\n */\nexport const sqlGenerators = {\n generateSql,\n};\n\n/**\n * Generate SQL and validate it in a single step.\n * Returns a unified result for both generation and validation errors.\n */\nasync function generateAndValidate(\n options: ToSqlOptions,\n temperature: number,\n previousError?: string,\n): Promise<StepResult> {\n const result = await sqlGenerators.generateSql({\n input: options.input,\n model: options.model ?? sqlQueryAgent.model,\n temperature,\n introspection: options.introspection,\n instructions: options.instructions,\n previousError,\n });\n\n if (!result.success) {\n return {\n ok: false,\n error: result.error,\n isUnanswerable: result.isUnanswerable,\n };\n }\n\n const validationError = await options.adapter.validate(result.sql);\n if (validationError) {\n return { ok: false, error: validationError };\n }\n\n return { ok: true, sql: result.sql };\n}\n\nexport interface ToSqlOptions {\n /** The natural language input to convert to SQL */\n input: string;\n /** Database adapter for validation */\n adapter: Adapter;\n /** Introspection/schema context */\n introspection: string;\n /** Instructions/teachings to include */\n instructions: Teachables[];\n /** Optional model override */\n model?: AgentModel;\n /** Maximum retry attempts on validation failure (default: 3) */\n maxRetries?: number;\n}\n\nexport interface ToSqlResult {\n /** The generated SQL query */\n sql: string;\n /** Number of attempts made */\n attempts: number;\n /** Validation errors encountered (if any retries occurred) */\n errors?: string[];\n}\n\n/**\n * Generate SQL from natural language with post-generation validation.\n * Retries generation if validation fails, including the error in the retry prompt.\n * Also retries on API-level JSON validation errors from the model.\n * Does NOT retry when the question is unanswerable (intentional error response).\n */\nexport async function toSql(options: ToSqlOptions): Promise<ToSqlResult> {\n const { maxRetries = 3 } = options;\n const errors: string[] = [];\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n const temperature = RETRY_TEMPERATURES[attempt - 1] ?? 0.3;\n const result = await generateAndValidate(\n options,\n temperature,\n errors.at(-1),\n );\n\n if (result.ok) {\n return {\n sql: result.sql,\n attempts: attempt,\n errors: errors.length ? errors : undefined,\n };\n }\n\n // Don't retry if the question is unanswerable - it's an intentional error\n if (result.isUnanswerable) {\n return { sql: '', attempts: attempt, errors: [result.error] };\n }\n\n errors.push(result.error);\n }\n\n return { sql: '', attempts: maxRetries, errors };\n}\n", "/**\n * Chat2 Agent - Separate Generate + Execute Tools (With Peek)\n *\n * This variant uses two separate tools:\n * 1. `generate_sql` - Takes a question, returns validated SQL (agent can inspect it)\n * 2. `execute_sql` - Takes SQL, executes it, returns results\n *\n * The agent sees the SQL before execution and can:\n * - Review the generated SQL\n * - Explain the approach to the user\n * - Decide to refine the question and regenerate\n * - Choose not to execute if something looks wrong\n */\nimport { groq } from '@ai-sdk/groq';\nimport { tool } from 'ai';\nimport z from 'zod';\n\nimport { agent, toState } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport type { TeachablesStore } from '../memory/store.ts';\nimport type { Teachables } from '../teach/teachables.ts';\nimport { toSql } from './sql.agent.ts';\n\nexport type Chat2State = {\n /** Database adapter for query execution */\n adapter: Adapter;\n /** Schema introspection XML */\n introspection: string;\n /** Teachings/instructions for SQL generation */\n instructions: Teachables[];\n /** Combined teachings string for the agent prompt */\n teachings: string;\n /** Optional memory store for user teachables */\n memory?: TeachablesStore;\n /** User ID for memory operations */\n userId?: string;\n};\n\n/**\n * Result returned by the generate_sql tool\n */\nexport interface GenerateSqlToolResult {\n success: boolean;\n /** The generated and validated SQL query */\n sql?: string;\n /** Error message if generation failed */\n error?: string;\n /** Number of attempts made during SQL generation */\n attempts?: number;\n /** Validation errors encountered during generation */\n validationErrors?: string[];\n}\n\n/**\n * Result returned by the execute_sql tool\n */\nexport interface ExecuteSqlToolResult {\n success: boolean;\n /** Query results as array of rows */\n data?: unknown[];\n /** Error message if execution failed */\n error?: string;\n /** Row count of results */\n rowCount?: number;\n}\n\nconst tools = {\n generate_sql: tool({\n description: `Generate a SQL query from a natural language question. This tool will:\n1. Translate your question into SQL\n2. Validate the SQL syntax\n3. Retry with corrections if validation fails\n4. Return the validated SQL for your review\n\nUse this BEFORE execute_sql to see what query will be run. You can then:\n- Explain the approach to the user\n- Decide if the SQL looks correct\n- Refine your question and regenerate if needed`,\n inputSchema: z.object({\n question: z\n .string()\n .min(1)\n .describe(\n 'The question to translate into SQL. Be specific about what data you need.',\n ),\n reasoning: z\n .string()\n .optional()\n .describe('Your reasoning for why this data is needed.'),\n }),\n execute: async ({ question }, options): Promise<GenerateSqlToolResult> => {\n const state = toState<Chat2State>(options);\n\n try {\n const sqlResult = await toSql({\n input: question,\n adapter: state.adapter,\n introspection: state.introspection,\n instructions: state.instructions,\n });\n\n if (!sqlResult.sql) {\n return {\n success: false,\n error: sqlResult.errors?.join('; ') || 'Failed to generate SQL',\n attempts: sqlResult.attempts,\n validationErrors: sqlResult.errors,\n };\n }\n\n return {\n success: true,\n sql: sqlResult.sql,\n attempts: sqlResult.attempts,\n validationErrors: sqlResult.errors,\n };\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n },\n }),\n\n execute_sql: tool({\n description: `Execute a SQL query and return the results. Use this AFTER generate_sql to run the query.\n\nOnly SELECT and WITH (CTE) queries are allowed - no data modification.`,\n inputSchema: z.object({\n sql: z\n .string()\n .min(1)\n .refine(\n (sql) =>\n sql.trim().toUpperCase().startsWith('SELECT') ||\n sql.trim().toUpperCase().startsWith('WITH'),\n {\n message: 'Only read-only SELECT or WITH queries are allowed.',\n },\n )\n .describe('The SQL query to execute (must be SELECT or WITH).'),\n reasoning: z\n .string()\n .optional()\n .describe('Brief explanation of what this query retrieves.'),\n }),\n execute: async ({ sql }, options): Promise<ExecuteSqlToolResult> => {\n const state = toState<Chat2State>(options);\n\n try {\n const data = await state.adapter.execute(sql);\n\n return {\n success: true,\n data,\n rowCount: Array.isArray(data) ? data.length : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof Error ? error.message : 'Query execution failed',\n };\n }\n },\n }),\n\n scratchpad: scratchpad_tool,\n};\n\n/**\n * Chat2 Agent - Table Augmented Generation with peek support.\n *\n * This agent uses separate generate_sql and execute_sql tools,\n * allowing it to review the SQL before execution. This enables:\n * - Transparency: Agent knows what SQL will be run\n * - Control: Agent can refine before executing\n * - Explanation: Agent can describe its approach to the user\n */\nexport const chat2Agent = agent<never, Chat2State>({\n name: 'chat2-with-peek',\n model: groq('openai/gpt-oss-20b'),\n tools,\n prompt: (state) => {\n return `\n${state?.teachings || ''}\n${state?.introspection || ''}\n\nWhen answering questions that require database queries:\n1. First use generate_sql to create the SQL query\n2. Review the generated SQL to ensure it matches the user's intent\n3. Use execute_sql to run the query\n4. Present the results to the user\n\nIf the generated SQL doesn't look right, you can refine your question and regenerate.\n`;\n },\n});\n\nexport { tools as chat2Tools };\n", "/**\n * Chat3 Agent - Agent Conversation/Collaboration\n *\n * This variant enables richer interaction between the conversation agent\n * and the SQL generation agent. The SQL agent can:\n * 1. Surface its confidence level\n * 2. State assumptions it's making\n * 3. Request clarification when uncertain\n *\n * The conversation agent can then:\n * - Answer clarifications from its context\n * - Ask the user for clarification\n * - Accept or refine the SQL agent's approach\n */\nimport { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, tool, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { agent, generate, toState, user } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport type { TeachablesStore } from '../memory/store.ts';\nimport {\n type Teachables,\n persona,\n toInstructions,\n} from '../teach/teachables.ts';\n\nexport type Chat3State = {\n /** Database adapter for query execution */\n adapter: Adapter;\n /** Schema introspection XML */\n introspection: string;\n /** Teachings/instructions for SQL generation */\n instructions: Teachables[];\n /** Combined teachings string for the agent prompt */\n teachings: string;\n /** Optional memory store for user teachables */\n memory?: TeachablesStore;\n /** User ID for memory operations */\n userId?: string;\n};\n\n/**\n * Output schema for the collaborative SQL agent\n */\nconst collaborativeSqlOutputSchema = z.discriminatedUnion('status', [\n z.object({\n status: z.literal('success'),\n sql: z.string().describe('The generated SQL query'),\n confidence: z\n .enum(['high', 'medium', 'low'])\n .describe('Confidence level in this SQL being correct'),\n assumptions: z\n .array(z.string())\n .optional()\n .describe('Assumptions made during SQL generation'),\n reasoning: z\n .string()\n .optional()\n .describe('Brief explanation of the query approach'),\n }),\n z.object({\n status: z.literal('clarification_needed'),\n question: z.string().describe('Question to clarify the request'),\n context: z.string().optional().describe('Why this clarification is needed'),\n options: z\n .array(z.string())\n .optional()\n .describe('Possible options if applicable'),\n }),\n z.object({\n status: z.literal('unanswerable'),\n reason: z.string().describe('Why this question cannot be answered'),\n suggestions: z\n .array(z.string())\n .optional()\n .describe('Alternative questions that could be answered'),\n }),\n]);\n\ntype CollaborativeSqlOutput = z.infer<typeof collaborativeSqlOutputSchema>;\n\n/**\n * Internal agent for collaborative SQL generation.\n * This agent can ask for clarification instead of guessing.\n */\nconst collaborativeSqlAgent = agent<CollaborativeSqlOutput, Chat3State>({\n name: 'collaborative-sql',\n model: groq('openai/gpt-oss-20b'),\n output: collaborativeSqlOutputSchema,\n prompt: (state) => {\n return `\n${toInstructions(\n 'instructions',\n persona({\n name: 'SQLCollab',\n role: 'You are an expert SQL query generator that collaborates with the user to ensure accuracy.',\n }),\n ...(state?.instructions || []),\n)}\n${state?.introspection || ''}\n\nIMPORTANT: You have three response options:\n\n1. SUCCESS - When you can confidently generate SQL:\n - Provide the SQL query\n - Rate your confidence (high/medium/low)\n - List any assumptions you made\n\n2. CLARIFICATION_NEEDED - When the question is ambiguous:\n - Ask a specific clarifying question\n - Explain why clarification is needed\n - Provide options if applicable\n\n3. UNANSWERABLE - When the question cannot be answered with available data:\n - Explain why\n - Suggest alternative questions that could be answered\n\nPrefer asking for clarification over making low-confidence guesses.\n`;\n },\n});\n\n/**\n * Result from the collaborative query tool\n */\nexport interface CollaborativeQueryResult {\n /** Whether a final SQL was produced */\n success: boolean;\n /** The generated SQL (if success) */\n sql?: string;\n /** Query results (if executed) */\n data?: unknown[];\n /** Confidence level of the SQL */\n confidence?: 'high' | 'medium' | 'low';\n /** Assumptions made during generation */\n assumptions?: string[];\n /** Clarification question (if needed) */\n clarificationNeeded?: string;\n /** Context for clarification */\n clarificationContext?: string;\n /** Options for clarification */\n clarificationOptions?: string[];\n /** Reason if unanswerable */\n unanswerableReason?: string;\n /** Suggested alternatives if unanswerable */\n suggestions?: string[];\n /** Error message if something failed */\n error?: string;\n}\n\nconst tools = {\n consult_sql_agent: tool({\n description: `Consult the SQL specialist agent to generate a query. The SQL agent may:\n- Return a SQL query with confidence level and assumptions\n- Ask for clarification if the question is ambiguous\n- Indicate if the question cannot be answered with available data\n\nBased on the response:\n- If clarification is needed, you can provide context or ask the user\n- If assumptions were made, verify them with the user for important queries\n- If unanswerable, relay the suggestions to the user`,\n inputSchema: z.object({\n question: z\n .string()\n .min(1)\n .describe('The question to translate into SQL.'),\n context: z\n .string()\n .optional()\n .describe('Additional context from the conversation that might help.'),\n previousClarification: z\n .string()\n .optional()\n .describe(\n 'Answer to a previous clarification question from the SQL agent.',\n ),\n }),\n execute: async (\n { question, context, previousClarification },\n options,\n ): Promise<CollaborativeQueryResult> => {\n const state = toState<Chat3State>(options);\n\n try {\n // Build the message for the SQL agent\n let fullQuestion = question;\n if (context) {\n fullQuestion = `${question}\\n\\nAdditional context: ${context}`;\n }\n if (previousClarification) {\n fullQuestion = `${fullQuestion}\\n\\nClarification provided: ${previousClarification}`;\n }\n\n const agentInstance = collaborativeSqlAgent.clone({\n model: wrapLanguageModel({\n model: collaborativeSqlAgent.model,\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.1 },\n }),\n }),\n });\n\n const { experimental_output: output } = await generate(\n agentInstance,\n [user(fullQuestion)],\n state,\n );\n\n // Handle the three response types\n if (output.status === 'success') {\n // Validate the SQL\n const validationError = await state.adapter.validate(output.sql);\n if (validationError) {\n return {\n success: false,\n error: `SQL validation failed: ${validationError}`,\n };\n }\n\n // Execute the SQL\n const data = await state.adapter.execute(output.sql);\n\n return {\n success: true,\n sql: output.sql,\n data,\n confidence: output.confidence,\n assumptions: output.assumptions,\n };\n }\n\n if (output.status === 'clarification_needed') {\n return {\n success: false,\n clarificationNeeded: output.question,\n clarificationContext: output.context,\n clarificationOptions: output.options,\n };\n }\n\n if (output.status === 'unanswerable') {\n return {\n success: false,\n unanswerableReason: output.reason,\n suggestions: output.suggestions,\n };\n }\n\n return {\n success: false,\n error: 'Unexpected response from SQL agent',\n };\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n },\n }),\n\n execute_sql: tool({\n description: `Execute a SQL query directly. Use this when you have SQL that you want to run\n(e.g., after receiving SQL from consult_sql_agent or for follow-up queries).`,\n inputSchema: z.object({\n sql: z\n .string()\n .min(1)\n .refine(\n (sql) =>\n sql.trim().toUpperCase().startsWith('SELECT') ||\n sql.trim().toUpperCase().startsWith('WITH'),\n {\n message: 'Only read-only SELECT or WITH queries are allowed.',\n },\n )\n .describe('The SQL query to execute.'),\n }),\n execute: async ({ sql }, options) => {\n const state = toState<Chat3State>(options);\n\n try {\n // Validate first\n const validationError = await state.adapter.validate(sql);\n if (validationError) {\n return {\n success: false,\n error: `Validation failed: ${validationError}`,\n };\n }\n\n const data = await state.adapter.execute(sql);\n return {\n success: true,\n data,\n rowCount: Array.isArray(data) ? data.length : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Execution failed',\n };\n }\n },\n }),\n\n scratchpad: scratchpad_tool,\n};\n\n/**\n * Chat3 Agent - Table Augmented Generation with agent collaboration.\n *\n * This agent collaborates with a specialized SQL agent that can:\n * - Express confidence levels\n * - Surface assumptions\n * - Request clarification\n *\n * This enables higher quality SQL generation through dialogue.\n */\nexport const chat3Agent = agent<never, Chat3State>({\n name: 'chat3-collaborative',\n model: groq('openai/gpt-oss-20b'),\n tools,\n prompt: (state) => {\n return `\n${state?.teachings || ''}\n${state?.introspection || ''}\n\nWhen answering questions that require database queries, use the consult_sql_agent tool.\n\nThe SQL agent may respond in three ways:\n1. SUCCESS with SQL, confidence, and assumptions - review the confidence and assumptions\n2. CLARIFICATION_NEEDED with a question - either answer from context or ask the user\n3. UNANSWERABLE with reason and suggestions - relay this to the user helpfully\n\nFor medium/low confidence results, consider mentioning the assumptions to the user.\nFor clarification requests, try to answer from conversation context first before asking the user.\n`;\n },\n});\n\nexport { tools as chat3Tools };\n", "/**\n * Chat4 Agent - Question Decomposition Approach\n *\n * This variant breaks down the user's question into semantic components\n * before passing it to the SQL agent. Instead of:\n * \"Which customers bought the most expensive products last quarter?\"\n *\n * It passes a decomposition:\n * - entities: customers, products, purchases\n * - filters: expensive products, last quarter\n * - aggregation: most (count? value?)\n * - output: list of customers\n *\n * This helps the SQL agent understand the different aspects of the question\n * without being told HOW to implement it.\n */\nimport { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, tool, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { agent, generate, toState, user } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport type { TeachablesStore } from '../memory/store.ts';\nimport {\n type Teachables,\n persona,\n toInstructions,\n} from '../teach/teachables.ts';\n\nexport type Chat4State = {\n /** Database adapter for query execution */\n adapter: Adapter;\n /** Schema introspection XML */\n introspection: string;\n /** Teachings/instructions for SQL generation */\n instructions: Teachables[];\n /** Combined teachings string for the agent prompt */\n teachings: string;\n /** Optional memory store for user teachables */\n memory?: TeachablesStore;\n /** User ID for memory operations */\n userId?: string;\n};\n\n/**\n * Schema for question decomposition\n */\nconst questionDecompositionSchema = z.object({\n originalQuestion: z\n .string()\n .describe('The original question being decomposed'),\n breakdown: z\n .array(z.string())\n .min(1)\n .describe(\n 'Semantic breakdown of the question into its component parts. Each part describes an aspect of what is being asked, NOT how to implement it.',\n ),\n entities: z\n .array(z.string())\n .optional()\n .describe(\n 'Key entities/concepts mentioned (e.g., customers, orders, products)',\n ),\n filters: z\n .array(z.string())\n .optional()\n .describe(\n 'Filtering criteria mentioned (e.g., \"last quarter\", \"above $100\")',\n ),\n aggregation: z\n .string()\n .optional()\n .describe(\n 'Type of aggregation if any (e.g., \"count\", \"sum\", \"average\", \"top N\")',\n ),\n ambiguities: z\n .array(z.string())\n .optional()\n .describe('Any ambiguous parts that might need clarification'),\n});\n\ntype QuestionDecomposition = z.infer<typeof questionDecompositionSchema>;\n\n/**\n * Output schema for the decomposition-aware SQL agent\n */\nconst decompositionSqlOutputSchema = z.union([\n z.object({\n sql: z\n .string()\n .describe('The SQL query that answers the decomposed question'),\n reasoning: z\n .string()\n .optional()\n .describe('How each breakdown component was addressed'),\n }),\n z.object({\n error: z\n .string()\n .describe('Error message if the question cannot be answered'),\n }),\n]);\n\ntype DecompositionSqlOutput = z.infer<typeof decompositionSqlOutputSchema>;\n\n/**\n * Internal agent for SQL generation from decomposed questions\n */\nconst decompositionSqlAgent = agent<DecompositionSqlOutput, Chat4State>({\n name: 'decomposition-sql',\n model: groq('openai/gpt-oss-20b'),\n output: decompositionSqlOutputSchema,\n prompt: (state) => {\n return `\n${toInstructions(\n 'instructions',\n persona({\n name: 'SQLDecomp',\n role: 'You are an expert SQL query generator. You receive questions broken down into semantic components and generate precise SQL.',\n }),\n ...(state?.instructions || []),\n)}\n${state?.introspection || ''}\n\nYou will receive questions in a decomposed format with:\n- breakdown: Semantic parts of the question\n- entities: Key concepts mentioned\n- filters: Filtering criteria\n- aggregation: Type of aggregation needed\n- ambiguities: Potentially unclear parts\n\nAddress each component of the breakdown in your SQL.\nIf there are ambiguities, make reasonable assumptions and note them in your reasoning.\n`;\n },\n});\n\n/**\n * Result from the decomposed query tool\n */\nexport interface DecomposedQueryResult {\n success: boolean;\n /** The original question */\n question?: string;\n /** How the question was decomposed */\n decomposition?: QuestionDecomposition;\n /** The generated SQL */\n sql?: string;\n /** Query results */\n data?: unknown[];\n /** How breakdown components were addressed */\n reasoning?: string;\n /** Error message if failed */\n error?: string;\n /** Number of generation attempts */\n attempts?: number;\n}\n\n/** Temperature progression for retries */\nconst RETRY_TEMPERATURES = [0, 0.2, 0.3];\n\nconst tools = {\n query_with_decomposition: tool({\n description: `Query the database using question decomposition. This tool:\n1. Breaks down your question into semantic components (entities, filters, aggregations)\n2. Passes the decomposition to the SQL specialist\n3. Generates and validates SQL\n4. Executes and returns results\n\nThis approach helps ensure all aspects of the question are addressed in the query.`,\n inputSchema: z.object({\n question: z.string().min(1).describe('The question to answer.'),\n breakdown: z\n .array(z.string())\n .min(1)\n .describe(\n 'Break down the question into its semantic parts. Each part should describe an ASPECT of what is being asked, not instructions. Example for \"top customers by revenue last month\": [\"customers who made purchases\", \"revenue from those purchases\", \"time period: last month\", \"ranking: top by total revenue\"]',\n ),\n entities: z\n .array(z.string())\n .optional()\n .describe(\n 'Key entities mentioned (e.g., [\"customers\", \"orders\", \"products\"])',\n ),\n filters: z\n .array(z.string())\n .optional()\n .describe('Filter criteria (e.g., [\"last month\", \"status = active\"])'),\n aggregation: z\n .string()\n .optional()\n .describe(\n 'Aggregation type if any (e.g., \"sum revenue\", \"count orders\", \"top 10\")',\n ),\n ambiguities: z\n .array(z.string())\n .optional()\n .describe('Note any ambiguous parts you identified'),\n }),\n execute: async (\n { question, breakdown, entities, filters, aggregation, ambiguities },\n options,\n ): Promise<DecomposedQueryResult> => {\n const state = toState<Chat4State>(options);\n\n const decomposition: QuestionDecomposition = {\n originalQuestion: question,\n breakdown,\n entities,\n filters,\n aggregation,\n ambiguities,\n };\n\n // Format the decomposition for the SQL agent\n const decomposedPrompt = formatDecomposition(decomposition);\n\n try {\n // Try SQL generation with retry logic\n let lastError: string | undefined;\n\n for (let attempt = 0; attempt < RETRY_TEMPERATURES.length; attempt++) {\n const temperature = RETRY_TEMPERATURES[attempt];\n\n const agentInstance = decompositionSqlAgent.clone({\n model: wrapLanguageModel({\n model: decompositionSqlAgent.model,\n middleware: defaultSettingsMiddleware({\n settings: { temperature },\n }),\n }),\n });\n\n const prompt = lastError\n ? `${decomposedPrompt}\\n\\nPrevious attempt failed with: ${lastError}. Please fix the query.`\n : decomposedPrompt;\n\n const { experimental_output: output } = await generate(\n agentInstance,\n [user(prompt)],\n state,\n );\n\n if ('error' in output) {\n return {\n success: false,\n question,\n decomposition,\n error: output.error,\n attempts: attempt + 1,\n };\n }\n\n // Validate the SQL\n const validationError = await state.adapter.validate(output.sql);\n if (validationError) {\n lastError = validationError;\n continue;\n }\n\n // Execute the SQL\n const data = await state.adapter.execute(output.sql);\n\n return {\n success: true,\n question,\n decomposition,\n sql: output.sql,\n data,\n reasoning: output.reasoning,\n attempts: attempt + 1,\n };\n }\n\n // All retries exhausted\n return {\n success: false,\n question,\n decomposition,\n error: `Failed after ${RETRY_TEMPERATURES.length} attempts. Last error: ${lastError}`,\n attempts: RETRY_TEMPERATURES.length,\n };\n } catch (error) {\n return {\n success: false,\n question,\n decomposition,\n error:\n error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n },\n }),\n\n execute_sql: tool({\n description: `Execute a SQL query directly. Use for follow-up queries or when you already have SQL.`,\n inputSchema: z.object({\n sql: z\n .string()\n .min(1)\n .refine(\n (sql) =>\n sql.trim().toUpperCase().startsWith('SELECT') ||\n sql.trim().toUpperCase().startsWith('WITH'),\n {\n message: 'Only read-only SELECT or WITH queries are allowed.',\n },\n )\n .describe('The SQL query to execute.'),\n }),\n execute: async ({ sql }, options) => {\n const state = toState<Chat4State>(options);\n\n try {\n const validationError = await state.adapter.validate(sql);\n if (validationError) {\n return {\n success: false,\n error: `Validation failed: ${validationError}`,\n };\n }\n\n const data = await state.adapter.execute(sql);\n return {\n success: true,\n data,\n rowCount: Array.isArray(data) ? data.length : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Execution failed',\n };\n }\n },\n }),\n\n scratchpad: scratchpad_tool,\n};\n\n/**\n * Format a question decomposition into a prompt for the SQL agent\n */\nfunction formatDecomposition(decomposition: QuestionDecomposition): string {\n const parts: string[] = [\n `Original Question: ${decomposition.originalQuestion}`,\n '',\n 'Question Breakdown:',\n ...decomposition.breakdown.map((part, i) => ` ${i + 1}. ${part}`),\n ];\n\n if (decomposition.entities?.length) {\n parts.push('', `Entities: ${decomposition.entities.join(', ')}`);\n }\n\n if (decomposition.filters?.length) {\n parts.push('', `Filters: ${decomposition.filters.join(', ')}`);\n }\n\n if (decomposition.aggregation) {\n parts.push('', `Aggregation: ${decomposition.aggregation}`);\n }\n\n if (decomposition.ambiguities?.length) {\n parts.push(\n '',\n 'Potential Ambiguities:',\n ...decomposition.ambiguities.map((a) => ` - ${a}`),\n );\n }\n\n parts.push(\n '',\n 'Generate SQL that addresses each component of the breakdown.',\n );\n\n return parts.join('\\n');\n}\n\n/**\n * Chat4 Agent - Table Augmented Generation with question decomposition.\n *\n * This agent breaks down questions into semantic components before\n * generating SQL. This approach:\n * - Ensures all aspects of the question are addressed\n * - Makes the reasoning explicit\n * - Helps with complex multi-part questions\n */\nexport const chat4Agent = agent<never, Chat4State>({\n name: 'chat4-decomposition',\n model: groq('openai/gpt-oss-20b'),\n tools,\n prompt: (state) => {\n return `\n${state?.teachings || ''}\n${state?.introspection || ''}\n\nWhen answering questions that require database queries, use the query_with_decomposition tool.\n\nIMPORTANT: You must break down the question into semantic parts - describe WHAT is being asked, not HOW to implement it.\n\nGood breakdown example for \"Which customers bought the most expensive products last quarter?\":\n- \"customers who made purchases\" (entity relationship)\n- \"products they purchased\" (what products)\n- \"expensive products - need definition\" (filter criteria - note ambiguity)\n- \"last quarter\" (time filter)\n- \"most - ranking by count or value?\" (aggregation - note ambiguity)\n\nBad breakdown (too instructional):\n- \"JOIN customers with orders\" (this is HOW, not WHAT)\n- \"Use ORDER BY and LIMIT\" (this is implementation)\n\nBreak the question into its semantic aspects, and let the SQL specialist figure out the implementation.\n`;\n },\n});\n\nexport { tools as chat4Tools };\n", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent } from '@deepagents/agent';\n\nexport const explainerAgent = agent<{ explanation: string }, { sql: string }>({\n name: 'explainer',\n model: groq('openai/gpt-oss-20b'),\n prompt: (state) => dedent`\n You are an expert SQL tutor.\n Explain the following SQL query in plain English to a non-technical user.\n Focus on the intent and logic, not the syntax.\n\n <sql>\n ${state?.sql}\n </sql>\n `,\n output: z.object({\n explanation: z.string().describe('The explanation of the SQL query.'),\n }),\n});\n", "/**\n * A question/SQL pair extracted or synthesized for training data.\n */\nexport interface ExtractedPair {\n question: string;\n sql: string;\n context?: string[];\n success: boolean;\n}\n\n/**\n * Interface for all pair producers (extractors and synthesizers).\n * Implementations encapsulate their specific inputs and logic.\n */\nexport abstract class PairProducer<T extends ExtractedPair = ExtractedPair> {\n /**\n * Produce question/SQL pairs.\n */\n abstract produce(): AsyncGenerator<T[], void, unknown>;\n\n protected from(producer: PairProducer<ExtractedPair> | ExtractedPair[]) {\n return Array.isArray(producer)\n ? (async function* (pairs: ExtractedPair[]) {\n yield pairs;\n })(producer)\n : producer.produce();\n }\n\n public toPairs(): Promise<T[]> {\n return toPairs(this);\n }\n}\n\n/**\n * Entry point for producing pairs from any source.\n */\nexport async function toPairs<T extends ExtractedPair>(\n producer: PairProducer<T>,\n): Promise<T[]> {\n const pairs: T[] = [];\n for await (const chunk of producer.produce()) {\n pairs.push(...chunk);\n }\n return pairs;\n}\n", "import {\n type Teachables,\n clarification,\n guardrail,\n hint,\n styleGuide,\n workflow,\n} from './teachables.ts';\n\nexport interface TeachingsOptions {\n /**\n * Controls date/time clarification behavior:\n * - 'strict': Ask for clarification when date range is missing (production default)\n * - false: Skip date clarifications, assume all matching data (useful for evals/benchmarks)\n */\n date?: 'strict' | false;\n}\n\nexport function guidelines(options: TeachingsOptions = {}): Teachables[] {\n const { date = 'strict' } = options;\n\n const baseTeachings: Teachables[] = [\n // Schema adherence\n hint(\n 'Use only tables and columns that exist in the schema. Never reference non-existent entities.',\n ),\n hint(\n 'If the user asks to show a table or entity without specifying columns, use SELECT *.',\n ),\n hint(\n 'When showing items associated with another entity, include the item ID and the related details requested.',\n ),\n hint(\n 'When asked to \"show\" items, list them unless the user explicitly asks to count or total.',\n ),\n hint(\n 'Use canonical/LowCardinality values verbatim for filtering; [rows/size] hints suggest when to aggregate instead of listing.',\n ),\n\n // Joins and relationships\n hint(\n 'Use appropriate JOINs based on the relationships defined in the schema.',\n ),\n hint(\n 'Favor PK/indexed columns for joins and filters; follow relationship metadata for join direction and cardinality.',\n ),\n\n // Aggregations and calculations\n hint(\n 'Apply proper aggregations (COUNT, SUM, AVG, etc.) when the question implies summarization.',\n ),\n hint(\n 'When asked \"how many X are there\" about types/categories/statuses (e.g., \"how many statuses are there?\"), use COUNT(DISTINCT column). This asks about variety, not row count.',\n ),\n hint(\n 'Use window functions when the question requires ranking, running totals, or comparisons across rows.',\n ),\n\n // Query semantics\n hint(\n 'Words like \"reach\", \"reached\", \"hit\" with a value (e.g., \"temperature reach 80\") mean >= (greater than or equal), not = (exact match).',\n ),\n hint(\n 'For \"shared by\" two groups or mutually exclusive conditions (e.g., population > 1500 AND < 500), use INTERSECT between separate queries. A single WHERE with contradictory AND returns nothing.',\n ),\n hint(\n 'When filtering by a specific value from a joined table (e.g., \"students who registered course statistics\"), always include that WHERE condition. Do not omit mentioned filters.',\n ),\n hint(\n 'Handle NULL values appropriately using IS NULL, IS NOT NULL, or COALESCE.',\n ),\n\n // Style and readability\n styleGuide({\n prefer:\n 'Use meaningful aliases for tables and columns to improve readability.',\n }),\n styleGuide({\n prefer:\n 'Summaries should be concise, business-friendly, highlight key comparisons, and add a short helpful follow-up when useful.',\n }),\n\n // Guardrails - Query safety\n guardrail({\n rule: 'Generate ONLY valid, executable SQL.',\n reason: 'Invalid SQL wastes resources and confuses users.',\n action: 'Validate syntax and schema references before returning.',\n }),\n guardrail({\n rule: 'Only generate SELECT statements (read-only queries).',\n reason: 'Prevents accidental data modification.',\n action:\n 'Never generate INSERT, UPDATE, DELETE, DROP, or other DDL/DML statements.',\n }),\n guardrail({\n rule: 'Avoid unbounded scans on large tables.',\n reason: 'Protects performance and prevents runaway queries.',\n action:\n 'Ensure filters are applied on indexed columns before querying broad fact tables.',\n }),\n guardrail({\n rule: 'Do not add LIMIT unless explicitly requested.',\n action:\n 'Only add LIMIT when user explicitly asks for \"top N\", \"first N\", or similar. Do NOT add LIMIT for \"list all\", \"show all\", or simple \"list\" queries.',\n reason: 'Adding arbitrary limits changes query semantics.',\n }),\n guardrail({\n rule: 'Add ORDER BY where appropriate for deterministic results.',\n reason: 'Ensures consistent query output.',\n action:\n 'Include ORDER BY when results have a natural ordering or when combined with LIMIT.',\n }),\n guardrail({\n rule: 'Prevent cartesian or guesswork joins.',\n reason: 'Protect correctness and performance.',\n action:\n 'If join keys are missing or unclear, inspect relationships and ask for the intended join path before executing.',\n }),\n guardrail({\n rule: 'Ensure the query is optimized for the schema.',\n reason: 'Better performance and resource usage.',\n action:\n 'Use indexed columns for filtering, avoid SELECT * on large joins, prefer specific column selection when appropriate.',\n }),\n guardrail({\n rule: 'When facing genuine ambiguity with multiple valid interpretations, seek clarification.',\n reason: 'Prevents incorrect assumptions in edge cases.',\n action:\n 'Ask a focused clarifying question before proceeding with a guess.',\n }),\n\n // Clarifications\n clarification({\n when: 'The request uses ambiguous scoring or ranking language (e.g., \"top\", \"best\", \"active\") without a metric.',\n ask: 'Clarify the ranking metric or definition before writing the query.',\n reason: 'Ensures the correct aggregation/ordering is used.',\n }),\n\n // Workflow\n workflow({\n task: 'SQL generation plan',\n steps: [\n 'Scan column names for terms matching the question. If a phrase like \"total X\" or \"number of Y\" matches a column name (e.g., Total_X, Num_Y), select that column directly instead of aggregating.',\n 'Translate the question into SQL patterns (aggregation, segmentation, time range, ranking) only if no column name match.',\n 'Choose tables/relations that satisfy those patterns; note lookup tables and filter values implied by schema hints.',\n 'Sketch join/filter/aggregation order considering table sizes, indexes, and stats.',\n 'Generate precise, validated SQL that answers the question.',\n ],\n }),\n ];\n\n // Date-specific clarifications (only when strict)\n if (date === 'strict') {\n baseTeachings.push(\n clarification({\n when: 'The request targets time-based data without a date range.',\n ask: 'Confirm the intended timeframe (e.g., last 30/90 days, YTD, specific year).',\n reason: 'Prevents large scans and irrelevant results.',\n }),\n );\n } else {\n // When date is false, assume all matching data without asking\n baseTeachings.push(\n hint(\n 'When a month, day, or time period is mentioned without a year (e.g., \"in August\", \"on Monday\"), assume ALL occurrences of that period in the data. Do not ask for year clarification.',\n ),\n );\n }\n\n return baseTeachings;\n}\n"],
|
|
5
|
-
"mappings": ";AA+CO,SAAS,yBAA2C;AACzD,SAAO;AAAA,IACL,QAAQ,CAAC;AAAA,IACT,OAAO,CAAC;AAAA,IACR,eAAe,CAAC;AAAA,IAChB,MAAM;AAAA,EACR;AACF;;;AC0DO,IAAe,UAAf,MAAuB;AAAA,EAc5B,MAAM,WAAW,MAAM,uBAAuB,GAAG;AAC/C,UAAM,QAAoD,CAAC;AAC3D,eAAW,MAAM,KAAK,WAAW;AAC/B,YAAM,YAAY,GAAG,IAAI;AACzB,YAAM,KAAK;AAAA,QACT,KAAK,UAAU;AAAA,QACf,IAAI,MAAM,UAAU,QAAQ,GAAG;AAAA,MACjC,CAAC;AAAA,IACH;AACA,WAAO,MACJ,IAAI,CAAC,EAAE,IAAI,IAAI,MAAM;AACpB,YAAM,cAAc,GAAG;AACvB,UAAI,gBAAgB,MAAM;AACxB,eAAO;AAAA,MACT;AACA,aAAO,IAAI,GAAG;AAAA,EAAM,WAAW;AAAA,IAAO,GAAG;AAAA,IAC3C,CAAC,EACA,KAAK,IAAI;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EA+BA,SAAS,OAAoC;AAC3C,QAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GAAG;AACvD,aAAO;AAAA,IACT;AACA,QAAI,OAAO,UAAU,UAAU;AAC7B,aAAO,OAAO,KAAK;AAAA,IACrB;AACA,QAAI,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,IAAI;AACpD,YAAM,SAAS,OAAO,KAAK;AAC3B,aAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAAA,IAC5C;AACA,WAAO;AAAA,EACT;AAAA;A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AAC,kBAAkB,aAAa;AAClC,kBAAQ;AAAA,YACN;AAAA,YACA,KAAK,UAAU,WAAW;AAAA,UAC5B;AACA,gBAAM,KAAK,QAAQ,QAAQ,WAAW;AAAA,YACpC,IAAIC,IAAG;AAAA,YACP,QAAQ,OAAO;AAAA,YACf,MAAM,YAAY;AAAA,YAClB,SAAS;AAAA,UACX,CAAC;AAAA,QACH;AAEA,cAAM,KAAK,QAAQ,QAAQ,WAAW;AAAA,UACpC,IAAIA,IAAG;AAAA,UACP,QAAQ,OAAO;AAAA,UACf,MAAM,gBAAgB;AAAA,UACtB,SAAS;AAAA,QACX,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
|
|
6
|
-
"names": ["groq", "z", "agent", "term", "clarification", "teachable", "tag", "z", "agent", "groq", "path", "process", "createHash", "existsSync", "hash", "path", "DatabaseSync", "path", "DatabaseSync", "v7", "generate", "user", "groq", "tool", "z", "agent", "toState", "scratchpad_tool", "groq", "
|
|
3
|
+
"sources": ["../src/lib/adapters/groundings/context.ts", "../src/lib/adapters/adapter.ts", "../src/lib/agents/developer.agent.ts", "../src/lib/agents/explainer.agent.ts", "../src/lib/agents/sql.agent.ts", "../src/lib/teach/xml.ts", "../src/lib/teach/teachables.ts", "../src/lib/agents/suggestions.agents.ts", "../src/lib/agents/text2sql.agent.ts", "../src/lib/memory/memory.prompt.ts", "../src/lib/checkpoint.ts", "../src/lib/file-cache.ts", "../src/lib/history/history.ts", "../src/lib/history/sqlite.history.ts", "../src/lib/history/history.sqlite.sql", "../src/lib/history/memory.history.ts", "../src/lib/memory/sqlite.store.ts", "../src/lib/memory/store.sqlite.sql", "../src/lib/memory/store.ts", "../src/lib/memory/memory.store.ts", "../src/lib/sql.ts", "../src/lib/agents/bi.agent.ts", "../src/lib/agents/chat1.agent.ts", "../src/lib/agents/chat2.agent.ts", "../src/lib/agents/chat3.agent.ts", "../src/lib/agents/chat4.agent.ts", "../src/lib/synthesis/types.ts", "../src/lib/teach/teachings.ts"],
|
|
4
|
+
"sourcesContent": ["import type { AdapterInfo, ColumnStats, Relationship, Table } from '../adapter.ts';\nimport type { View } from './view.grounding.ts';\n\n/**\n * Column type for grounding operations.\n * Common interface between Table.columns and View.columns.\n */\nexport interface Column {\n name: string;\n type: string;\n kind?: 'LowCardinality' | 'Enum';\n values?: string[];\n stats?: ColumnStats;\n}\n\n/**\n * Entity with columns (Table or View).\n */\nexport interface ColumnContainer {\n name: string;\n columns: Column[];\n}\n\n/**\n * Shared context object passed to all groundings.\n * Groundings read from and write to this context.\n */\nexport interface GroundingContext {\n /** Tables discovered by TableGrounding */\n tables: Table[];\n\n /** Views discovered by ViewGrounding */\n views: View[];\n\n /** Relationships discovered by TableGrounding */\n relationships: Relationship[];\n\n /** Database info collected by InfoGrounding */\n info?: AdapterInfo;\n\n /** Business context report generated by ReportGrounding */\n report?: string;\n}\n\n/**\n * Create a new empty grounding context.\n */\nexport function createGroundingContext(): GroundingContext {\n return {\n tables: [],\n views: [],\n relationships: [],\n info: undefined,\n };\n}\n", "import type { AbstractGrounding } from './groundings/abstract.grounding.ts';\nimport { createGroundingContext } from './groundings/context.ts';\n\n/**\n * Filter type for view/table names.\n * - string[]: explicit list of view names\n * - RegExp: pattern to match view names\n * - function: predicate to filter view names\n */\nexport type Filter = string[] | RegExp | ((viewName: string) => boolean);\n\nexport interface Table {\n name: string;\n schema?: string;\n rawName?: string;\n columns: {\n name: string;\n type: string;\n kind?: 'LowCardinality' | 'Enum';\n values?: string[];\n isIndexed?: boolean;\n stats?: ColumnStats;\n }[];\n rowCount?: number;\n sizeHint?: 'tiny' | 'small' | 'medium' | 'large' | 'huge';\n indexes?: TableIndex[];\n constraints?: TableConstraint[];\n}\n\nexport interface TableIndex {\n name: string;\n columns: string[];\n unique?: boolean;\n type?: string;\n}\n\nexport interface TableConstraint {\n name: string;\n type:\n | 'CHECK'\n | 'UNIQUE'\n | 'NOT_NULL'\n | 'DEFAULT'\n | 'PRIMARY_KEY'\n | 'FOREIGN_KEY';\n columns?: string[];\n definition?: string;\n defaultValue?: string;\n referencedTable?: string;\n referencedColumns?: string[];\n}\n\nexport interface ColumnStats {\n min?: string;\n max?: string;\n nullFraction?: number;\n}\n\nexport type Relationship = {\n table: string;\n from: string[];\n referenced_table: string;\n to: string[];\n};\n\nexport type TablesFilter = string[] | RegExp;\n\nexport interface Introspection {\n tables: Table[];\n relationships: Relationship[];\n}\n\nexport interface AdapterInfo {\n dialect: string;\n version?: string;\n database?: string;\n details?: Record<string, unknown>;\n}\n\nexport type AdapterInfoProvider =\n | AdapterInfo\n | (() => Promise<AdapterInfo> | AdapterInfo);\n\nexport type IntrospectionPhase =\n | 'tables'\n | 'row_counts'\n | 'primary_keys'\n | 'indexes'\n | 'column_stats'\n | 'low_cardinality'\n | 'relationships';\n\nexport interface IntrospectionProgress {\n phase: IntrospectionPhase;\n message: string;\n current?: number;\n total?: number;\n}\n\nexport type OnProgress = (progress: IntrospectionProgress) => void;\n\nexport interface IntrospectOptions {\n onProgress?: OnProgress;\n}\n\nexport type GroundingFn = (adapter: Adapter) => AbstractGrounding;\n\nexport type ExecuteFunction = (sql: string) => Promise<any> | any;\nexport type ValidateFunction = (\n sql: string,\n) => Promise<string | void> | string | void;\n\nexport abstract class Adapter {\n abstract grounding: GroundingFn[];\n\n /**\n * Default schema name for this database.\n * PostgreSQL: 'public', SQL Server: 'dbo', SQLite: undefined\n */\n abstract readonly defaultSchema: string | undefined;\n\n /**\n * System schemas to exclude from introspection by default.\n */\n abstract readonly systemSchemas: string[];\n\n async introspect(ctx = createGroundingContext()) {\n const lines: { tag: string; fn: () => string | null }[] = [];\n for (const fn of this.grounding) {\n const grounding = fn(this);\n lines.push({\n tag: grounding.tag,\n fn: await grounding.execute(ctx),\n });\n }\n return lines\n .map(({ fn, tag }) => {\n const description = fn();\n if (description === null) {\n return '';\n }\n return `<${tag}>\\n${description}\\n</${tag}>`;\n })\n .join('\\n');\n }\n abstract execute(sql: string): Promise<any[]> | any[];\n abstract validate(sql: string): Promise<string | void> | string | void;\n abstract runQuery<Row>(sql: string): Promise<Row[]> | Row[];\n\n /**\n * Quote an identifier (table/column name) for safe use in SQL.\n * Each database uses different quoting styles.\n */\n abstract quoteIdentifier(name: string): string;\n\n /**\n * Escape a string value for safe use in SQL.\n * Each database escapes different characters.\n */\n abstract escape(value: string): string;\n\n /**\n * Build a SELECT query to sample rows from a table.\n * Each database uses different syntax for limiting rows (LIMIT vs TOP).\n */\n abstract buildSampleRowsQuery(\n tableName: string,\n columns: string[] | undefined,\n limit: number,\n ): string;\n\n /**\n * Convert unknown database value to number.\n * Handles number, bigint, and string types.\n */\n toNumber(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) {\n return value;\n }\n if (typeof value === 'bigint') {\n return Number(value);\n }\n if (typeof value === 'string' && value.trim() !== '') {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n }\n\n /**\n * Parse a potentially qualified table name into schema and table parts.\n */\n parseTableName(name: string): { schema: string; table: string } {\n if (name.includes('.')) {\n const [schema, ...rest] = name.split('.');\n return { schema, table: rest.join('.') };\n }\n return { schema: this.defaultSchema ?? '', table: name };\n }\n\n /**\n * Escape a string value for use in SQL string literals (single quotes).\n * Used in WHERE clauses like: WHERE name = '${escapeString(value)}'\n */\n escapeString(value: string): string {\n return value.replace(/'/g, \"''\");\n }\n\n /**\n * Build a SQL filter clause to include/exclude schemas.\n * @param columnName - The schema column name (e.g., 'TABLE_SCHEMA')\n * @param allowedSchemas - If provided, filter to these schemas only\n */\n buildSchemaFilter(columnName: string, allowedSchemas?: string[]): string {\n if (allowedSchemas && allowedSchemas.length > 0) {\n const values = allowedSchemas\n .map((s) => `'${this.escapeString(s)}'`)\n .join(', ');\n return `AND ${columnName} IN (${values})`;\n }\n if (this.systemSchemas.length > 0) {\n const values = this.systemSchemas\n .map((s) => `'${this.escapeString(s)}'`)\n .join(', ');\n return `AND ${columnName} NOT IN (${values})`;\n }\n return '';\n }\n}\n\nexport function filterTablesByName<T extends { name: string }>(\n tables: T[],\n filter: TablesFilter | undefined,\n): T[] {\n if (!filter) return tables;\n return tables.filter((table) => matchesFilter(table.name, filter));\n}\n\nexport function filterRelationshipsByTables(\n relationships: Relationship[],\n tableNames: Set<string> | undefined,\n): Relationship[] {\n if (tableNames === undefined) {\n return relationships;\n }\n if (tableNames.size === 0) {\n return [];\n }\n return relationships.filter(\n (it) => tableNames.has(it.table) || tableNames.has(it.referenced_table),\n );\n}\n\nexport function applyTablesFilter(\n tables: Table[],\n relationships: Relationship[],\n filter: TablesFilter | undefined,\n): { tables: Table[]; relationships: Relationship[] } {\n if (!filter) {\n return { tables, relationships };\n }\n\n const allowedNames = new Set(\n getTablesWithRelated(tables, relationships, filter),\n );\n\n return {\n tables: tables.filter((table) => allowedNames.has(table.name)),\n relationships: filterRelationshipsByTables(relationships, allowedNames),\n };\n}\n\nexport function matchesFilter(\n tableName: string,\n filter: TablesFilter,\n): boolean {\n if (Array.isArray(filter)) {\n return filter.includes(tableName);\n }\n return filter.test(tableName);\n}\n\nexport function getTablesWithRelated(\n allTables: Table[],\n relationships: Relationship[],\n filter: TablesFilter,\n): string[] {\n const matchedTables = filterTablesByName(allTables, filter).map(\n (it) => it.name,\n );\n\n if (matchedTables.length === 0) {\n return [];\n }\n\n const adjacency = new Map<string, Set<string>>();\n\n for (const rel of relationships) {\n if (!adjacency.has(rel.table)) {\n adjacency.set(rel.table, new Set());\n }\n if (!adjacency.has(rel.referenced_table)) {\n adjacency.set(rel.referenced_table, new Set());\n }\n adjacency.get(rel.table)!.add(rel.referenced_table);\n adjacency.get(rel.referenced_table)!.add(rel.table);\n }\n\n const result = new Set<string>(matchedTables);\n const queue = [...matchedTables];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n const neighbors = adjacency.get(current);\n\n if (!neighbors) {\n continue;\n }\n\n for (const neighbor of neighbors) {\n if (!result.has(neighbor)) {\n result.add(neighbor);\n queue.push(neighbor);\n }\n }\n }\n\n return Array.from(result);\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { tool } from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent, generate, toState } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport type { Teachables } from '../teach/teachables.ts';\nimport { explainerAgent } from './explainer.agent.ts';\nimport { toSql } from './sql.agent.ts';\n\n/**\n * State passed to the developer agent\n */\nexport type DeveloperAgentState = {\n /** Database adapter for validation */\n adapter: Adapter;\n /** Schema introspection XML */\n introspection: string;\n /** Combined teachings/instructions */\n teachings: string;\n /** Instructions for SQL generation */\n instructions: Teachables[];\n};\n\nconst tools = {\n /**\n * Generate SQL from natural language question.\n * Uses the toSql function with retry logic and validation.\n */\n generate_sql: tool({\n description: dedent`\n Generate a validated SQL query from a natural language question.\n The query is automatically validated against the database schema.\n Use this when the user asks a question that requires data retrieval.\n\n Returns the SQL query along with generation metadata (attempts, any errors encountered).\n `,\n inputSchema: z.object({\n question: z\n .string()\n .min(1)\n .describe('The natural language question to convert to SQL'),\n }),\n execute: async ({ question }, options) => {\n const state = toState<DeveloperAgentState>(options);\n try {\n const result = await toSql({\n input: question,\n adapter: state.adapter,\n introspection: state.introspection,\n instructions: state.instructions,\n });\n return {\n success: true,\n sql: result.sql,\n attempts: result.attempts,\n errors: result.errors,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n },\n }),\n\n /**\n * Get plain-English explanation of a SQL query.\n */\n explain_sql: tool({\n description: dedent`\n Get a plain-English explanation of a SQL query.\n Use this to help the user understand what a query does.\n\n The explanation focuses on intent and logic, not syntax.\n `,\n inputSchema: z.object({\n sql: z.string().min(1).describe('The SQL query to explain'),\n }),\n execute: async ({ sql }) => {\n const { experimental_output } = await generate(explainerAgent, [], {\n sql,\n });\n return { explanation: experimental_output.explanation };\n },\n }),\n\n /**\n * Show database schema introspection.\n */\n show_schema: tool({\n description: dedent`\n Display the database schema introspection.\n Use this when the user wants to see available tables, columns, or relationships.\n\n Optionally filter by table name to reduce output.\n `,\n inputSchema: z.object({\n table: z\n .string()\n .optional()\n .describe(\n 'Optional: filter to show only a specific table. If omitted, shows full schema.',\n ),\n }),\n execute: async ({ table }, options) => {\n const state = toState<DeveloperAgentState>(options);\n\n if (!table) {\n return { schema: state.introspection };\n }\n\n // Filter introspection to show only the requested table\n // The introspection is XML, so we do a simple string search\n const lines = state.introspection.split('\\n');\n const tableLines: string[] = [];\n let inTable = false;\n let depth = 0;\n\n for (const line of lines) {\n const lowerLine = line.toLowerCase();\n\n // Check if this line starts the target table\n if (\n lowerLine.includes(`name=\"${table.toLowerCase()}\"`) ||\n lowerLine.includes(`table=\"${table.toLowerCase()}\"`)\n ) {\n inTable = true;\n depth = 1;\n tableLines.push(line);\n continue;\n }\n\n if (inTable) {\n tableLines.push(line);\n\n // Track depth for nested tags\n if (line.includes('</')) {\n depth--;\n }\n if (\n line.includes('<') &&\n !line.includes('</') &&\n !line.includes('/>')\n ) {\n depth++;\n }\n\n // End when we close the table tag\n if (depth <= 0) {\n break;\n }\n }\n }\n\n if (tableLines.length === 0) {\n return {\n schema: `Table \"${table}\" not found in schema. Use show_schema without a table filter to see all available tables.`,\n };\n }\n\n return { schema: tableLines.join('\\n') };\n },\n }),\n\n /**\n * Developer scratchpad for notes and reasoning.\n */\n scratchpad: scratchpad_tool,\n};\n\n/**\n * Developer Agent - Power-user conversational interface for SQL generation\n *\n * This agent provides tools for SQL generation, validation, and explanation\n * without execution. Designed for developers/DBAs who want full control\n * over query building and refinement.\n *\n * Tools:\n * - generate_sql: Convert natural language to validated SQL\n * - validate_sql: Check SQL syntax without execution\n * - explain_sql: Get plain-English explanation of SQL\n * - show_schema: Display schema introspection on demand\n * - scratchpad: Developer notes/reasoning\n */\nexport const developerAgent = agent<never, DeveloperAgentState>({\n model: groq('gpt-oss-20b'),\n tools,\n name: 'developer_agent',\n prompt: (state) => {\n return dedent`\n You are an expert SQL developer assistant helping power users build and refine queries.\n\n ## Your Capabilities\n\n You have access to the following tools:\n\n 1. **generate_sql**: Convert natural language questions to validated SQL queries\n - Automatically validates against the database schema\n - Returns generation metadata (attempts, errors if any)\n\n 2. **explain_sql**: Get a plain-English explanation of any SQL query\n - Helps users understand complex queries\n - Focuses on intent and logic, not syntax\n\n 3. **show_schema**: Display database schema information\n - Can show full schema or filter by table name\n - Use to explore available tables and columns\n\n 4. **scratchpad**: Record your reasoning and notes\n\n ## Guidelines\n\n - Be transparent: show the SQL you generate before explaining it\n - Be precise: provide exact column names and table references\n - Be helpful: suggest refinements and alternatives when appropriate\n - Support both natural language questions AND raw SQL input\n - When validating user SQL, explain any errors clearly\n - Use show_schema proactively when you need to verify table/column names\n\n ${state?.teachings || ''}\n ${state?.introspection || ''}\n `;\n },\n});\n", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent } from '@deepagents/agent';\n\nexport const explainerAgent = agent<{ explanation: string }, { sql: string }>({\n name: 'explainer',\n model: groq('openai/gpt-oss-20b'),\n prompt: (state) => dedent`\n You are an expert SQL tutor.\n Explain the following SQL query in plain English to a non-technical user.\n Focus on the intent and logic, not the syntax.\n\n <sql>\n ${state?.sql}\n </sql>\n `,\n output: z.object({\n explanation: z.string().describe('The explanation of the SQL query.'),\n }),\n});\n", "import { groq } from '@ai-sdk/groq';\nimport {\n APICallError,\n JSONParseError,\n NoContentGeneratedError,\n NoObjectGeneratedError,\n NoOutputGeneratedError,\n TypeValidationError,\n defaultSettingsMiddleware,\n wrapLanguageModel,\n} from 'ai';\nimport { Console } from 'node:console';\nimport { createWriteStream } from 'node:fs';\nimport pRetry from 'p-retry';\nimport z from 'zod';\n\nimport {\n type AgentModel,\n agent,\n generate,\n toOutput,\n user,\n} from '@deepagents/agent';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport {\n type Teachables,\n persona,\n toInstructions,\n} from '../teach/teachables.ts';\n\nexport interface ToSqlOptions {\n /** The natural language input to convert to SQL */\n input: string;\n /** Database adapter for validation */\n adapter: Adapter;\n /** Introspection/schema context */\n introspection: string;\n /** Instructions/teachings to include */\n instructions: Teachables[];\n /** Optional model override */\n model?: AgentModel;\n /** Maximum retry attempts on validation failure (default: 3) */\n maxRetries?: number;\n}\n\nexport interface ToSqlResult {\n /** The generated SQL query */\n sql: string;\n /** Number of attempts made */\n attempts: number;\n /** Validation errors encountered (if any retries occurred) */\n errors?: string[];\n}\n\nconst logger = new Console({\n stdout: createWriteStream('./sql-agent.log', { flags: 'a' }),\n stderr: createWriteStream('./sql-agent-error.log', { flags: 'a' }),\n inspectOptions: { depth: null },\n});\n\ntype SqlGeneratorState = {\n // FIXME: this should not be here after creating the context package\n introspection: string;\n teachings: string;\n};\n\ntype SqlGeneratorOutput =\n | { sql: string; reasoning?: string }\n | { error: string };\n\n/**\n * Agent that generates SQL queries from introspection and natural language questions.\n * Used for creating synthetic training data for text-to-SQL models.\n */\n/** Temperature progression for retries: deterministic first, then increasingly exploratory */\nconst RETRY_TEMPERATURES = [0, 0.2, 0.3];\n\nconst sqlQueryAgent = agent<SqlGeneratorOutput, SqlGeneratorState>({\n name: 'text2sql',\n model: groq('openai/gpt-oss-20b'),\n logging: process.env.AGENT_LOGGING === 'true',\n output: z.union([\n z.object({\n sql: z.string().describe('The SQL query that answers the question'),\n reasoning: z\n .string()\n .optional()\n .describe('The reasoning steps taken to generate the SQL'),\n }),\n z.object({\n error: z\n .string()\n .describe(\n 'Error message explaining why the question cannot be answered with the given schema',\n ),\n }),\n ]),\n prompt: (state) => {\n return `\n ${state?.teachings || ''}\n ${state?.introspection || ''}\n `;\n },\n});\n\n/** Extract SQL from markdown fenced code block if present */\nfunction extractSql(output: string): string {\n const match = output.match(/```sql\\n?([\\s\\S]*?)```/);\n return match ? match[1].trim() : output.trim();\n}\n\nconst marker = Symbol('SQLValidationError');\n/**\n * Error thrown when SQL validation fails.\n */\nexport class SQLValidationError extends Error {\n [marker]: true;\n constructor(message: string) {\n super(message);\n this.name = 'SQLValidationError';\n this[marker] = true;\n }\n static isInstance(error: unknown): error is SQLValidationError {\n return error instanceof SQLValidationError && error[marker] === true;\n }\n}\n\n/**\n * Error thrown when the question cannot be answered with the given schema.\n */\nexport class UnanswerableSQLError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'UnanswerableSQLError';\n }\n static isInstance(error: unknown): error is UnanswerableSQLError {\n return error instanceof UnanswerableSQLError;\n }\n}\n\nexport async function toSql(options: ToSqlOptions): Promise<ToSqlResult> {\n const { maxRetries = 3 } = options;\n\n return withRetry(\n async (attemptNumber, errors, attempts) => {\n const agentInstance = sqlQueryAgent.clone({\n model: wrapLanguageModel({\n model: options.model ?? sqlQueryAgent.model,\n middleware: defaultSettingsMiddleware({\n settings: {\n temperature: RETRY_TEMPERATURES[attemptNumber - 1] ?? 0.3,\n topP: 1,\n },\n }),\n }),\n });\n\n const messages = errors.length\n ? [\n user(options.input),\n user(\n `<validation_error>Your previous SQL query had the following error: ${errors.at(-1)?.message}. Please fix the query.</validation_error>`,\n ),\n ]\n : [user(options.input)];\n\n const output = await toOutput(\n generate(agentInstance, messages, {\n introspection: options.introspection,\n teachings: toInstructions(\n 'instructions',\n persona({\n name: 'Freya',\n role: 'You are an expert SQL query generator. You translate natural language questions into precise, efficient SQL queries based on the provided database schema.',\n }),\n ...options.instructions,\n ),\n }),\n );\n\n // Handle error responses (question is unanswerable with given schema)\n if ('error' in output) {\n throw new UnanswerableSQLError(output.error);\n }\n\n const sql = extractSql(output.sql);\n\n // Validate the generated SQL\n const validationError = await options.adapter.validate(sql);\n if (validationError) {\n throw new SQLValidationError(validationError);\n }\n\n return {\n attempts,\n sql,\n errors: errors.length ? errors.map(formatErrorMessage) : undefined,\n };\n },\n { retries: maxRetries - 1 },\n );\n}\n\nfunction formatErrorMessage(error: Error) {\n if (APICallError.isInstance(error)) {\n if (error.message.startsWith('Failed to validate JSON')) {\n return `Schema validation failed: ${error.message}`;\n }\n return error.message;\n }\n if (SQLValidationError.isInstance(error)) {\n return `SQL Validation Error: ${error.message}`;\n }\n return error.message;\n}\n\nasync function withRetry<T>(\n computation: (\n attemptNumber: number,\n errors: Error[],\n attempts: number,\n ) => Promise<T>,\n options: { retries: number } = { retries: 3 },\n) {\n const errors: Error[] = [];\n let attempts = 0;\n return pRetry(\n (attemptNumber) => {\n return computation(attemptNumber, errors, ++attempts);\n },\n {\n retries: options.retries,\n shouldRetry: (context) => {\n // Don't retry if unanswerable - it's intentional\n if (UnanswerableSQLError.isInstance(context.error)) {\n return false;\n }\n // Retry on validation errors\n if (SQLValidationError.isInstance(context.error)) {\n return true;\n }\n console.log({\n NoObjectGeneratedError: NoObjectGeneratedError.isInstance(\n context.error,\n ),\n NoOutputGeneratedError: NoOutputGeneratedError.isInstance(\n context.error,\n ),\n APICallError: APICallError.isInstance(context.error),\n JSONParseError: JSONParseError.isInstance(context.error),\n TypeValidationError: TypeValidationError.isInstance(context.error),\n NoContentGeneratedError: NoContentGeneratedError.isInstance(\n context.error,\n ),\n });\n // Retry on AI SDK errors\n return (\n APICallError.isInstance(context.error) ||\n JSONParseError.isInstance(context.error) ||\n TypeValidationError.isInstance(context.error) ||\n NoObjectGeneratedError.isInstance(context.error) ||\n NoOutputGeneratedError.isInstance(context.error) ||\n NoContentGeneratedError.isInstance(context.error)\n );\n },\n onFailedAttempt(context) {\n logger.error(`toSQL`, context.error);\n console.log(\n `Attempt ${context.attemptNumber} failed. There are ${context.retriesLeft} retries left.`,\n );\n // console.dir(context.error, { depth: null });\n errors.push(context.error);\n },\n },\n );\n}\n", "export function wrapBlock(tag: string, children: string[]): string {\n const content = children\n .filter((child): child is string => Boolean(child))\n .join('\\n');\n if (!content) {\n return '';\n }\n return `<${tag}>\\n${indentBlock(content, 2)}\\n</${tag}>`;\n}\n\nexport function list(tag: string, values: string[], childTag: string): string {\n if (!values.length) {\n return '';\n }\n const children = values.map((value) => leaf(childTag, value)).join('\\n');\n return `<${tag}>\\n${indentBlock(children, 2)}\\n</${tag}>`;\n}\n\nexport function leaf(tag: string, value: string): string {\n const safe = escapeXml(value);\n if (safe.includes('\\n')) {\n return `<${tag}>\\n${indentBlock(safe, 2)}\\n</${tag}>`;\n }\n return `<${tag}>${safe}</${tag}>`;\n}\n\nexport function indentBlock(text: string, spaces: number): string {\n if (!text.trim()) {\n return '';\n }\n const padding = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.length ? padding + line : padding))\n .join('\\n');\n}\n\nexport function escapeXml(value: string): string {\n if (value == null) {\n return '';\n }\n return value\n .replaceAll(/&/g, '&')\n .replaceAll(/</g, '<')\n .replaceAll(/>/g, '>')\n .replaceAll(/\"/g, '"')\n .replaceAll(/'/g, ''');\n}\n", "import { indentBlock, leaf, list, wrapBlock } from './xml.ts';\n\nexport interface Teachables {\n type: GeneratedTeachable['type'] | 'user_profile';\n /** Serialize to GeneratedTeachable for storage */\n encode: () => GeneratedTeachable;\n /** Render to XML string for prompts */\n decode: () => string;\n}\nexport type GeneratedTeachable =\n | { type: 'term'; name: string; definition: string }\n | { type: 'hint'; text: string }\n | { type: 'guardrail'; rule: string; reason?: string; action?: string }\n | {\n type: 'explain';\n concept: string;\n explanation: string;\n therefore?: string;\n }\n | { type: 'example'; question: string; answer: string; note?: string }\n | { type: 'clarification'; when: string; ask: string; reason: string }\n | {\n type: 'workflow';\n task: string;\n steps: string[];\n triggers?: string[];\n notes?: string;\n }\n | { type: 'quirk'; issue: string; workaround: string }\n | { type: 'styleGuide'; prefer: string; never?: string; always?: string }\n | {\n type: 'analogy';\n concept: string[];\n relationship: string;\n insight?: string;\n therefore?: string;\n pitfall?: string;\n }\n | { type: 'glossary'; entries: Record<string, string> }\n // User-specific teachable types\n | { type: 'identity'; name?: string; role?: string }\n | { type: 'persona'; name: string; role: string; tone: string }\n | { type: 'alias'; term: string; meaning: string }\n | { type: 'preference'; aspect: string; value: string }\n | { type: 'context'; description: string }\n | { type: 'correction'; subject: string; clarification: string };\n\n/**\n * Teach the system domain-specific vocabulary and business terminology.\n *\n * Use this to define simple, direct mappings between business terms and their meanings.\n * The system will understand these terms when users mention them in queries.\n *\n * @param name - The business term or acronym to define\n * @param definition - What the term means in your domain\n *\n * @example\n * // Logistics/Transportation dataset\n * term(\"deadhead miles\", \"distance driven with empty truck between deliveries\")\n * term(\"dwell time\", \"total time a truck spends at a loading dock or warehouse\")\n * term(\"LTL\", \"less than truckload - shipment that doesn't fill entire truck\")\n *\n * @example\n * // Education/University dataset\n * term(\"matriculation\", \"students who completed enrollment and started classes\")\n * term(\"DFW rate\", \"percentage of students receiving D, F, or Withdrawal in a course\")\n * term(\"cohort\", \"group of students who entered the same semester or academic year\")\n *\n * @example\n * // Finance/Banking dataset\n * term(\"NPL\", \"non-performing loan - loan past due 90+ days\")\n * term(\"basis points\", \"one hundredth of a percentage point (1% = 100 bps)\")\n * term(\"AUM\", \"assets under management - total market value of client investments\")\n */\nexport function term(name: string, definition: string): Teachables {\n return {\n type: 'term',\n encode: () => ({ type: 'term', name, definition }),\n decode: () =>\n wrapBlock('term', [leaf('name', name), leaf('definition', definition)]),\n };\n}\n\n/**\n * Teach the system behavioral rules and constraints that should always apply.\n *\n * Use this for business logic, data quality rules, or query preferences that should\n * be automatically applied to all relevant queries. Hints are injected as constraints\n * in the system prompt.\n *\n * @param text - The rule or constraint to follow (use imperative language)\n *\n * @example\n * // Manufacturing/Supply Chain dataset\n * hint(\"Always exclude work orders with status = 'simulation' from production metrics\")\n * hint(\"When calculating OEE (overall equipment effectiveness), only count scheduled production time\")\n * hint(\"Defect rates should be calculated per batch, not per individual unit, for consistency\")\n *\n * @example\n * // Real Estate/Property dataset\n * hint(\"Never include properties with listing_status = 'draft' in market analysis\")\n * hint(\"Always filter out duplicate MLS listings - use the earliest listing_date for each property_id\")\n * hint(\"Square footage comparisons must specify if including or excluding basement/garage\")\n *\n * @example\n * // Social Media/Content Platform dataset\n * hint(\"Engagement metrics should exclude bot accounts identified by is_verified_human = false\")\n * hint(\"View counts reset daily - always use cumulative_views for historical analysis\")\n * hint(\"Default content filters to published_status = 'public' unless analyzing drafts\")\n */\nexport function hint(text: string): Teachables {\n return {\n type: 'hint',\n encode: () => ({ type: 'hint', text }),\n decode: () => leaf('hint', text),\n };\n}\n\n/**\n * Define hard guardrails, safety rules, and compliance boundaries the system must enforce.\n *\n * Use this for \"never do\" rules, sensitive data handling, and required behaviors when\n * certain conditions occur. Guardrails should be explicit and action oriented.\n *\n * @param input.rule - The guardrail or restriction to enforce\n * @param input.reason - Why this guardrail exists (compliance, security, performance)\n * @param input.action - What to do when this guardrail is triggered (block, ask, sanitize)\n *\n * @example\n * // Healthcare dataset\n * guardrail({\n * rule: \"Never return PHI like SSN, MRN, or full address in query results\",\n * reason: \"HIPAA compliance\",\n * action: \"If asked, state that identifiable patient data cannot be shared; offer de-identified aggregates instead\"\n * })\n *\n * @example\n * // Finance dataset\n * guardrail({\n * rule: \"Block any query exposing employee-level compensation by name\",\n * reason: \"Confidential payroll data\",\n * action: \"Provide ranges grouped by department or level instead of individual salaries\"\n * })\n *\n * @example\n * // E-commerce dataset\n * guardrail({\n * rule: \"Warn when a query would scan more than 10 million rows; require a narrower date range\",\n * reason: \"Performance and cost control\",\n * action: \"Ask the user to add filters (recent timeframe, specific categories) before proceeding\"\n * })\n */\nexport function guardrail(input: {\n rule: string;\n reason?: string;\n action?: string;\n}): Teachables {\n const { rule, reason, action } = input;\n return {\n type: 'guardrail',\n encode: () => ({ type: 'guardrail', rule, reason, action }),\n decode: () =>\n wrapBlock('guardrail', [\n leaf('rule', rule),\n reason ? leaf('reason', reason) : '',\n action ? leaf('action', action) : '',\n ]),\n };\n}\n\n/**\n * Teach the system a rich understanding of a single concept using metaphors and explanations.\n *\n * Use this when a simple term definition isn't enough - when you need to convey deeper\n * understanding about how to think about and calculate a metric or concept.\n *\n * @param input.concept - The concept being explained\n * @param input.explanation - A metaphor or detailed explanation (often using real-world comparisons)\n * @param input.therefore - Optional actionable instruction based on this understanding\n *\n * @example\n * // Gaming/Entertainment dataset\n * explain({\n * concept: \"daily active users to monthly active users ratio\",\n * explanation: \"like measuring how many club members visit daily vs just once a month - shows stickiness\",\n * therefore: \"Calculate as DAU / MAU, where higher ratio (closer to 1) means more engaged user base\"\n * })\n *\n * @example\n * // HR/Employee Management dataset\n * explain({\n * concept: \"time to fill\",\n * explanation: \"like measuring how long a house sits on the market - from posting job to accepting offer\",\n * therefore: \"Calculate as days between job_posted_date and offer_accepted_date, exclude cancelled requisitions\"\n * })\n *\n * @example\n * // Telecommunications dataset\n * explain({\n * concept: \"network congestion ratio\",\n * explanation: \"like rush hour traffic density - measures actual usage vs total capacity at peak times\",\n * therefore: \"Calculate as (peak_hour_bandwidth_used / total_bandwidth_capacity) during busiest hour of day\"\n * })\n */\nexport function explain(input: {\n concept: string;\n explanation: string;\n therefore?: string;\n}): Teachables {\n const { concept, explanation, therefore } = input;\n return {\n type: 'explain',\n encode: () => ({ type: 'explain', concept, explanation, therefore }),\n decode: () =>\n wrapBlock('explanation', [\n leaf('concept', concept),\n leaf('details', explanation),\n therefore ? leaf('therefore', therefore) : '',\n ]),\n };\n}\n\n/**\n * Teach the system through concrete examples of question \u2192 SQL pairs.\n *\n * Use this for few-shot learning - show the system exactly how to translate\n * specific types of questions into SQL queries. Great for establishing patterns\n * and handling domain-specific query structures.\n *\n * @param input.question - The natural language question or request\n * @param input.answer - The correct answer that responds to the question\n * @param input.note - Optional note or explanation about the example\n *\n * @example\n * // Energy/Utilities dataset\n * example({\n * question: \"show me peak demand hours for the last week\",\n * answer: \"SELECT DATE_TRUNC('hour', reading_timestamp) as hour, MAX(consumption_kwh) as peak_demand FROM meter_readings WHERE reading_timestamp >= CURRENT_DATE - INTERVAL '7 days' GROUP BY hour ORDER BY peak_demand DESC LIMIT 10\"\n * })\n *\n * @example\n * // Agriculture/Farm Management dataset\n * example({\n * question: \"what is the average yield per acre by crop type this season\",\n * answer: \"SELECT crop_type, AVG(harvest_quantity / field_acres) as yield_per_acre FROM harvests WHERE harvest_date >= '2024-01-01' GROUP BY crop_type ORDER BY yield_per_acre DESC\"\n * })\n *\n * @example\n * // Travel/Hospitality dataset\n * example({\n * question: \"show me hotel occupancy rate for this month\",\n * answer: \"SELECT hotel_name, (SUM(occupied_rooms) / SUM(total_rooms)) * 100 as occupancy_rate FROM daily_occupancy WHERE date >= DATE_TRUNC('month', CURRENT_DATE) GROUP BY hotel_id, hotel_name ORDER BY occupancy_rate DESC\",\n * note: \"Occupancy rate is a percentage - multiply by 100 for readable output\"\n * })\n */\nexport function example(input: {\n question: string;\n answer: string;\n note?: string;\n}): Teachables {\n const { question, answer, note } = input;\n return {\n type: 'example',\n encode: () => ({ type: 'example', question, answer, note }),\n decode: () =>\n wrapBlock('example', [\n leaf('question', question),\n leaf('answer', answer),\n note ? leaf('note', note) : '',\n ]),\n };\n}\n\n/**\n * Teach the system when and what to ask for clarification.\n *\n * Use this to handle ambiguous terms or situations where the system should\n * proactively ask the user for more information before generating a query.\n * Makes the system more conversational and precise.\n *\n * @param input.when - The condition or trigger that should prompt clarification\n * @param input.ask - The question to ask the user\n * @param input.reason - Why this clarification is necessary (helps system understand importance)\n *\n * @example\n * // Marketing/Advertising dataset\n * clarification({\n * when: \"user asks for 'conversion rate'\",\n * ask: \"Which conversion: click-to-lead, lead-to-opportunity, or opportunity-to-customer?\",\n * reason: \"Conversion rate means different things at each funnel stage - need to specify which metric\"\n * })\n *\n * @example\n * // Food Delivery dataset\n * clarification({\n * when: \"user asks about 'delivery time'\",\n * ask: \"Do you mean estimated time at order, actual delivery time, or time from kitchen to door?\",\n * reason: \"Multiple time metrics exist - estimated vs actual impacts customer satisfaction differently\"\n * })\n *\n * @example\n * // Fitness/Gym Management dataset\n * clarification({\n * when: \"user mentions 'active members'\",\n * ask: \"Do you mean paid memberships or members who actually visited in last 30 days?\",\n * reason: \"Many paid members don't use facilities - different metrics for revenue vs utilization\"\n * })\n */\nexport function clarification(input: {\n when: string;\n ask: string;\n reason: string;\n}): Teachables {\n const { when, ask, reason } = input;\n return {\n type: 'clarification',\n encode: () => ({ type: 'clarification', when, ask, reason }),\n decode: () =>\n wrapBlock('clarification', [\n leaf('when', when),\n leaf('ask', ask),\n leaf('reason', reason),\n ]),\n };\n}\n\n/**\n * Teach the system multi-step analytical processes that can't be solved with a single query.\n *\n * Use this for complex analytical tasks that require multiple CTEs, sequential logic,\n * or specific methodologies. Workflows teach the system HOW to approach a type of analysis.\n *\n * @param input.task - Name of the analytical task\n * @param input.steps - Sequential steps to execute (can include SQL snippets or descriptions)\n * @param input.triggers - Optional phrases that should activate this workflow\n * @param input.notes - Optional additional context, warnings, or guidance\n *\n * @example\n * // Insurance dataset\n * workflow({\n * task: \"Claims Loss Ratio Analysis\",\n * triggers: [\"loss ratio\", \"claims ratio\", \"underwriting performance\"],\n * steps: [\n * \"Calculate total claims paid for each policy period\",\n * \"Calculate total premiums earned for same period\",\n * \"Compute loss ratio as (claims_paid / premiums_earned) * 100\",\n * \"Segment by policy type, geography, and underwriter\",\n * \"Identify policies with loss ratio > 100% (losing money)\",\n * \"Calculate trend over time using rolling 12-month windows\"\n * ],\n * notes: \"Use incurred date for claims, not paid date. Exclude reinsurance recoveries from claims total.\"\n * })\n *\n * @example\n * // Media/Publishing dataset\n * workflow({\n * task: \"Content Performance Funnel\",\n * triggers: [\"content funnel\", \"engagement funnel\", \"content performance\"],\n * steps: [\n * \"Count total impressions (articles shown) per content piece\",\n * \"Count click-throughs (articles opened)\",\n * \"Count scroll depth > 50% (meaningful engagement)\",\n * \"Count shares, comments, or saves (viral actions)\",\n * \"Calculate conversion rate at each funnel stage\",\n * \"Identify top-performing content by final conversion rate\"\n * ],\n * notes: \"Requires multiple event types. Join events table multiple times or use conditional aggregation.\"\n * })\n *\n * @example\n * // Sports Analytics dataset\n * workflow({\n * task: \"Player Performance Rating Calculation\",\n * triggers: [\"player rating\", \"performance score\", \"player analytics\"],\n * steps: [\n * \"Aggregate per-game stats: points, assists, rebounds, turnovers\",\n * \"Calculate efficiency metrics: shooting percentage, plus/minus\",\n * \"Normalize each metric using z-scores vs league average\",\n * \"Apply position-specific weights to each metric\",\n * \"Combine weighted scores into overall performance rating (0-100)\",\n * \"Rank players within position group and overall\"\n * ],\n * notes: \"Requires league-wide statistics for normalization. Update weights each season based on game trends.\"\n * })\n */\nexport function workflow(input: {\n task: string;\n steps: string[];\n triggers?: string[];\n notes?: string;\n}): Teachables {\n const { task, steps, triggers, notes } = input;\n return {\n type: 'workflow',\n encode: () => ({ type: 'workflow', task, steps, triggers, notes }),\n decode: () =>\n wrapBlock('workflow', [\n leaf('task', task),\n triggers?.length ? list('triggers', triggers, 'trigger') : '',\n list('steps', steps, 'step'),\n notes ? leaf('notes', notes) : '',\n ]),\n };\n}\n\n/**\n * Teach the system about data quirks, edge cases, or database-specific issues and their workarounds.\n *\n * Use this to document weird data patterns, database limitations, or special handling\n * required for specific scenarios. Helps the system navigate real-world messiness.\n *\n * @param input.issue - Description of the quirk, edge case, or problem\n * @param input.workaround - How to handle or work around this issue\n *\n * @example\n * // Government/Public Services dataset\n * quirk({\n * issue: \"Citizen IDs contain leading zeros but are stored as integers, losing the zeros\",\n * workaround: \"Always cast to VARCHAR and use LPAD(citizen_id::VARCHAR, 10, '0') to restore leading zeros\"\n * })\n *\n * @example\n * // Aviation dataset\n * quirk({\n * issue: \"Flight times crossing midnight show as negative duration (landing before takeoff)\",\n * workaround: \"Add 24 hours when calculated duration < 0: CASE WHEN duration < 0 THEN duration + INTERVAL '24 hours' ELSE duration END\"\n * })\n *\n * @example\n * // Automotive/Dealership dataset\n * quirk({\n * issue: \"VIN numbers with letter 'O' were incorrectly entered as zero '0' in legacy data\",\n * workaround: \"When searching by VIN, use REPLACE(vin, '0', 'O') or fuzzy matching to handle both cases\"\n * })\n */\nexport function quirk(input: {\n issue: string;\n workaround: string;\n}): Teachables {\n const { issue, workaround } = input;\n return {\n type: 'quirk',\n encode: () => ({ type: 'quirk', issue, workaround }),\n decode: () =>\n wrapBlock('quirk', [\n leaf('issue', issue),\n leaf('workaround', workaround),\n ]),\n };\n}\n\n/**\n * Teach the system SQL style preferences and coding standards for generated queries.\n *\n * Use this to enforce consistent SQL formatting, naming conventions, and best practices\n * specific to your team or organization. Improves readability and maintainability.\n *\n * @param input.prefer - Preferred SQL style or pattern\n * @param input.never - Optional anti-pattern to avoid\n * @param input.always - Optional rule that must always be followed\n *\n * @example\n * // Non-profit/Charity dataset\n * styleGuide({\n * prefer: \"Use donor-centric language in column aliases: 'donor_name' not 'customer_name'\",\n * never: \"Never expose internal donor IDs in external reports - use public gift IDs\",\n * always: \"Always include fiscal year in date-based aggregations (FY starts July 1)\"\n * })\n *\n * @example\n * // Legal/Law Firm dataset\n * styleGuide({\n * prefer: \"Use billable_hours with 2 decimal precision for accurate client billing\",\n * never: \"Never include attorney_rate in queries visible to paralegals - confidential data\",\n * always: \"Always filter by matter_status = 'open' unless specifically analyzing closed cases\"\n * })\n *\n * @example\n * // Inventory/Warehouse dataset\n * styleGuide({\n * prefer: \"Use location_id in joins rather than location_name (duplicates exist across warehouses)\",\n * never: \"Never aggregate inventory without grouping by warehouse_id first\",\n * always: \"Always use inventory_on_hand - inventory_reserved for available stock calculations\"\n * })\n */\nexport function styleGuide(input: {\n prefer: string;\n never?: string;\n always?: string;\n}): Teachables {\n const { prefer, never, always } = input;\n return {\n type: 'styleGuide',\n encode: () => ({ type: 'styleGuide', prefer, never, always }),\n decode: () =>\n wrapBlock('style_guide', [\n leaf('prefer', prefer),\n always ? leaf('always', always) : '',\n never ? leaf('never', never) : '',\n ]),\n };\n}\n\n/**\n * Teach the system by comparing related concepts through real-world analogies.\n *\n * Use this to teach relational understanding between two concepts by drawing comparisons\n * to familiar real-world scenarios. Helps the system understand WHY concepts differ and\n * when to use each one appropriately.\n *\n * @param input.concept - Array of two related concepts to compare\n * @param input.relationship - The comparison/analogy using real-world examples\n * @param input.insight - Optional key insight the analogy reveals\n * @param input.therefore - Optional actionable instruction based on this understanding\n * @param input.pitfall - Optional common mistake to avoid\n *\n * @example\n * // E-commerce dataset\n * analogy({\n * concept: [\"cart abandonment\", \"browse abandonment\"],\n * relationship: \"Cart abandonment is like leaving items at a checkout counter, browse abandonment is like window shopping without picking anything up\",\n * insight: \"Cart abandonment shows purchase intent (added to cart), browse abandonment shows only interest\",\n * therefore: \"Prioritize cart abandonment recovery campaigns - higher conversion potential than browse\",\n * pitfall: \"Don't combine both into generic 'abandonment rate' - they need different marketing strategies\"\n * })\n *\n * @example\n * // SaaS dataset\n * analogy({\n * concept: [\"logo churn\", \"revenue churn\"],\n * relationship: \"Logo churn is like counting how many customers left the store, revenue churn is how much money walked out\",\n * insight: \"Losing 10 small customers (high logo churn) might hurt less than losing 1 enterprise customer (high revenue churn)\",\n * therefore: \"Always report both metrics - logo churn for customer satisfaction, revenue churn for financial health\",\n * pitfall: \"Don't use logo churn to predict revenue impact - customer size distribution matters\"\n * })\n *\n * @example\n * // Healthcare dataset\n * analogy({\n * concept: [\"incident\", \"prevalence\"],\n * relationship: \"Incidence is like new house sales this month, prevalence is total houses currently occupied\",\n * insight: \"Incidence measures new cases over time, prevalence measures all existing cases at a point in time\",\n * therefore: \"For tracking disease outbreaks use incidence rate, for resource planning use prevalence\",\n * pitfall: \"Don't sum incidence rates across time periods - it's a rate not a count\"\n * })\n */\nexport function analogy(input: {\n concept: string[];\n relationship: string;\n insight?: string;\n therefore?: string;\n pitfall?: string;\n}): Teachables {\n const { concept, relationship, insight, therefore, pitfall } = input;\n return {\n type: 'analogy',\n encode: () => ({\n type: 'analogy',\n concept,\n relationship,\n insight,\n therefore,\n pitfall,\n }),\n decode: () =>\n wrapBlock('analogy', [\n list('concepts', concept, 'concept'),\n leaf('relationship', relationship),\n insight ? leaf('insight', insight) : '',\n therefore ? leaf('therefore', therefore) : '',\n pitfall ? leaf('pitfall', pitfall) : '',\n ]),\n };\n}\n\n/**\n * Map business terms directly to SQL expressions or fragments.\n *\n * Use this to teach the system how to CALCULATE or QUERY specific business concepts.\n * The system will substitute these SQL patterns when users mention the term.\n *\n * **Glossary vs Alias:**\n * - `alias` = user vocabulary \u2192 table/column name (\"the big table\" \u2192 \"orders table\")\n * - `glossary` = business term \u2192 SQL expression (\"revenue\" \u2192 \"SUM(orders.total_amount)\")\n *\n * In short: alias renames, glossary computes.\n *\n * @param entries - Record mapping business terms to their SQL expressions\n *\n * @example\n * glossary({\n * \"revenue\": \"SUM(orders.total_amount)\",\n * \"average order value\": \"AVG(orders.total_amount)\",\n * \"active user\": \"last_login > NOW() - INTERVAL '30 days'\",\n * \"churned\": \"status = 'churned'\",\n * \"power user\": \"order_count > 10\",\n * \"net revenue\": \"SUM(orders.total_amount) - SUM(refunds.amount)\",\n * })\n */\nexport function glossary(entries: Record<string, string>): Teachables {\n return {\n type: 'glossary',\n encode: () => ({ type: 'glossary', entries }),\n decode: () =>\n wrapBlock(\n 'glossary',\n Object.entries(entries).map(([term, sql]) =>\n wrapBlock('entry', [leaf('term', term), leaf('sql', sql)]),\n ),\n ),\n };\n}\n\n// =============================================================================\n// User-Specific Teachable Types\n// =============================================================================\n\n/**\n * Define the user's identity including name and/or role.\n *\n * Use this to capture who the user is and what lens they view data through.\n * Helps tailor explanations, terminology, and focus areas.\n *\n * @param input.name - The user's name (optional)\n * @param input.role - The user's role or position (optional)\n *\n * @example\n * identity({ name: \"John\", role: \"VP of Sales\" })\n * identity({ role: \"Data analyst in the marketing team\" })\n * identity({ name: \"Sarah\" })\n * identity({ role: \"Finance manager focused on cost optimization\" })\n */\nexport function identity(input: { name?: string; role?: string }): Teachables {\n const { name, role } = input;\n return {\n type: 'identity',\n encode: () => ({ type: 'identity', name, role }),\n decode: () =>\n wrapBlock('identity', [\n name ? leaf('name', name) : '',\n role ? leaf('role', role) : '',\n ]),\n };\n}\n\n/**\n * Define an AI persona with a name, role, and communication tone.\n *\n * Use this to customize the assistant's personality and how it communicates.\n * The persona influences the style and approach of responses.\n *\n * @param input.name - The persona's name\n * @param input.role - The persona's role or expertise\n * @param input.tone - The communication style (e.g., friendly, professional, concise)\n *\n * @example\n * persona({ name: \"DataBot\", role: \"SQL Expert\", tone: \"friendly and encouraging\" })\n * persona({ name: \"QueryMaster\", role: \"Database Analyst\", tone: \"professional and concise\" })\n * persona({ name: \"SQLHelper\", role: \"Data Assistant\", tone: \"casual and approachable\" })\n */\nexport function persona(input: {\n name: string;\n role: string;\n tone?: string;\n}): Teachables {\n const { name, role, tone } = input;\n return {\n type: 'persona',\n encode: () => ({ type: 'persona', name, role, tone: tone ?? '' }),\n decode: () =>\n wrapBlock('persona', [\n leaf('name', name),\n leaf('role', role),\n tone ? leaf('tone', tone) : '',\n ]),\n };\n}\n\n/**\n * Define user-specific term meanings and vocabulary.\n *\n * Use this when the user has their own definitions for terms that might\n * differ from standard or domain definitions. Like `term()` but personal.\n *\n * @param termName - The term the user uses\n * @param meaning - What the user means by this term\n *\n * @example\n * alias(\"revenue\", \"gross revenue before deductions, not net\")\n * alias(\"active users\", \"users who logged in within the last 30 days\")\n * alias(\"the big table\", \"the orders table\")\n * alias(\"Q4\", \"October through December, not fiscal Q4\")\n */\nexport function alias(termName: string, meaning: string): Teachables {\n return {\n type: 'alias',\n encode: () => ({ type: 'alias', term: termName, meaning }),\n decode: () =>\n wrapBlock('alias', [leaf('term', termName), leaf('meaning', meaning)]),\n };\n}\n\n/**\n * Define how the user prefers results presented.\n *\n * Use this to capture output formatting, style, and behavioral preferences\n * that should apply to all interactions with this user.\n *\n * @param aspect - What aspect of output this preference applies to\n * @param value - The user's preference\n *\n * @example\n * preference(\"date format\", \"YYYY-MM-DD\")\n * preference(\"output style\", \"tables over charts unless trend data\")\n * preference(\"detail level\", \"always show the SQL query in responses\")\n * preference(\"row limit\", \"default to 50 rows unless I ask for more\")\n * preference(\"explanation style\", \"brief and to the point\")\n */\nexport function preference(aspect: string, value: string): Teachables {\n return {\n type: 'preference',\n encode: () => ({ type: 'preference', aspect, value }),\n decode: () =>\n wrapBlock('preference', [leaf('aspect', aspect), leaf('value', value)]),\n };\n}\n\n/**\n * Define the user's current working focus or project.\n *\n * Use this to capture temporary context that helps inform defaults,\n * assumptions, and suggestions. Should be updated as focus changes.\n *\n * @param description - What the user is currently working on\n *\n * @example\n * context(\"Preparing Q4 board presentation\")\n * context(\"Investigating drop in signups last week\")\n * context(\"Working on EMEA regional analysis for strategy meeting\")\n * context(\"Debugging discrepancy in revenue numbers\")\n */\nexport function context(description: string): Teachables {\n return {\n type: 'context',\n encode: () => ({ type: 'context', description }),\n decode: () => leaf('context', description),\n };\n}\n\n/**\n * Record a correction the user made to previous understanding.\n *\n * Use this when the user corrects a misunderstanding about data, columns,\n * or business logic. Prevents repeating the same mistake.\n *\n * @param subject - What was misunderstood\n * @param clarification - The correct understanding\n *\n * @example\n * correction(\"status column\", \"1 = active, 0 = inactive, not boolean true/false\")\n * correction(\"orders table\", \"Use orders_v2, not the deprecated legacy_orders table\")\n * correction(\"date field\", \"order_date is when order was placed, ship_date is when shipped\")\n * correction(\"revenue calculation\", \"Must exclude refunds and chargebacks\")\n */\nexport function correction(subject: string, clarification: string): Teachables {\n return {\n type: 'correction',\n encode: () => ({ type: 'correction', subject, clarification }),\n decode: () =>\n wrapBlock('correction', [\n leaf('subject', subject),\n leaf('clarification', clarification),\n ]),\n };\n}\n\nexport function teachable(\n tag: string,\n ...teachables: Teachables[]\n): Teachables {\n return {\n type: 'user_profile',\n encode: () => teachables[0]?.encode() ?? ({ type: 'context', description: '' }),\n decode: () => toInstructions(tag, ...teachables),\n };\n}\n\nexport function toInstructions(\n tag: string,\n ...teachables: Teachables[]\n): string {\n if (!teachables.length) {\n return '';\n }\n\n const grouped = new Map<Teachables['type'], Teachables[]>();\n for (const teachable of teachables) {\n const existing = grouped.get(teachable.type) ?? [];\n existing.push(teachable);\n grouped.set(teachable.type, existing);\n }\n\n const definedTypes = new Set(SECTION_ORDER.map((s) => s.type));\n\n const sections = SECTION_ORDER.map(({ type, tag }) => {\n const items = grouped.get(type);\n if (!items?.length) {\n return '';\n }\n const renderedItems = items\n .map((item) => item.decode().trim())\n .filter(Boolean)\n .map((item) => indentBlock(item, 2))\n .join('\\n');\n if (!renderedItems.length) {\n return '';\n }\n return `<${tag}>\\n${renderedItems}\\n</${tag}>`;\n }).filter((section): section is string => Boolean(section));\n\n // Render types not defined in SECTION_ORDER at the end\n for (const [type, items] of grouped) {\n if (definedTypes.has(type)) {\n continue;\n }\n const renderedItems = items\n .map((item) => item.decode().trim())\n .filter(Boolean)\n .map((item) => indentBlock(item, 2))\n .join('\\n');\n if (renderedItems.length) {\n sections.push(renderedItems);\n }\n }\n\n if (!sections.length) {\n return '';\n }\n\n const content = indentBlock(sections.join('\\n'), 2);\n return `<${tag}>\\n${content}\\n</${tag}>`;\n}\n\nconst SECTION_ORDER: Array<{ type: Teachables['type']; tag: string }> = [\n // User context (render first - most important for personalization)\n { type: 'identity', tag: 'identity' },\n { type: 'persona', tag: 'persona' },\n { type: 'context', tag: 'user_context' },\n { type: 'preference', tag: 'user_preferences' },\n { type: 'alias', tag: 'user_vocabulary' },\n { type: 'correction', tag: 'user_corrections' },\n // Domain knowledge\n { type: 'guardrail', tag: 'guardrails' },\n { type: 'styleGuide', tag: 'style_guides' },\n { type: 'hint', tag: 'hints' },\n { type: 'clarification', tag: 'clarifications' },\n { type: 'workflow', tag: 'workflows' },\n { type: 'quirk', tag: 'quirks' },\n { type: 'term', tag: 'terminology' },\n { type: 'explain', tag: 'explanations' },\n { type: 'analogy', tag: 'analogies' },\n { type: 'glossary', tag: 'glossary' },\n { type: 'example', tag: 'examples' },\n];\n\nexport function toTeachables(generated: GeneratedTeachable[]): Teachables[] {\n return generated.map((item) => {\n switch (item.type) {\n case 'persona':\n return persona({ name: item.name, role: item.role, tone: item.tone });\n case 'term':\n return term(item.name, item.definition);\n case 'hint':\n return hint(item.text);\n case 'guardrail':\n return guardrail({\n rule: item.rule,\n reason: item.reason,\n action: item.action,\n });\n case 'explain':\n return explain({\n concept: item.concept,\n explanation: item.explanation,\n therefore: item.therefore,\n });\n case 'example':\n return example({\n question: item.question,\n answer: item.answer,\n note: item.note,\n });\n case 'clarification':\n return clarification({\n when: item.when,\n ask: item.ask,\n reason: item.reason,\n });\n case 'workflow':\n return workflow({\n task: item.task,\n steps: item.steps,\n triggers: item.triggers,\n notes: item.notes,\n });\n case 'quirk':\n return quirk({\n issue: item.issue,\n workaround: item.workaround,\n });\n case 'styleGuide':\n return styleGuide({\n prefer: item.prefer,\n never: item.never,\n always: item.always,\n });\n case 'analogy':\n return analogy({\n concept: item.concept,\n relationship: item.relationship,\n insight: item.insight,\n therefore: item.therefore,\n pitfall: item.pitfall,\n });\n case 'glossary':\n return glossary(item.entries);\n // User-specific teachable types\n case 'identity':\n return identity({ name: item.name, role: item.role });\n case 'alias':\n return alias(item.term, item.meaning);\n case 'preference':\n return preference(item.aspect, item.value);\n case 'context':\n return context(item.description);\n case 'correction':\n return correction(item.subject, item.clarification);\n }\n });\n}\n\n/**\n * Convert Teachables back to GeneratedTeachable format for storage.\n *\n * @param teachables - Array of Teachables to convert\n * @returns Array of GeneratedTeachable objects suitable for storage\n *\n * @example\n * const teachings = [term('NPL', 'non-performing loan'), hint('Always filter by status')];\n * const forStorage = fromTeachables(teachings);\n * // [{ type: 'term', name: 'NPL', definition: 'non-performing loan' }, { type: 'hint', text: 'Always filter by status' }]\n */\nexport function fromTeachables(teachables: Teachables[]): GeneratedTeachable[] {\n return teachables.map((t) => t.encode());\n}\n\n/**\n * Default export containing all system teachable factory functions.\n * Excludes user-specific teachables (identity, alias, preference, context, correction).\n */\nexport default {\n persona,\n term,\n hint,\n guardrail,\n explain,\n example,\n clarification,\n workflow,\n quirk,\n styleGuide,\n analogy,\n glossary,\n teachable,\n};\n", "import { groq } from '@ai-sdk/groq';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent, thirdPersonPrompt } from '@deepagents/agent';\n\nimport type { Introspection } from '../adapters/adapter.ts';\nimport { databaseSchemaPrompt } from '../prompt.ts';\n\ntype SuggestionsAgentContext = {\n context?: string;\n adapterInfo?: string;\n};\ntype SuggestionsAgentOutput = {\n suggestions: {\n question: string;\n sql: string;\n businessValue: string;\n }[];\n};\n\nexport const suggestionsAgent = agent<\n SuggestionsAgentOutput,\n SuggestionsAgentContext\n>({\n name: 'text2sql-suggestions',\n model: groq('openai/gpt-oss-20b'),\n output: z.object({\n suggestions: z\n .array(\n z.object({\n question: z\n .string()\n .describe('A complex, high-impact business question.'),\n sql: z\n .string()\n .describe('The SQL statement needed to answer the question.'),\n businessValue: z\n .string()\n .describe('Why the question matters to stakeholders.'),\n }),\n )\n .min(1)\n .max(5)\n .describe('A set of up to two advanced question + SQL pairs.'),\n }),\n prompt: (state) => {\n return dedent`\n ${thirdPersonPrompt()}\n\n <identity>\n You are a senior analytics strategist who proposes ambitious business questions\n and drafts the SQL needed to answer them. You specialize in identifying ideas\n that combine multiple tables, apply segmentation or time analysis, and surface\n metrics that drive executive decisions.\n </identity>\n\n\n <instructions>\n - Recommend one or two UNIQUE questions that go beyond simple counts or listings.\n - Favor questions that require joins, aggregates, time comparisons, cohort analysis,\n or window functions.\n - For each question, explain the business reason stakeholders care about it.\n - Provide the complete SQL query that could answer the question in the given schema.\n - Keep result sets scoped with LIMIT clauses (max 50 rows) when returning raw rows.\n - Ensure table/column names match the provided schema exactly.\n - Use columns marked [LowCardinality: ...] to identify meaningful categorical filters or segmentations.\n - Leverage table [rows / size] hints to determine whether to aggregate (large tables) or inspect detailed data (tiny tables).\n - Reference PK/Indexed annotations and the Indexes list to recommend queries that use efficient join/filter paths.\n - Column annotations may expose ranges/null percentages\u2014use them to suggest realistic thresholds or quality checks.\n - Consult <relationship_examples> to anchor your recommendations in the actual join paths between tables.\n - Output only information grounded in the schema/context provided.\n </instructions>\n\n <response-format>\n Return valid JSON that satisfies the defined output schema.\n </response-format>\n `;\n },\n});\n", "import { groq } from '@ai-sdk/groq';\nimport { type Tool, tool } from 'ai';\nimport z from 'zod';\n\nimport { agent, toState } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport memoryPrompt from '../memory/memory.prompt.ts';\nimport type { TeachablesStore } from '../memory/store.ts';\nimport type { GeneratedTeachable } from '../teach/teachables.ts';\n\nexport type RenderingTools = Record<string, Tool<unknown, never>>;\n\nconst tools = {\n validate_query: tool({\n description: `Validate SQL query syntax before execution. Use this to check if your SQL is valid before running db_query. This helps catch errors early and allows you to correct the query if needed.`,\n inputSchema: z.object({\n sql: z.string().describe('The SQL query to validate.'),\n }),\n execute: async ({ sql }, options) => {\n const state = toState<{ adapter: Adapter }>(options);\n const result = await state.adapter.validate(sql);\n if (typeof result === 'string') {\n return `Validation Error: ${result}`;\n }\n return 'Query is valid.';\n },\n }),\n get_sample_rows: tool({\n description: `Sample rows from a table to understand data formatting, codes, and value patterns. Use BEFORE writing queries when:\n- Column types in schema don't reveal format (e.g., \"status\" could be 'active'/'inactive' or 1/0)\n- Date/time formats are unclear (ISO, Unix timestamp, locale-specific)\n- You need to understand lookup table codes or enum values\n- Column names are ambiguous (e.g., \"type\", \"category\", \"code\")`,\n inputSchema: z.object({\n tableName: z.string().describe('The name of the table to sample.'),\n columns: z\n .array(z.string())\n .optional()\n .describe(\n 'Specific columns to sample. If omitted, samples all columns.',\n ),\n limit: z\n .number()\n .min(1)\n .max(10)\n .default(3)\n .optional()\n .describe('Number of rows to sample (1-10, default 3).'),\n }),\n execute: ({ tableName, columns, limit = 3 }, options) => {\n const safeLimit = Math.min(Math.max(1, limit), 10);\n const state = toState<{ adapter: Adapter }>(options);\n const sql = state.adapter.buildSampleRowsQuery(\n tableName,\n columns,\n safeLimit,\n );\n return state.adapter.execute(sql);\n },\n }),\n db_query: tool({\n description: `Internal tool to fetch data from the store's database. Write a SQL query to retrieve the information needed to answer the user's question. The results will be returned as data that you can then present to the user in natural language.`,\n inputSchema: z.object({\n reasoning: z\n .string()\n .describe(\n 'Your reasoning for why this SQL query is relevant to the user request.',\n ),\n sql: z\n .string()\n .min(1, { message: 'SQL query cannot be empty.' })\n .refine(\n (sql) =>\n sql.trim().toUpperCase().startsWith('SELECT') ||\n sql.trim().toUpperCase().startsWith('WITH'),\n {\n message: 'Only read-only SELECT or WITH queries are allowed.',\n },\n )\n .describe('The SQL query to execute against the database.'),\n }),\n execute: ({ sql }, options) => {\n const state = toState<{ adapter: Adapter }>(options);\n return state.adapter.execute(sql);\n },\n }),\n scratchpad: scratchpad_tool,\n};\n\nconst userMemoryTypes = [\n 'identity',\n 'alias',\n 'preference',\n 'context',\n 'correction',\n] as const;\n\nconst userMemorySchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('identity'),\n description: z.string().describe(\"The user's identity: role or/and name\"),\n }),\n z.object({\n type: z.literal('alias'),\n term: z.string().describe('The term the user uses'),\n meaning: z.string().describe('What the user means by this term'),\n }),\n z.object({\n type: z.literal('preference'),\n aspect: z\n .string()\n .describe('What aspect of output this preference applies to'),\n value: z.string().describe(\"The user's preference\"),\n }),\n z.object({\n type: z.literal('context'),\n description: z.string().describe('What the user is currently working on'),\n }),\n z.object({\n type: z.literal('correction'),\n subject: z.string().describe('What was misunderstood'),\n clarification: z.string().describe('The correct understanding'),\n }),\n]);\n\nexport const memoryTools = {\n remember_memory: tool({\n description:\n 'Store something about the user for future conversations. Use silently when user shares facts, preferences, vocabulary, corrections, or context.',\n inputSchema: z.object({ memory: userMemorySchema }),\n execute: async ({ memory }, options) => {\n const state = toState<{ memory: TeachablesStore; userId: string }>(\n options,\n );\n await state.memory.remember(state.userId, memory as GeneratedTeachable);\n return 'Remembered.';\n },\n }),\n forget_memory: tool({\n description:\n 'Forget a specific memory. Use when user asks to remove something.',\n inputSchema: z.object({\n id: z.string().describe('The ID of the teachable to forget'),\n }),\n execute: async ({ id }, options) => {\n const state = toState<{ memory: TeachablesStore }>(options);\n await state.memory.forget(id);\n return 'Forgotten.';\n },\n }),\n recall_memory: tool({\n description:\n 'List stored memories for the current user. Use when user asks what you remember about them or wants to see their stored preferences.',\n inputSchema: z.object({\n type: z\n .enum(userMemoryTypes)\n .optional()\n .catch(undefined)\n .describe('Optional: filter by memory type'),\n }),\n execute: async ({ type }, options) => {\n const state = toState<{ memory: TeachablesStore; userId: string }>(\n options,\n );\n const memories = await state.memory.recall(state.userId, type);\n if (memories.length === 0) {\n return type ? `No ${type} memories stored.` : 'No memories stored.';\n }\n return memories.map((m) => ({\n id: m.id,\n type: m.type,\n data: m.data,\n createdAt: m.createdAt,\n }));\n },\n }),\n update_memory: tool({\n description:\n 'Update an existing memory. Use when user wants to modify something you previously stored.',\n inputSchema: z.object({\n memory: userMemorySchema,\n id: z.string().describe('The ID of the memory to update'),\n }),\n execute: async ({ id, memory }, options) => {\n const state = toState<{ memory: TeachablesStore }>(options);\n await state.memory.update(id, memory as GeneratedTeachable);\n return 'Updated.';\n },\n }),\n};\n\n/**\n * Chain of Thought prompt for text-to-SQL.\n *\n * Research-backed approach:\n * - Keep reasoning concise to avoid error propagation (EMNLP 2023)\n * - Focus on schema linking and database operations (Struct-SQL 2025)\n * - Use intermediate representations for complex queries\n *\n * @see https://arxiv.org/abs/2305.14215\n * @see https://arxiv.org/html/2512.17053\n */\nconst chainOfThoughtPrompt = `\n## Query Reasoning Process\n\nLet's think step by step before writing SQL:\n\n1. **Schema Link**: Which tables and columns are relevant? Verify they exist in the schema.\n2. **Join Path**: If multiple tables, what relationships connect them?\n3. **Filters**: What WHERE conditions are needed?\n4. **Aggregation**: Is COUNT, SUM, AVG, GROUP BY, or HAVING required?\n5. **Output**: What columns to SELECT and any ORDER BY or LIMIT?\n6. **Verify**: Do all referenced tables and columns exist in the schema above?\n\nFor simple queries, steps 2-4 may not apply\u2014skip them.\n\nFor complex queries requiring multiple data points, decompose into sub-questions:\n- Break the question into simpler parts (Q1, Q2, ...)\n- Determine if each part needs a subquery or CTE\n- Combine the parts into the final query\n\nKeep reasoning brief. Verbose explanations cause errors.\n`;\n\n/**\n * Few-shot examples demonstrating the CoT reasoning process.\n * Uses abstract placeholders (table_a, column_x) for maximum generalization.\n */\nconst fewShotExamples = `\n## Examples\n\n### Example 1: Simple Filter\nQuestion: \"How many records in table_a have column_x equal to 'value'?\"\nReasoning:\n- Schema Link: table_a, column_x\n- Filters: column_x = 'value'\n- Aggregation: COUNT(*)\nSQL: SELECT COUNT(*) FROM table_a WHERE column_x = 'value'\n\n### Example 2: JOIN Query\nQuestion: \"Show column_y from table_b for each record in table_a where column_x is 'value'\"\nReasoning:\n- Schema Link: table_a (column_x, id), table_b (column_y, fk_a)\n- Join Path: table_a.id \u2192 table_b.fk_a\n- Filters: column_x = 'value'\n- Output: column_y from table_b\nSQL: SELECT b.column_y FROM table_a a JOIN table_b b ON b.fk_a = a.id WHERE a.column_x = 'value'\n\n### Example 3: Aggregation with GROUP BY\nQuestion: \"What is the total of column_y grouped by column_x?\"\nReasoning:\n- Schema Link: table_a (column_x, column_y)\n- Aggregation: SUM(column_y), GROUP BY column_x\n- Output: column_x, sum\nSQL: SELECT column_x, SUM(column_y) as total FROM table_a GROUP BY column_x\n\n### Example 4: Complex Aggregation\nQuestion: \"Which values of column_x have more than 10 records, sorted by count descending?\"\nReasoning:\n- Schema Link: table_a (column_x)\n- Aggregation: COUNT(*), GROUP BY column_x, HAVING > 10\n- Output: column_x, count, ORDER BY count DESC\nSQL: SELECT column_x, COUNT(*) as cnt FROM table_a GROUP BY column_x HAVING COUNT(*) > 10 ORDER BY cnt DESC\n\n### Example 5: Subquery (Decomposition)\nQuestion: \"Show records from table_a where column_y is above average\"\nReasoning:\n- Decompose:\n - Q1: What is the average of column_y?\n - Q2: Which records have column_y above that value?\n- Schema Link: table_a (column_y)\n- Filters: column_y > (result of Q1)\n- Output: all columns from matching records\n- Verify: table_a and column_y exist \u2713\nSQL: SELECT * FROM table_a WHERE column_y > (SELECT AVG(column_y) FROM table_a)\n\n### Example 6: Complex Multi-Join (Decomposition)\nQuestion: \"Find the top 3 categories by total sales amount for orders placed last month\"\nReasoning:\n- Decompose:\n - Q1: Which orders were placed last month?\n - Q2: What is the total sales per category for those orders?\n - Q3: Which 3 categories have the highest totals?\n- Schema Link: orders (order_date, id), order_items (order_id, amount, product_id), products (id, category_id), categories (id, name)\n- Join Path: orders \u2192 order_items \u2192 products \u2192 categories\n- Filters: order_date within last month\n- Aggregation: SUM(amount), GROUP BY category\n- Output: category name, total, ORDER BY total DESC, LIMIT 3\n- Verify: all tables and columns exist \u2713\nSQL: SELECT c.name, SUM(oi.amount) as total FROM orders o JOIN order_items oi ON oi.order_id = o.id JOIN products p ON p.id = oi.product_id JOIN categories c ON c.id = p.category_id WHERE o.order_date >= DATE('now', '-1 month') GROUP BY c.id, c.name ORDER BY total DESC LIMIT 3\n`;\n\n/**\n * An agent that does Table Augmented Generation for Text-to-SQL tasks.\n */\nexport const t_a_g = agent<\n { sql: string },\n {\n // FIXME: this should not be here after creating the context package\n introspection: string;\n teachings: string;\n memory?: TeachablesStore;\n userId?: string;\n }\n>({\n model: groq('openai/gpt-oss-20b'),\n tools,\n name: 'text2sql',\n prompt: (state) => {\n const hasMemory = !!state?.memory;\n\n return `\n ${state?.teachings || ''}\n ${state?.introspection || ''}\n\n ${chainOfThoughtPrompt}\n\n ${fewShotExamples}\n\n ${hasMemory ? memoryPrompt : ''}\n `;\n },\n});\n", "import {\n clarification,\n example,\n explain,\n guardrail,\n hint,\n toInstructions,\n workflow,\n} from '../teach/teachables.ts';\n\nexport default toInstructions(\n 'memory_guidelines',\n\n // Section 1: Core behavior\n guardrail({\n rule: 'Silently store user information when revealed. Respond to memory-related requests.',\n reason: 'Memory enables personalized responses across conversations',\n action:\n 'Store silently on reveal. Respond explicitly when asked about memories.',\n }),\n\n // Section 2: Workflows for memory operations\n\n workflow({\n task: 'Store user identity silently',\n triggers: [\"I'm a\", 'I work as', 'my name is', 'my role is'],\n steps: [\n 'Extract name and/or role from the statement',\n 'Call remember_memory() with type: \"identity\" and name/role fields',\n 'Do NOT announce or confirm - continue conversation naturally',\n ],\n notes:\n 'This should happen silently without disrupting the conversation flow.',\n }),\n\n workflow({\n task: 'Store user preferences and context silently',\n triggers: ['When I say', 'I prefer', \"I'm working on\"],\n steps: [\n 'Identify the memory type (alias/preference/context/correction)',\n 'Extract the relevant information',\n 'Call remember_memory() with appropriate type and fields',\n 'Do NOT announce or confirm - continue conversation naturally',\n ],\n notes:\n 'This should happen silently without disrupting the conversation flow.',\n }),\n\n workflow({\n task: 'Forget a memory',\n triggers: ['forget that', 'remove my', 'delete the', \"don't remember that\"],\n steps: [\n 'Call recall_memory() to list relevant memories',\n 'Find the memory ID that matches user request',\n 'Call forget_memory({ id }) with the found ID',\n 'Confirm to user what was forgotten',\n ],\n }),\n\n workflow({\n task: 'Update a memory',\n triggers: ['actually now I', 'I changed', 'update my', 'no longer'],\n steps: [\n 'Call recall_memory() to find the existing memory',\n 'Get the memory ID from results',\n 'Call update_memory({ id, memory }) with new data',\n 'Confirm the update to user',\n ],\n }),\n\n // Section 3: Type disambiguation\n\n explain({\n concept: 'identity vs context',\n explanation:\n 'Identity = WHO the user is (name and/or role, permanent). Context = WHAT they are working on (temporary focus).',\n therefore: 'Identity rarely changes. Context changes per project/task.',\n }),\n\n explain({\n concept: 'alias vs correction',\n explanation:\n 'Alias = user defines their own term/shorthand. Correction = user fixes a misunderstanding about existing data/schema.',\n therefore: 'Alias is vocabulary. Correction is data clarification.',\n }),\n\n explain({\n concept: 'preference memory type',\n explanation:\n 'Stores output/style/format preferences. Fields: { aspect: string, value: string }',\n therefore: 'Use for formatting, limits, display style, data scope filters',\n }),\n\n // Section 4: Clarifications for ambiguous situations\n\n clarification({\n when: 'user says something like \"X actually means Y\" but unclear if defining their term or correcting data',\n ask: 'Are you defining your own shorthand for this term, or correcting how the data/schema actually works?',\n reason:\n 'Alias is personal vocabulary. Correction is a data/schema clarification that applies universally.',\n }),\n\n clarification({\n when: 'user mentions a project or task that could be their identity or current focus',\n ask: 'Is this your ongoing identity (name/role), or a specific project you are currently working on?',\n reason:\n 'Identity is permanent. Context is temporary focus that may change.',\n }),\n\n // Section 5: Examples\n\n // Identity - role\n example({\n question: \"I'm the VP of Sales\",\n answer: 'remember_memory({ memory: { type: \"identity\", role: \"VP of Sales\" }})',\n note: 'Identity stores role',\n }),\n\n // Identity - name\n example({\n question: 'My name is Sarah',\n answer: 'remember_memory({ memory: { type: \"identity\", name: \"Sarah\" }})',\n note: 'Identity stores name',\n }),\n\n // Context\n example({\n question: \"I'm analyzing Q4 performance\",\n answer: 'remember_memory({ memory: { type: \"context\", description: \"Analyzing Q4 performance\" }})',\n note: 'Current task = context',\n }),\n\n // Alias\n example({\n question: 'When I say \"big customers\", I mean revenue > $1M',\n answer: 'remember_memory({ memory: { type: \"alias\", term: \"big customers\", meaning: \"revenue > $1M\" }})',\n note: 'User defining their vocabulary = alias',\n }),\n\n // Correction\n example({\n question:\n 'No, the status column uses 1 for active, not the string \"active\"',\n answer: 'remember_memory({ memory: { type: \"correction\", subject: \"status column values\", clarification: \"Uses 1 for active, not string\" }})',\n note: 'Correcting schema/data assumption = correction',\n }),\n\n // Preference\n example({\n question: 'Always show dates as YYYY-MM-DD',\n answer: 'remember_memory({ memory: { type: \"preference\", aspect: \"date format\", value: \"YYYY-MM-DD\" }})',\n }),\n\n // Recall\n example({\n question: 'What do you remember about me?',\n answer: 'recall_memory({})',\n note: 'List all stored memories',\n }),\n\n // Section 6: What NOT to remember\n hint('Do NOT remember one-time query details like \"show last 10 orders\"'),\n hint(\n 'Do NOT remember information already stored - use recall_memory to check first',\n ),\n hint('Do NOT remember obvious or universal facts'),\n);\n", "import { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport pLimit from 'p-limit';\n\nexport interface CheckpointOptions {\n /** Path to the checkpoint file */\n path: string;\n /** Hash to detect config changes - if changed, checkpoint is invalidated */\n configHash?: string;\n}\n\n/**\n * Codec for encoding/decoding values during checkpoint operations.\n * Use this when storing objects with methods (like Teachables) that need\n * to be serialized to plain JSON and restored with their methods.\n */\nexport interface Codec<T, TSerialized = unknown> {\n /** Convert runtime value to JSON-serializable format */\n encode: (value: T) => TSerialized;\n /** Convert stored JSON back to runtime value */\n decode: (serialized: TSerialized) => T;\n}\n\ninterface PointEntry {\n inputHash: string;\n output: unknown;\n}\n\ninterface PointData {\n committed: boolean;\n entries: PointEntry[];\n}\n\ninterface CheckpointFile {\n configHash?: string;\n points: Record<string, PointData>;\n}\n\nexport class Checkpoint {\n private points: Record<string, PointData>;\n\n private constructor(\n private path: string,\n private configHash: string | undefined,\n points: Record<string, PointData>,\n ) {\n this.points = points;\n }\n\n /**\n * Load checkpoint from file, or return empty checkpoint if none exists.\n * Handles corrupted files and config changes gracefully.\n */\n static async load(options: CheckpointOptions): Promise<Checkpoint> {\n const { path, configHash } = options;\n\n if (existsSync(path)) {\n try {\n const content = readFileSync(path, 'utf-8');\n const file: CheckpointFile = JSON.parse(content);\n\n // Check if config changed\n if (configHash && file.configHash && file.configHash !== configHash) {\n console.log('\u26A0 Config changed, starting fresh');\n return new Checkpoint(path, configHash, {});\n }\n\n const points = file.points ?? {};\n const totalEntries = Object.values(points).reduce(\n (sum, p) => sum + p.entries.length,\n 0,\n );\n console.log(`\u2713 Resuming from checkpoint (${totalEntries} entries)`);\n return new Checkpoint(path, configHash, points);\n } catch {\n console.log('\u26A0 Checkpoint corrupted, starting fresh');\n return new Checkpoint(path, configHash, {});\n }\n }\n\n console.log('Starting new checkpoint');\n return new Checkpoint(path, configHash, {});\n }\n\n /**\n * Run a single computation with checkpointing.\n * If already completed, returns cached value.\n *\n * @param key - Unique identifier for this computation\n * @param computation - Async function that produces the value\n * @param codec - Optional codec for encoding/decoding non-primitive values\n */\n async run<T>(\n key: string,\n computation: () => Promise<T>,\n codec?: Codec<T>,\n ): Promise<T> {\n const point = this.point<T>(key);\n\n // Use fixed input hash for single-value runs\n return point.through(\n 'single',\n async () => {\n const result = await computation();\n return codec ? (codec.encode(result) as T) : result;\n },\n codec,\n );\n }\n\n /**\n * Create a resumable checkpoint point for iterative operations.\n *\n * @param step - Unique identifier for this checkpoint point\n */\n point<T>(step: string): Point<T> {\n this.points[step] ??= { committed: false, entries: [] };\n return new Point<T>(this.points[step], () => this.save());\n }\n\n /**\n * Process each input with automatic checkpointing and concurrency.\n *\n * @param step - Unique identifier for this checkpoint\n * @param inputs - Items to process\n * @param process - Function to process each input\n * @param options - Optional settings like concurrency\n * @returns All outputs (use `.flat()` if outputs are arrays)\n */\n async each<I, O>(\n step: string,\n inputs: Iterable<I>,\n process: (input: I) => Promise<O>,\n options?: { concurrency?: number },\n ): Promise<O[]> {\n const point = this.point<O>(step);\n const limit = pLimit(options?.concurrency ?? 1);\n\n const inputArray = Array.from(inputs);\n await Promise.all(\n inputArray.map((input) =>\n limit(() => point.through(input, () => process(input))),\n ),\n );\n\n await point.commit();\n return point.values();\n }\n\n /**\n * Get clean output from all completed points.\n * Single-entry points return the value directly, multi-entry return arrays.\n */\n getOutput(): Record<string, unknown> {\n const output: Record<string, unknown> = {};\n for (const [key, pointData] of Object.entries(this.points)) {\n if (pointData.entries.length === 1) {\n output[key] = pointData.entries[0].output;\n } else {\n output[key] = pointData.entries.map((e) => e.output);\n }\n }\n return output;\n }\n\n /** Get the file path where checkpoint is stored */\n getPath(): string {\n return this.path;\n }\n\n private async save(): Promise<void> {\n const file: CheckpointFile = {\n configHash: this.configHash,\n points: this.points,\n };\n const content = JSON.stringify(file, null, 2);\n\n // Atomic write: write to temp file, then rename\n const tempPath = `${this.path}.tmp`;\n writeFileSync(tempPath, content);\n renameSync(tempPath, this.path);\n }\n}\n\nfunction hash(value: unknown): string {\n return createHash('md5').update(JSON.stringify(value)).digest('hex');\n}\n\n/**\n * A checkpoint point for tracking iterative operations.\n * Uses input hashing to determine if an operation was already processed.\n */\nexport class Point<T> {\n #cache: Map<string, T>;\n\n constructor(\n private data: PointData,\n private persist: () => Promise<void>,\n ) {\n this.#cache = new Map(\n data.entries.map((e) => [e.inputHash, e.output as T]),\n );\n }\n\n /**\n * Execute computation if input wasn't processed before.\n * Returns cached output if input hash exists, otherwise executes, saves, and returns.\n */\n async through<I, O>(\n input: I,\n compute: () => Promise<O>,\n codec?: Codec<O>,\n ): Promise<O> {\n const inputHash = hash(input);\n\n if (this.#cache.has(inputHash)) {\n const cached = this.#cache.get(inputHash) as O;\n return codec ? codec.decode(cached) : cached;\n }\n\n const output = await compute();\n this.data.entries.push({ inputHash, output });\n this.#cache.set(inputHash, output as T);\n await this.persist();\n return codec ? codec.decode(output) : output;\n }\n\n /** Mark this point as complete. */\n async commit(): Promise<void> {\n this.data.committed = true;\n await this.persist();\n }\n\n /** Check if this point has been committed. */\n isCommitted(): boolean {\n return this.data.committed;\n }\n\n /** Get all outputs from this point. */\n values(): T[] {\n return this.data.entries.map((e) => e.output as T);\n }\n}\n\n/**\n * Generate a hash from a config object for checkpoint invalidation.\n * If config changes, the checkpoint will be invalidated and pipeline restarts.\n */\nexport function hashConfig(config: Record<string, unknown>): string {\n return createHash('md5').update(JSON.stringify(config)).digest('hex');\n}\n", "import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport path from 'node:path';\n\nexport class FileCache {\n public path: string;\n constructor(watermark: string, extension = '.txt') {\n const hash = createHash('md5').update(watermark).digest('hex');\n this.path = path.join(tmpdir(), `text2sql-${hash}${extension}`);\n }\n\n async get() {\n if (existsSync(this.path)) {\n return readFile(this.path, 'utf-8');\n }\n return null;\n }\n\n set(content: string) {\n return writeFile(this.path, content, 'utf-8');\n }\n}\n\nexport class JsonCache<T> extends FileCache {\n constructor(watermark: string) {\n super(watermark, '.json');\n }\n\n async read(): Promise<T | null> {\n const content = await this.get();\n if (content) {\n return JSON.parse(content) as T;\n }\n return null;\n }\n\n write(data: T) {\n return this.set(JSON.stringify(data));\n }\n}\n", "import type { UIMessage } from 'ai';\n\nexport interface Message {\n id: string;\n chatId: string;\n role: string;\n createdAt: string | Date;\n content: UIMessage;\n}\n\nexport interface Chat {\n id: string;\n userId: string;\n title?: string | null;\n messages: Message[];\n}\n\nexport interface CreateChatParams {\n id: string;\n userId: string;\n title?: string;\n}\n\nexport interface UpdateChatParams {\n title?: string;\n}\n\nexport interface CreateMessageParams {\n id: string;\n chatId: string;\n role: string;\n content: UIMessage;\n createdAt?: Date;\n}\n\nexport abstract class History {\n abstract listChats(userId: string): Promise<Chat[]>;\n abstract getChat(chatId: string): Promise<Chat | null>;\n abstract createChat(chat: CreateChatParams): Promise<Chat>;\n abstract upsertChat(chat: CreateChatParams): Promise<Chat>;\n abstract deleteChat(chatId: string): Promise<void>;\n abstract updateChat(chatId: string, updates: UpdateChatParams): Promise<void>;\n abstract addMessage(message: CreateMessageParams): Promise<void>;\n abstract upsertMessage(message: CreateMessageParams): Promise<Message>;\n abstract deleteMessage(messageId: string): Promise<void>;\n}\n", "import { DatabaseSync } from 'node:sqlite';\n\nimport historyDDL from './history.sqlite.sql';\nimport {\n type Chat,\n type CreateChatParams,\n type CreateMessageParams,\n History,\n type Message,\n type UpdateChatParams,\n} from './history.ts';\n\nexport class SqliteHistory extends History {\n #db: DatabaseSync;\n\n constructor(path: string) {\n super();\n this.#db = new DatabaseSync(path);\n this.#db.exec(historyDDL);\n }\n\n async listChats(userId: string): Promise<Chat[]> {\n return this.#db\n .prepare(`SELECT * FROM chats WHERE \"userId\" = ?`)\n .all(userId) as unknown as Chat[];\n }\n\n async getChat(chatId: string): Promise<Chat | null> {\n const rows = this.#db\n .prepare(\n `SELECT\n c.id as chatId, c.\"userId\", c.title,\n m.id as messageId, m.role, m.\"createdAt\", m.content\n FROM chats c\n LEFT JOIN messages m ON m.\"chatId\" = c.id\n WHERE c.id = ?\n ORDER BY m.\"createdAt\" ASC`,\n )\n .all(chatId) as unknown as Array<{\n chatId: string;\n userId: string;\n title: string | null;\n messageId: string | null;\n role: string;\n createdAt: string;\n content: string;\n }>;\n\n if (!rows.length) return null;\n\n const firstRow = rows[0];\n const chat: Chat = {\n id: firstRow.chatId,\n userId: firstRow.userId,\n title: firstRow.title,\n messages: [],\n };\n\n for (const row of rows) {\n if (row.messageId) {\n chat.messages.push({\n id: row.messageId,\n chatId: firstRow.chatId,\n role: row.role as string,\n createdAt: row.createdAt as string,\n content: JSON.parse(row.content),\n });\n }\n }\n\n return chat;\n }\n\n async createChat(chat: CreateChatParams): Promise<Chat> {\n this.#db\n .prepare(`INSERT INTO chats (id, \"userId\", title) VALUES (?, ?, ?)`)\n .run(chat.id, chat.userId, chat.title || null);\n return chat as Chat;\n }\n\n async upsertChat(chat: CreateChatParams) {\n this.#db\n .prepare(\n `INSERT INTO chats (id, \"userId\", title) VALUES (?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET title = excluded.title, \"userId\" = excluded.\"userId\"`,\n )\n .run(chat.id, chat.userId, chat.title || null);\n return this.getChat(chat.id) as Promise<Chat>;\n }\n\n async deleteChat(chatId: string): Promise<void> {\n this.#db.prepare(`DELETE FROM chats WHERE id = ?`).run(chatId);\n }\n\n async updateChat(chatId: string, updates: UpdateChatParams): Promise<void> {\n if (updates.title !== undefined) {\n this.#db\n .prepare(`UPDATE chats SET title = ? WHERE id = ?`)\n .run(updates.title, chatId);\n }\n }\n\n async addMessage(message: CreateMessageParams): Promise<void> {\n const createdAt = message.createdAt\n ? message.createdAt.toISOString()\n : new Date().toISOString();\n this.#db\n .prepare(\n `INSERT INTO messages (id, \"chatId\", role, \"createdAt\", content) VALUES (?, ?, ?, ?, ?)`,\n )\n .run(\n message.id,\n message.chatId,\n message.role,\n createdAt,\n JSON.stringify(message.content),\n );\n }\n\n async upsertMessage(message: CreateMessageParams): Promise<Message> {\n const createdAt = message.createdAt\n ? message.createdAt.toISOString()\n : new Date().toISOString();\n this.#db\n .prepare(\n `INSERT INTO messages (id, \"chatId\", role, \"createdAt\", content) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(id) DO UPDATE SET \"chatId\" = excluded.\"chatId\", role = excluded.role, \"createdAt\" = excluded.\"createdAt\", content = excluded.content`,\n )\n .run(\n message.id,\n message.chatId,\n message.role,\n createdAt,\n JSON.stringify(message.content),\n );\n return {\n ...message,\n createdAt,\n };\n }\n\n async deleteMessage(messageId: string): Promise<void> {\n this.#db.prepare(`DELETE FROM messages WHERE id = ?`).run(messageId);\n }\n}\n", "CREATE TABLE IF NOT EXISTS \"chats\" (\n\t\"id\" VARCHAR PRIMARY KEY,\n\t\"title\" VARCHAR,\n\t\"userId\" VARCHAR\n);\n\nCREATE TABLE IF NOT EXISTS \"messages\" (\n\t\"id\" VARCHAR PRIMARY KEY,\n\t\"chatId\" VARCHAR NOT NULL REFERENCES \"chats\" (\"id\") ON DELETE CASCADE,\n\t\"createdAt\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\"role\" VARCHAR NOT NULL,\n\t\"content\" TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS \"messages_chat_id_idx\" ON \"messages\" (\"chatId\");\n\nCREATE INDEX IF NOT EXISTS \"messages_chat_id_created_at_idx\" ON \"messages\" (\"chatId\", \"createdAt\");\n", "import { SqliteHistory } from './sqlite.history.ts';\n\nexport class InMemoryHistory extends SqliteHistory {\n constructor() {\n super(':memory:');\n }\n}\n", "import { DatabaseSync } from 'node:sqlite';\nimport { v7 } from 'uuid';\n\nimport {\n type GeneratedTeachable,\n type Teachables,\n toTeachables,\n} from '../teach/teachables.ts';\nimport storeDDL from './store.sqlite.sql';\nimport { type StoredTeachable, TeachablesStore } from './store.ts';\n\ninterface TeachableRow {\n id: string;\n userId: string;\n type: string;\n data: string;\n createdAt: string;\n updatedAt: string;\n}\n\nfunction rowToStoredTeachable(row: TeachableRow): StoredTeachable {\n return {\n id: row.id,\n userId: row.userId,\n type: row.type as GeneratedTeachable['type'],\n data: JSON.parse(row.data),\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n}\n\nexport class SqliteTeachablesStore extends TeachablesStore {\n #db: DatabaseSync;\n\n constructor(path: string) {\n super();\n this.#db = new DatabaseSync(path);\n this.#db.exec(storeDDL);\n }\n\n async remember(\n userId: string,\n data: GeneratedTeachable,\n ): Promise<StoredTeachable> {\n const id = v7();\n const now = new Date().toISOString();\n\n this.#db\n .prepare(\n 'INSERT INTO teachables (id, userId, type, data, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)',\n )\n .run(id, userId, data.type, JSON.stringify(data), now, now);\n\n return (await this.get(id))!;\n }\n\n async recall(\n userId: string,\n type?: GeneratedTeachable['type'],\n ): Promise<StoredTeachable[]> {\n let rows: TeachableRow[];\n\n if (type === undefined) {\n rows = this.#db\n .prepare('SELECT * FROM teachables WHERE userId = ? ORDER BY createdAt')\n .all(userId) as unknown as TeachableRow[];\n } else {\n rows = this.#db\n .prepare(\n 'SELECT * FROM teachables WHERE userId = ? AND type = ? ORDER BY createdAt',\n )\n .all(userId, type) as unknown as TeachableRow[];\n }\n\n return rows.map(rowToStoredTeachable);\n }\n\n async get(id: string): Promise<StoredTeachable | null> {\n const row = this.#db\n .prepare('SELECT * FROM teachables WHERE id = ?')\n .get(id) as TeachableRow | undefined;\n\n if (!row) return null;\n return rowToStoredTeachable(row);\n }\n\n async update(id: string, data: GeneratedTeachable): Promise<StoredTeachable> {\n const now = new Date().toISOString();\n\n this.#db\n .prepare(\n 'UPDATE teachables SET data = ?, type = ?, updatedAt = ? WHERE id = ?',\n )\n .run(JSON.stringify(data), data.type, now, id);\n\n return (await this.get(id))!;\n }\n\n async forget(id: string): Promise<void> {\n this.#db.prepare('DELETE FROM teachables WHERE id = ?').run(id);\n }\n\n async forgetAll(userId: string): Promise<void> {\n this.#db.prepare('DELETE FROM teachables WHERE userId = ?').run(userId);\n }\n\n async toTeachables(userId: string): Promise<Teachables[]> {\n const stored = await this.recall(userId);\n return toTeachables(stored.map((s) => s.data));\n }\n}\n", "CREATE TABLE IF NOT EXISTS \"teachables\" (\n\t\"id\" VARCHAR PRIMARY KEY,\n\t\"userId\" VARCHAR,\n\t\"type\" VARCHAR NOT NULL,\n\t\"data\" TEXT NOT NULL,\n\t\"createdAt\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n\t\"updatedAt\" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE INDEX IF NOT EXISTS \"teachables_user_id_idx\" ON \"teachables\" (\"userId\");\n\nCREATE INDEX IF NOT EXISTS \"teachables_type_idx\" ON \"teachables\" (\"type\");\n\nCREATE INDEX IF NOT EXISTS \"teachables_user_type_idx\" ON \"teachables\" (\"userId\", \"type\");\n", "import type { GeneratedTeachable, Teachables } from '../teach/teachables.ts';\n\nexport interface StoredTeachable {\n id: string;\n userId: string;\n type: GeneratedTeachable['type'];\n data: GeneratedTeachable;\n createdAt: string;\n updatedAt: string;\n}\n\nexport abstract class TeachablesStore {\n /**\n * Remember a teachable for a user.\n */\n abstract remember(\n userId: string,\n data: GeneratedTeachable,\n ): Promise<StoredTeachable>;\n\n /**\n * Recall teachables for a user, optionally filtered by type.\n */\n abstract recall(\n userId: string,\n type?: GeneratedTeachable['type'],\n ): Promise<StoredTeachable[]>;\n\n /**\n * Get a specific teachable by ID.\n */\n abstract get(id: string): Promise<StoredTeachable | null>;\n\n /**\n * Update an existing teachable.\n */\n abstract update(\n id: string,\n data: GeneratedTeachable,\n ): Promise<StoredTeachable>;\n\n /**\n * Forget (remove) a specific teachable by ID.\n */\n abstract forget(id: string): Promise<void>;\n\n /**\n * Forget all teachables for a user.\n */\n abstract forgetAll(userId: string): Promise<void>;\n\n /**\n * Convert stored teachables to Teachables array for use with toInstructions().\n */\n abstract toTeachables(userId: string): Promise<Teachables[]>;\n}\n", "import { SqliteTeachablesStore } from './sqlite.store.ts';\n\nexport class InMemoryTeachablesStore extends SqliteTeachablesStore {\n constructor() {\n super(':memory:');\n }\n}\n", "import {\n InvalidToolInputError,\n NoSuchToolError,\n ToolCallRepairError,\n type UIMessage,\n generateId,\n} from 'ai';\nimport { v7 } from 'uuid';\n\nimport {\n type Agent,\n type AgentModel,\n generate,\n stream,\n user,\n} from '@deepagents/agent';\n\nimport type { Adapter, IntrospectOptions } from './adapters/adapter.ts';\nimport { biAgent } from './agents/bi.agent.ts';\nimport { chat1Agent, chat1Tools } from './agents/chat1.agent.ts';\nimport { chat2Agent, chat2Tools } from './agents/chat2.agent.ts';\nimport { chat3Agent, chat3Tools } from './agents/chat3.agent.ts';\nimport { chat4Agent, chat4Tools } from './agents/chat4.agent.ts';\nimport { developerAgent } from './agents/developer.agent.ts';\nimport { explainerAgent } from './agents/explainer.agent.ts';\nimport { toSql as agentToSql } from './agents/sql.agent.ts';\nimport {\n type RenderingTools,\n memoryTools,\n t_a_g,\n} from './agents/text2sql.agent.ts';\nimport { FileCache } from './file-cache.ts';\nimport { History } from './history/history.ts';\nimport type { TeachablesStore } from './memory/store.ts';\nimport {\n type ExtractedPair,\n type PairProducer,\n toPairs as collectPairs,\n} from './synthesis/types.ts';\nimport {\n type Teachables,\n guardrail,\n hint,\n persona,\n styleGuide,\n teachable,\n toInstructions,\n} from './teach/teachables.ts';\nimport { type TeachingsOptions, guidelines } from './teach/teachings.ts';\n\nexport interface InspectionResult {\n /** The grounding/introspection data (database schema context as XML) */\n grounding: string;\n\n /** The full instructions XML that would be sent to the agent */\n instructions: string;\n\n /** User-specific teachables that were loaded */\n userTeachables: Teachables[];\n\n /** System teachings configured */\n systemTeachings: Teachables[];\n\n /** Tool names available to the agent */\n tools: string[];\n}\n\nexport class Text2Sql {\n #config: {\n model?: AgentModel;\n adapter: Adapter;\n history: History;\n tools?: RenderingTools;\n instructions: Teachables[];\n memory?: TeachablesStore;\n introspection: FileCache;\n };\n\n constructor(config: {\n adapter: Adapter;\n history: History;\n version: string;\n tools?: RenderingTools;\n instructions?: Teachables[];\n model?: AgentModel;\n memory?: TeachablesStore;\n /**\n * Configure teachings behavior\n * @see TeachingsOptions\n */\n teachingsOptions?: TeachingsOptions;\n }) {\n this.#config = {\n adapter: config.adapter,\n history: config.history,\n instructions: [\n ...guidelines(config.teachingsOptions),\n ...(config.instructions ?? []),\n ],\n tools: config.tools ?? {},\n model: config.model,\n memory: config.memory,\n introspection: new FileCache('introspection-' + config.version),\n };\n }\n\n public async explain(sql: string) {\n const { experimental_output } = await generate(\n explainerAgent,\n [user('Explain this SQL.')],\n { sql },\n );\n return experimental_output.explanation;\n }\n\n public async toSql(input: string): Promise<string> {\n const introspection = await this.index();\n\n const result = await agentToSql({\n input,\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n model: this.#config.model,\n });\n\n return result.sql;\n }\n\n public instruct(...dataset: Teachables[]) {\n this.#config.instructions.push(...dataset);\n }\n\n public async inspect(agent: Agent) {\n const [grounding] = await Promise.all([this.index() as Promise<string>]);\n\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const allInstructions = [\n ...this.#config.instructions,\n guardrail({\n rule: 'ALWAYS use `get_sample_rows` before writing queries that filter or compare against string columns.',\n reason: 'Prevents SQL errors from wrong value formats.',\n action:\n \"Target specific columns (e.g., get_sample_rows('table', ['status', 'type'])).\",\n }),\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n\n const tools = Object.keys({\n ...agent.handoff.tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n });\n\n return {\n tools,\n prompt: agent.instructions({\n introspection: grounding,\n teachings: toInstructions('instructions', ...allInstructions),\n }),\n };\n }\n\n public async index(options?: IntrospectOptions) {\n const cached = await this.#config.introspection.get();\n if (cached) {\n return cached;\n }\n const introspection = await this.#config.adapter.introspect();\n await this.#config.introspection.set(introspection);\n return introspection;\n }\n\n /**\n * Generate training data pairs using a producer factory.\n * The factory receives the configured adapter, so users don't need to pass it manually.\n *\n * @example\n * // Generate questions for existing SQL\n * const pairs = await text2sql.toPairs(\n * (adapter) => new SqlExtractor(sqls, adapter, { validateSql: true })\n * );\n *\n * @example\n * // Extract from chat history with validation\n * const pairs = await text2sql.toPairs(\n * (adapter) => new ValidatedProducer(\n * new MessageExtractor(messages),\n * adapter\n * )\n * );\n */\n public async toPairs<T extends PairProducer>(\n factory: (adapter: Adapter) => T,\n ): Promise<ExtractedPair[]> {\n const producer = factory(this.#config.adapter);\n return collectPairs(producer);\n }\n\n // public async suggest() {\n // const [introspection, adapterInfo] = await Promise.all([\n // this.index(),\n // this.#config.adapter.introspect(),\n // ]);\n // const { experimental_output: output } = await generate(\n // suggestionsAgent,\n // [\n // user(\n // 'Suggest high-impact business questions and matching SQL queries for this database.',\n // ),\n // ],\n // {\n // },\n // );\n // return output.suggestions;\n // }\n\n public async chat(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n // Build instructions with conditional rendering hint\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const instructions = [\n ...this.#config.instructions,\n guardrail({\n rule: 'ALWAYS use `get_sample_rows` before writing queries that filter or compare against string columns.',\n reason: 'Prevents SQL errors from wrong value formats.',\n action:\n \"Target specific columns (e.g., get_sample_rows('table', ['status', 'type'])).\",\n }),\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n const originalMessage = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n const result = stream(\n t_a_g.clone({\n model: this.#config.model,\n tools: {\n ...t_a_g.handoff.tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n },\n }),\n originalMessage,\n {\n teachings: toInstructions(\n 'instructions',\n persona({\n name: 'Freya',\n role: 'You are an expert SQL query generator, answering business questions with accurate queries.',\n tone: 'Your tone should be concise and business-friendly.',\n }),\n ...instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n memory: this.#config.memory,\n userId: params.userId,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessage,\n );\n }\n\n /**\n * Chat1 - Combined tool, no peek.\n *\n * Uses a single `query_database` tool that:\n * 1. Takes a natural language question\n * 2. Internally calls toSql() to generate validated SQL\n * 3. Executes the SQL\n * 4. Returns both SQL and results\n *\n * The agent does NOT see the SQL before execution.\n */\n public async chat1(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const instructions = [\n ...this.#config.instructions,\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n\n const originalMessage = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n\n const result = stream(\n chat1Agent.clone({\n model: this.#config.model,\n tools: {\n ...chat1Tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n },\n }),\n originalMessage,\n {\n teachings: toInstructions(\n 'instructions',\n ...instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n memory: this.#config.memory,\n userId: params.userId,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessage,\n );\n }\n\n /**\n * Chat2 - Separate generate + execute tools (with peek).\n *\n * Uses two separate tools:\n * 1. `generate_sql` - Takes a question, returns validated SQL\n * 2. `execute_sql` - Takes SQL, executes it\n *\n * The agent sees the SQL before execution and can review/refine.\n */\n public async chat2(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const instructions = [\n ...this.#config.instructions,\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n\n const originalMessage = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n\n const result = stream(\n chat2Agent.clone({\n model: this.#config.model,\n tools: {\n ...chat2Tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n },\n }),\n originalMessage,\n {\n teachings: toInstructions(\n 'instructions',\n ...instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n memory: this.#config.memory,\n userId: params.userId,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessage,\n );\n }\n\n /**\n * Chat3 - Agent conversation/collaboration.\n *\n * Enables richer interaction where the SQL agent can:\n * - Surface confidence levels\n * - State assumptions\n * - Request clarification when uncertain\n */\n public async chat3(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const instructions = [\n ...this.#config.instructions,\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n\n const originalMessage = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n\n const result = stream(\n chat3Agent.clone({\n model: this.#config.model,\n tools: {\n ...chat3Tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n },\n }),\n originalMessage,\n {\n teachings: toInstructions(\n 'instructions',\n\n ...instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n memory: this.#config.memory,\n userId: params.userId,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessage,\n );\n }\n\n /**\n * Chat4 - Question decomposition approach.\n *\n * Breaks down questions into semantic components before SQL generation:\n * - entities: Key concepts mentioned\n * - filters: Filtering criteria\n * - aggregation: Type of aggregation\n * - breakdown: Semantic parts of the question\n *\n * This helps ensure all aspects of the question are addressed.\n */\n public async chat4(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n const renderToolNames = Object.keys(this.#config.tools ?? {}).filter(\n (name) => name.startsWith('render_'),\n );\n const instructions = [\n ...this.#config.instructions,\n ...(renderToolNames.length\n ? [\n hint(`Rendering tools available: ${renderToolNames.join(', ')}.`),\n styleGuide({\n prefer:\n 'Use render_* tools for trend/over time/monthly requests or chart asks',\n always:\n 'Include text insight alongside visualizations. Prefer line charts for time-based data.',\n }),\n ]\n : []),\n ];\n\n const originalMessage = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n\n const result = stream(\n chat4Agent.clone({\n model: this.#config.model,\n tools: {\n ...chat4Tools,\n ...(this.#config.memory ? memoryTools : {}),\n ...this.#config.tools,\n },\n }),\n originalMessage,\n {\n teachings: toInstructions(\n 'instructions',\n ...instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n memory: this.#config.memory,\n userId: params.userId,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessage,\n );\n }\n /**\n * Business intelligence focused chat agent.\n *\n * Creates dashboards using MDX components with embedded SQL queries.\n * The agent explores data, validates SQL, and outputs markdown with\n * JSX chart components that the frontend renders via MDX.\n *\n * @example\n * ```typescript\n * const result = await text2sql.bi(\n * [user(\"Show me a sales dashboard for last 30 days\")],\n * { chatId: 'dashboard-1', userId: 'user-1' }\n * );\n * // Result contains markdown with <BarChart sql=\"...\" />, <KPI sql=\"...\" />, etc.\n * ```\n */\n public async bi(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n const originalMessages = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n\n // Pass configured instructions as teachings for the BI agent\n const result = stream(\n biAgent.clone({\n model: this.#config.model,\n }),\n originalMessages,\n {\n teachings: toInstructions(\n 'instructions',\n ...this.#config.instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessages,\n );\n }\n\n /**\n * Developer-focused conversational interface for SQL generation.\n *\n * Provides power-user tools for query building without execution:\n * - generate_sql: Convert natural language to validated SQL\n * - validate_sql: Check SQL syntax\n * - explain_sql: Get plain-English explanations\n * - show_schema: Explore database schema on demand\n *\n * @example\n * ```typescript\n * const result = await text2sql.developer(\n * [user(\"Generate a query to find top customers by revenue\")],\n * { chatId: 'dev-session-1', userId: 'dev-1' }\n * );\n * // Agent responds with SQL, can validate, explain, or refine iteratively\n * ```\n */\n public async developer(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, userTeachables] = await Promise.all([\n this.index({ onProgress: console.log }),\n this.#config.memory\n ? this.#config.memory.toTeachables(params.userId)\n : [],\n ]);\n const chat = await this.#config.history.upsertChat({\n id: params.chatId,\n userId: params.userId,\n title: 'Chat ' + params.chatId,\n });\n\n const originalMessages = [\n ...chat.messages.map((it) => it.content),\n ...messages,\n ];\n\n const result = stream(\n developerAgent.clone({\n model: this.#config.model,\n }),\n originalMessages,\n {\n teachings: toInstructions(\n 'instructions',\n ...this.#config.instructions,\n teachable('user_profile', ...userTeachables),\n ),\n adapter: this.#config.adapter,\n introspection,\n instructions: this.#config.instructions,\n },\n );\n\n return this.#createUIMessageStream(\n result,\n messages,\n params,\n originalMessages,\n );\n }\n\n /**\n * Helper to create UI message stream with common error handling and persistence.\n */\n #createUIMessageStream(\n result: ReturnType<typeof stream>,\n messages: UIMessage[],\n params: { chatId: string; userId: string },\n originalMessages: UIMessage[],\n ) {\n return result.toUIMessageStream({\n onError: (error) => {\n if (NoSuchToolError.isInstance(error)) {\n return 'The model tried to call an unknown tool.';\n } else if (InvalidToolInputError.isInstance(error)) {\n return 'The model called a tool with invalid arguments.';\n } else if (ToolCallRepairError.isInstance(error)) {\n return 'The model tried to call a tool with invalid arguments, but it was repaired.';\n } else {\n return 'An unknown error occurred.';\n }\n },\n sendStart: true,\n sendFinish: true,\n sendReasoning: true,\n sendSources: true,\n originalMessages: originalMessages,\n generateMessageId: generateId,\n onFinish: async ({ responseMessage, isContinuation }) => {\n const userMessage = messages.at(-1);\n if (!isContinuation && userMessage) {\n console.log(\n 'Saving user message to history:',\n JSON.stringify(userMessage),\n );\n await this.#config.history.addMessage({\n id: v7(),\n chatId: params.chatId,\n role: userMessage.role,\n content: userMessage,\n });\n }\n\n await this.#config.history.addMessage({\n id: v7(),\n chatId: params.chatId,\n role: responseMessage.role,\n content: responseMessage,\n });\n },\n });\n }\n}\n", "/**\n * BI Agent - Business Intelligence dashboard generator\n *\n * This agent creates dashboard specifications using HTML custom elements.\n * It outputs markdown with embedded kebab-case HTML tags that the\n * frontend parses. Charts contain SQL queries that the frontend\n * executes independently.\n *\n * Workflow:\n * 1. Analyze request and plan metrics\n * 2. Output dashboard with row/col/grid layout and chart components\n */\nimport { groq } from '@ai-sdk/groq';\nimport { tool } from 'ai';\nimport dedent from 'dedent';\nimport z from 'zod';\n\nimport { agent, toState } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\n\n/**\n * State passed to the BI agent\n */\nexport type BiAgentState = {\n /** Database adapter for query execution and validation */\n adapter: Adapter;\n /** Schema introspection XML */\n introspection: string;\n /** Combined teachings/instructions string */\n teachings: string;\n};\n\n/**\n * Tools available to the BI agent for SQL validation and reasoning\n */\nconst tools = {\n /**\n * Validate SQL query syntax without executing.\n * Use this to verify queries are correct before embedding in dashboard components.\n */\n validate_query: tool({\n description: dedent`\n Validate SQL query syntax before embedding in dashboard components.\n Use this to verify your queries are syntactically correct and reference valid tables/columns.\n\n This tool does NOT execute the query or return data.\n Only SELECT or WITH statements are allowed.\n `,\n inputSchema: z.object({\n reasoning: z\n .string()\n .describe(\n 'Why this query helps understand the data for dashboard design.',\n ),\n sql: z\n .string()\n .min(1, { message: 'SQL query cannot be empty.' })\n .refine(\n (sql) =>\n sql.trim().toUpperCase().startsWith('SELECT') ||\n sql.trim().toUpperCase().startsWith('WITH'),\n {\n message: 'Only read-only SELECT or WITH queries are allowed.',\n },\n )\n .describe('The SQL query to validate.'),\n }),\n execute: async ({ sql }, options) => {\n const state = toState<BiAgentState>(options);\n const result = await state.adapter.validate(sql);\n if (typeof result === 'string') {\n return { valid: false, error: result };\n }\n return { valid: true };\n },\n }),\n\n /**\n * Record insights and reasoning during schema analysis and dashboard design.\n */\n scratchpad: scratchpad_tool,\n};\n\n/**\n * HTML component documentation for the agent prompt\n */\nconst COMPONENTS_DOC = dedent`\n ## Available Components\n\n You output markdown with embedded HTML custom elements. Use kebab-case tags with closing tags.\n\n ### Chart Components\n\n #### Area Charts\n | Component | Required Props | Optional Props | Use Case |\n |-----------|----------------|----------------|----------|\n | \\`<area-chart>\\` | \\`title\\`, \\`sql\\` | \\`x-key\\`, \\`y-key\\`, \\`variant\\` | Cumulative values, trends with volume |\n\n **Variants** (use \\`variant\\` prop):\n - \\`default\\` - Basic area with smooth curves\n - \\`linear\\` - Sharp-edged lines showing precise changes\n - \\`step\\` - Step-based segments for discrete data\n - \\`stacked\\` - Multiple series stacked on top of each other\n - \\`stacked-expand\\` - Normalized to 100% showing percentage contribution\n - \\`gradient\\` - Filled with gradient for visual depth\n\n #### Bar Charts\n | Component | Required Props | Optional Props | Use Case |\n |-----------|----------------|----------------|----------|\n | \\`<bar-chart>\\` | \\`title\\`, \\`sql\\` | \\`x-key\\`, \\`y-key\\`, \\`variant\\`, \\`orientation\\` | Categorical comparisons, grouped data |\n\n **Variants** (use \\`variant\\` prop):\n - \\`default\\` - Basic vertical bars\n - \\`multiple\\` - Multiple series side by side\n - \\`stacked\\` - Multiple series stacked\n - \\`labeled\\` - With value labels on bars\n - \\`negative\\` - Supports positive/negative values with conditional coloring\n - \\`mixed\\` - Different colors per category\n\n **Orientation** (use \\`orientation\\` prop):\n - \\`vertical\\` (default) - Vertical bars\n - \\`horizontal\\` - Horizontal bars (good for long category names)\n\n #### Line Charts\n | Component | Required Props | Optional Props | Use Case |\n |-----------|----------------|----------------|----------|\n | \\`<line-chart>\\` | \\`title\\`, \\`sql\\` | \\`x-key\\`, \\`y-key\\`, \\`variant\\` | Trends over time, continuous data |\n\n **Variants** (use \\`variant\\` prop):\n - \\`default\\` - Smooth curved lines\n - \\`linear\\` - Straight lines between points\n - \\`step\\` - Step-based transitions\n - \\`dots\\` - Lines with visible data point markers\n - \\`multiple\\` - Multiple series for comparisons (A/B testing, etc.)\n - \\`interactive\\` - With metric switching capability\n - \\`labeled\\` - With value labels at each point\n\n #### Pie & Donut Charts\n | Component | Required Props | Optional Props | Use Case |\n |-----------|----------------|----------------|----------|\n | \\`<pie-chart>\\` | \\`title\\`, \\`sql\\` | \\`label-key\\`, \\`value-key\\`, \\`variant\\` | Part-to-whole relationships, distributions |\n | \\`<donut-chart>\\` | \\`title\\`, \\`sql\\` | \\`label-key\\`, \\`value-key\\`, \\`variant\\` | Same as pie but with center space for text/KPI |\n\n **Variants** (use \\`variant\\` prop):\n - \\`default\\` - Basic pie/donut\n - \\`labeled\\` - With labels on segments\n - \\`legend\\` - With external legend\n - \\`interactive\\` - With hover highlighting and selection\n - \\`stacked\\` - Multiple concentric rings for comparison\n\n #### Radar Charts\n | Component | Required Props | Optional Props | Use Case |\n |-----------|----------------|----------------|----------|\n | \\`<radar-chart>\\` | \\`title\\`, \\`sql\\` | \\`label-key\\`, \\`value-key\\`, \\`variant\\` | Multi-dimensional comparisons, skill assessments |\n\n **Variants** (use \\`variant\\` prop):\n - \\`default\\` - Basic radar with polygon grid\n - \\`dots\\` - With visible data point markers\n - \\`filled\\` - With filled area\n - \\`multiple\\` - Multiple series overlapping\n - \\`circle\\` - Circular grid instead of polygon\n - \\`legend\\` - With integrated legend\n\n #### Radial Charts\n | Component | Required Props | Optional Props | Use Case |\n |-----------|----------------|----------------|----------|\n | \\`<radial-chart>\\` | \\`title\\`, \\`sql\\` | \\`value-key\\`, \\`variant\\` | Progress indicators, gauges, circular metrics |\n\n **Variants** (use \\`variant\\` prop):\n - \\`default\\` - Basic radial bars from center outward\n - \\`text\\` - With centered value/caption text\n - \\`shape\\` - Gauge-style arc (not full circle)\n - \\`stacked\\` - Concentric arcs for multiple metrics\n - \\`grid\\` - With background grid rings\n\n #### KPI Component\n | Component | Required Props | Optional Props | Use Case |\n |-----------|----------------|----------------|----------|\n | \\`<kpi>\\` | \\`title\\`, \\`sql\\` | \\`variant\\`, \\`format\\`, \\`trend-sql\\`, \\`target\\`, \\`icon\\`, \\`description\\`, \\`color\\` | Rich metric displays with trends, progress, sparklines |\n\n **Variants** (use \\`variant\\` prop):\n - \\`default\\` - Simple value card\n - \\`trend\\` - Value with change indicator (\u219112.5% or \u21933.2%)\n - \\`comparison\\` - Value with previous period value shown\n - \\`progress\\` - Value with horizontal progress bar toward target\n - \\`ring\\` - Value with circular progress gauge toward target\n - \\`sparkline\\` - Value with mini area chart showing recent trend\n\n **Props Reference**:\n - \\`title\\` (required) - Display label\n - \\`sql\\` (required) - Query returning \\`{ value: number }\\`\n - \\`variant\\` - Display style (see above)\n - \\`format\\` - Value format: \\`currency\\`, \\`percent\\`, \\`number\\`, \\`compact\\`, \\`duration\\`\n - \\`trend-sql\\` - Query for trend data:\n - For \\`trend\\`/\\`comparison\\`: returns \\`{ change: number }\\` or \\`{ previous: number }\\`\n - For \\`sparkline\\`: returns time-series \\`[{ date, value }]\\`\n - \\`target\\` - Target value for \\`progress\\`/\\`ring\\` variants\n - \\`icon\\` - Icon identifier: \\`dollar\\`, \\`users\\`, \\`cart\\`, \\`chart\\`, \\`percent\\`, \\`clock\\`\n - \\`description\\` - Subtitle/context text\n - \\`color\\` - Accent color: \\`positive\\` (green), \\`negative\\` (red), \\`neutral\\`, \\`primary\\`\n\n #### Data Table\n | Component | Required Props | Optional Props | Use Case |\n |-----------|----------------|----------------|----------|\n | \\`<data-table>\\` | \\`title\\`, \\`sql\\` | \\`columns\\` | Detailed data, lists, rankings |\n\n ### Layout Components\n | Component | Props | Description |\n |-----------|-------|-------------|\n | \\`<row>\\` | \\`gap?\\` | Horizontal flex container (small, medium, or large) |\n | \\`<column>\\` | \\`span\\` (1-12) | Column within row, 12-column grid |\n | \\`<grid>\\` | \\`cols\\`, \\`gap?\\` | CSS Grid container |\n\n ### Chart Selection Guide\n - **Time series / Trends with volume**: Use \\`<area-chart>\\` (shows magnitude over time)\n - **Time series / Precise trends**: Use \\`<line-chart>\\` (clean trend lines)\n - **Categories / Comparisons**: Use \\`<bar-chart>\\`\n - **Part-to-whole / Proportions**: Use \\`<pie-chart>\\` or \\`<donut-chart>\\`\n - **Multi-dimensional comparisons**: Use \\`<radar-chart>\\` (e.g., comparing skills, features)\n - **Progress / Gauges**: Use \\`<radial-chart>\\` (circular progress indicators)\n - **Detailed data / Rankings**: Use \\`<data-table>\\`\n - **Single metrics**: Use \\`<kpi>\\` with appropriate variant:\n - Simple value \u2192 \\`default\\`\n - Value with change indicator \u2192 \\`trend\\`\n - Value vs previous period \u2192 \\`comparison\\`\n - Value toward goal \u2192 \\`progress\\` or \\`ring\\`\n - Value with recent history \u2192 \\`sparkline\\`\n\n ### Example Output\n \\`\\`\\`markdown\n ## Sales Dashboard\n\n <row>\n <column span=\"3\">\n <kpi\n title=\"Total Revenue\"\n sql=\"SELECT SUM(amount) as value FROM orders\"\n trend-sql=\"SELECT ((SUM(CASE WHEN created_at >= NOW() - INTERVAL '30 days' THEN amount END) - SUM(CASE WHEN created_at >= NOW() - INTERVAL '60 days' AND created_at < NOW() - INTERVAL '30 days' THEN amount END)) / NULLIF(SUM(CASE WHEN created_at >= NOW() - INTERVAL '60 days' AND created_at < NOW() - INTERVAL '30 days' THEN amount END), 0) * 100) as change FROM orders\"\n variant=\"trend\"\n format=\"currency\"\n icon=\"dollar\">\n </kpi>\n </column>\n <column span=\"3\">\n <kpi\n title=\"Orders Today\"\n sql=\"SELECT COUNT(*) as value FROM orders WHERE DATE(created_at) = CURRENT_DATE\"\n trend-sql=\"SELECT DATE(created_at) as date, COUNT(*) as value FROM orders WHERE created_at >= NOW() - INTERVAL '7 days' GROUP BY 1 ORDER BY 1\"\n variant=\"sparkline\"\n icon=\"cart\">\n </kpi>\n </column>\n <column span=\"3\">\n <kpi\n title=\"Sales Target\"\n sql=\"SELECT SUM(amount) as value FROM orders WHERE EXTRACT(QUARTER FROM created_at) = EXTRACT(QUARTER FROM NOW())\"\n target=\"100000\"\n variant=\"progress\"\n format=\"currency\"\n description=\"Q4 2024 Goal\">\n </kpi>\n </column>\n <column span=\"3\">\n <kpi\n title=\"Conversion Rate\"\n sql=\"SELECT (COUNT(DISTINCT buyer_id)::float / COUNT(DISTINCT visitor_id) * 100) as value FROM sessions\"\n variant=\"ring\"\n target=\"100\"\n format=\"percent\"\n color=\"primary\">\n </kpi>\n </column>\n </row>\n\n <row>\n <column span=\"8\">\n <area-chart\n title=\"Revenue Over Time\"\n sql=\"SELECT DATE_TRUNC('month', created_at) as month, SUM(amount) as revenue FROM orders GROUP BY 1 ORDER BY 1\"\n x-key=\"month\"\n y-key=\"revenue\"\n variant=\"gradient\">\n </area-chart>\n </column>\n <column span=\"4\">\n <donut-chart\n title=\"Revenue by Category\"\n sql=\"SELECT category, SUM(amount) as revenue FROM orders GROUP BY category\"\n label-key=\"category\"\n value-key=\"revenue\"\n variant=\"interactive\">\n </donut-chart>\n </column>\n </row>\n\n <row>\n <column span=\"6\">\n <bar-chart\n title=\"Monthly Comparison\"\n sql=\"SELECT DATE_TRUNC('month', created_at) as month, SUM(CASE WHEN EXTRACT(YEAR FROM created_at) = 2024 THEN amount END) as this_year, SUM(CASE WHEN EXTRACT(YEAR FROM created_at) = 2023 THEN amount END) as last_year FROM orders GROUP BY 1\"\n variant=\"multiple\"\n x-key=\"month\">\n </bar-chart>\n </column>\n <column span=\"6\">\n <radar-chart\n title=\"Product Performance\"\n sql=\"SELECT metric, score FROM product_metrics WHERE product_id = 1\"\n label-key=\"metric\"\n value-key=\"score\"\n variant=\"filled\">\n </radar-chart>\n </column>\n </row>\n\n <data-table\n title=\"Top 10 Products\"\n sql=\"SELECT name, SUM(quantity) as sold, SUM(amount) as revenue FROM order_items GROUP BY name ORDER BY revenue DESC LIMIT 10\">\n </data-table>\n \\`\\`\\`\n`;\n\nexport const biAgent = agent<never, BiAgentState>({\n model: groq('gpt-oss-20b'),\n tools,\n name: 'bi_agent',\n prompt: (state) => {\n return dedent`\n You are an expert BI analyst that creates dashboard specifications using HTML custom elements.\n\n ${COMPONENTS_DOC}\n\n ## Your Workflow\n\n 1. **PLAN**: Analyze the request and schema to determine what metrics/visualizations to create\n 2. **VALIDATE**: Use \\`validate_query\\` to verify SQL syntax is correct before embedding\n 3. **OUTPUT**: Generate the dashboard using layout and chart components\n\n ## Critical Rules\n\n - **Design from schema**: Use the provided schema introspection to understand available tables, columns, and relationships\n - **Validate all queries**: Use \\`validate_query\\` to ensure SQL is syntactically correct before embedding in components\n - **Use kebab-case HTML tags** with closing tags (e.g., \\`<bar-chart></bar-chart>\\`)\n - Use \\`scratchpad\\` to record schema analysis insights and design decisions\n - Choose chart types based on column types (dates \u2192 line/area, categories \u2192 bar/pie, numbers \u2192 KPI)\n - Use layout components (row, column, grid) to organize the dashboard\n - Include a text introduction explaining what the dashboard shows\n\n ## SQL Rules\n\n - Only SELECT or WITH statements\n - Use proper date/time functions for the database\n - Include appropriate GROUP BY, ORDER BY clauses\n - Use aliases for calculated columns\n\n ${state?.teachings || ''}\n ${state?.introspection || ''}\n `;\n },\n});\n", "/**\n * Chat1 Agent - Combined Tool, No Peek\n *\n * This variant uses a single `query_database` tool that:\n * 1. Takes a natural language question\n * 2. Internally calls toSql() to generate validated SQL\n * 3. Executes the SQL\n * 4. Returns both the SQL and results\n *\n * The agent does NOT see the SQL before execution - it's generated and executed in one step.\n */\nimport { groq } from '@ai-sdk/groq';\nimport { tool } from 'ai';\nimport z from 'zod';\n\nimport { agent, toState } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport type { TeachablesStore } from '../memory/store.ts';\nimport type { Teachables } from '../teach/teachables.ts';\nimport { type ToSqlOptions, toSql } from './sql.agent.ts';\n\nexport type Chat1State = {\n /** Database adapter for query execution */\n adapter: Adapter;\n /** Schema introspection XML */\n introspection: string;\n /** Teachings/instructions for SQL generation */\n instructions: Teachables[];\n /** Combined teachings string for the agent prompt */\n teachings: string;\n /** Optional memory store for user teachables */\n memory?: TeachablesStore;\n /** User ID for memory operations */\n userId?: string;\n};\n\n/**\n * Result returned by the query_database tool\n */\nexport interface QueryDatabaseResult {\n success: boolean;\n /** The generated SQL query */\n sql?: string;\n /** Query results as array of rows */\n data?: unknown[];\n /** Error message if generation or execution failed */\n error?: string;\n /** Number of attempts made during SQL generation */\n attempts?: number;\n}\n\nconst tools = {\n query_database: tool({\n description: `Query the database to answer a question. Provide your question in natural language and this tool will:\n1. Generate the appropriate SQL query\n2. Validate the SQL syntax\n3. Execute the query\n4. Return the results\n\nUse this tool when you need to retrieve data to answer the user's question.`,\n inputSchema: z.object({\n question: z\n .string()\n .min(1)\n .describe(\n 'The question to answer, expressed in natural language. Be specific about what data you need.',\n ),\n reasoning: z\n .string()\n .optional()\n .describe(\n 'Your reasoning for why this query is needed to answer the user.',\n ),\n }),\n execute: async ({ question }, options): Promise<QueryDatabaseResult> => {\n const state = toState<Chat1State>(options);\n\n try {\n // Generate SQL using the dedicated toSql function with validation and retry\n const sqlResult = await toSql({\n input: question,\n adapter: state.adapter,\n introspection: state.introspection,\n instructions: state.instructions,\n });\n\n // If SQL generation failed after all retries\n if (!sqlResult.sql) {\n return {\n success: false,\n error: sqlResult.errors?.join('; ') || 'Failed to generate SQL',\n };\n }\n\n // Execute the validated SQL\n const data = await state.adapter.execute(sqlResult.sql);\n\n return {\n success: true,\n sql: sqlResult.sql,\n data,\n };\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n },\n }),\n\n scratchpad: scratchpad_tool,\n};\n\n/**\n * Chat1 Agent - Table Augmented Generation with combined query tool.\n *\n * This agent receives user questions and uses the query_database tool\n * to fetch data. The SQL generation is delegated to the specialized\n * sqlQueryAgent via the toSql() function.\n */\nexport const chat1Agent = agent<never, Chat1State>({\n name: 'chat1-combined',\n model: groq('openai/gpt-oss-20b'),\n tools,\n prompt: (state) => {\n return `\n${state?.teachings || ''}\n${state?.introspection || ''}\n`;\n },\n});\n\nexport { tools as chat1Tools };\n", "/**\n * Chat2 Agent - Separate Generate + Execute Tools (With Peek)\n *\n * This variant uses two separate tools:\n * 1. `generate_sql` - Takes a question, returns validated SQL (agent can inspect it)\n * 2. `execute_sql` - Takes SQL, executes it, returns results\n *\n * The agent sees the SQL before execution and can:\n * - Review the generated SQL\n * - Explain the approach to the user\n * - Decide to refine the question and regenerate\n * - Choose not to execute if something looks wrong\n */\nimport { groq } from '@ai-sdk/groq';\nimport { tool } from 'ai';\nimport z from 'zod';\n\nimport { agent, toState } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport type { TeachablesStore } from '../memory/store.ts';\nimport type { Teachables } from '../teach/teachables.ts';\nimport { toSql } from './sql.agent.ts';\n\nexport type Chat2State = {\n /** Database adapter for query execution */\n adapter: Adapter;\n /** Schema introspection XML */\n introspection: string;\n /** Teachings/instructions for SQL generation */\n instructions: Teachables[];\n /** Combined teachings string for the agent prompt */\n teachings: string;\n /** Optional memory store for user teachables */\n memory?: TeachablesStore;\n /** User ID for memory operations */\n userId?: string;\n};\n\n/**\n * Result returned by the generate_sql tool\n */\nexport interface GenerateSqlToolResult {\n success: boolean;\n /** The generated and validated SQL query */\n sql?: string;\n /** Error message if generation failed */\n error?: string;\n /** Number of attempts made during SQL generation */\n attempts?: number;\n /** Validation errors encountered during generation */\n validationErrors?: string[];\n}\n\n/**\n * Result returned by the execute_sql tool\n */\nexport interface ExecuteSqlToolResult {\n success: boolean;\n /** Query results as array of rows */\n data?: unknown[];\n /** Error message if execution failed */\n error?: string;\n /** Row count of results */\n rowCount?: number;\n}\n\nconst tools = {\n generate_sql: tool({\n description: `Generate a SQL query from a natural language question. This tool will:\n1. Translate your question into SQL\n2. Validate the SQL syntax\n3. Retry with corrections if validation fails\n4. Return the validated SQL for your review\n\nUse this BEFORE execute_sql to see what query will be run. You can then:\n- Explain the approach to the user\n- Decide if the SQL looks correct\n- Refine your question and regenerate if needed`,\n inputSchema: z.object({\n question: z\n .string()\n .min(1)\n .describe(\n 'The question to translate into SQL. Be specific about what data you need.',\n ),\n reasoning: z\n .string()\n .optional()\n .describe('Your reasoning for why this data is needed.'),\n }),\n execute: async ({ question }, options): Promise<GenerateSqlToolResult> => {\n const state = toState<Chat2State>(options);\n\n try {\n const sqlResult = await toSql({\n input: question,\n adapter: state.adapter,\n introspection: state.introspection,\n instructions: state.instructions,\n });\n\n if (!sqlResult.sql) {\n return {\n success: false,\n error: sqlResult.errors?.join('; ') || 'Failed to generate SQL',\n validationErrors: sqlResult.errors,\n };\n }\n\n return {\n success: true,\n sql: sqlResult.sql,\n validationErrors: sqlResult.errors,\n };\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n },\n }),\n\n execute_sql: tool({\n description: `Execute a SQL query and return the results. Use this AFTER generate_sql to run the query.\n\nOnly SELECT and WITH (CTE) queries are allowed - no data modification.`,\n inputSchema: z.object({\n sql: z\n .string()\n .min(1)\n .refine(\n (sql) =>\n sql.trim().toUpperCase().startsWith('SELECT') ||\n sql.trim().toUpperCase().startsWith('WITH'),\n {\n message: 'Only read-only SELECT or WITH queries are allowed.',\n },\n )\n .describe('The SQL query to execute (must be SELECT or WITH).'),\n reasoning: z\n .string()\n .optional()\n .describe('Brief explanation of what this query retrieves.'),\n }),\n execute: async ({ sql }, options): Promise<ExecuteSqlToolResult> => {\n const state = toState<Chat2State>(options);\n\n try {\n const data = await state.adapter.execute(sql);\n\n return {\n success: true,\n data,\n rowCount: Array.isArray(data) ? data.length : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof Error ? error.message : 'Query execution failed',\n };\n }\n },\n }),\n\n scratchpad: scratchpad_tool,\n};\n\n/**\n * Chat2 Agent - Table Augmented Generation with peek support.\n *\n * This agent uses separate generate_sql and execute_sql tools,\n * allowing it to review the SQL before execution. This enables:\n * - Transparency: Agent knows what SQL will be run\n * - Control: Agent can refine before executing\n * - Explanation: Agent can describe its approach to the user\n */\nexport const chat2Agent = agent<never, Chat2State>({\n name: 'chat2-with-peek',\n model: groq('openai/gpt-oss-20b'),\n tools,\n prompt: (state) => {\n return `\n${state?.teachings || ''}\n${state?.introspection || ''}\n\nWhen answering questions that require database queries:\n1. First use generate_sql to create the SQL query\n2. Review the generated SQL to ensure it matches the user's intent\n3. Use execute_sql to run the query\n4. Present the results to the user\n\nIf the generated SQL doesn't look right, you can refine your question and regenerate.\n`;\n },\n});\n\nexport { tools as chat2Tools };\n", "/**\n * Chat3 Agent - Agent Conversation/Collaboration\n *\n * This variant enables richer interaction between the conversation agent\n * and the SQL generation agent. The SQL agent can:\n * 1. Surface its confidence level\n * 2. State assumptions it's making\n * 3. Request clarification when uncertain\n *\n * The conversation agent can then:\n * - Answer clarifications from its context\n * - Ask the user for clarification\n * - Accept or refine the SQL agent's approach\n */\nimport { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, tool, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { agent, generate, toState, user } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport type { TeachablesStore } from '../memory/store.ts';\nimport {\n type Teachables,\n persona,\n toInstructions,\n} from '../teach/teachables.ts';\n\nexport type Chat3State = {\n /** Database adapter for query execution */\n adapter: Adapter;\n /** Schema introspection XML */\n introspection: string;\n /** Teachings/instructions for SQL generation */\n instructions: Teachables[];\n /** Combined teachings string for the agent prompt */\n teachings: string;\n /** Optional memory store for user teachables */\n memory?: TeachablesStore;\n /** User ID for memory operations */\n userId?: string;\n};\n\n/**\n * Output schema for the collaborative SQL agent\n */\nconst collaborativeSqlOutputSchema = z.discriminatedUnion('status', [\n z.object({\n status: z.literal('success'),\n sql: z.string().describe('The generated SQL query'),\n confidence: z\n .enum(['high', 'medium', 'low'])\n .describe('Confidence level in this SQL being correct'),\n assumptions: z\n .array(z.string())\n .optional()\n .describe('Assumptions made during SQL generation'),\n reasoning: z\n .string()\n .optional()\n .describe('Brief explanation of the query approach'),\n }),\n z.object({\n status: z.literal('clarification_needed'),\n question: z.string().describe('Question to clarify the request'),\n context: z.string().optional().describe('Why this clarification is needed'),\n options: z\n .array(z.string())\n .optional()\n .describe('Possible options if applicable'),\n }),\n z.object({\n status: z.literal('unanswerable'),\n reason: z.string().describe('Why this question cannot be answered'),\n suggestions: z\n .array(z.string())\n .optional()\n .describe('Alternative questions that could be answered'),\n }),\n]);\n\ntype CollaborativeSqlOutput = z.infer<typeof collaborativeSqlOutputSchema>;\n\n/**\n * Internal agent for collaborative SQL generation.\n * This agent can ask for clarification instead of guessing.\n */\nconst collaborativeSqlAgent = agent<CollaborativeSqlOutput, Chat3State>({\n name: 'collaborative-sql',\n model: groq('openai/gpt-oss-20b'),\n output: collaborativeSqlOutputSchema,\n prompt: (state) => {\n return `\n${toInstructions(\n 'instructions',\n persona({\n name: 'SQLCollab',\n role: 'You are an expert SQL query generator that collaborates with the user to ensure accuracy.',\n }),\n ...(state?.instructions || []),\n)}\n${state?.introspection || ''}\n\nIMPORTANT: You have three response options:\n\n1. SUCCESS - When you can confidently generate SQL:\n - Provide the SQL query\n - Rate your confidence (high/medium/low)\n - List any assumptions you made\n\n2. CLARIFICATION_NEEDED - When the question is ambiguous:\n - Ask a specific clarifying question\n - Explain why clarification is needed\n - Provide options if applicable\n\n3. UNANSWERABLE - When the question cannot be answered with available data:\n - Explain why\n - Suggest alternative questions that could be answered\n\nPrefer asking for clarification over making low-confidence guesses.\n`;\n },\n});\n\n/**\n * Result from the collaborative query tool\n */\nexport interface CollaborativeQueryResult {\n /** Whether a final SQL was produced */\n success: boolean;\n /** The generated SQL (if success) */\n sql?: string;\n /** Query results (if executed) */\n data?: unknown[];\n /** Confidence level of the SQL */\n confidence?: 'high' | 'medium' | 'low';\n /** Assumptions made during generation */\n assumptions?: string[];\n /** Clarification question (if needed) */\n clarificationNeeded?: string;\n /** Context for clarification */\n clarificationContext?: string;\n /** Options for clarification */\n clarificationOptions?: string[];\n /** Reason if unanswerable */\n unanswerableReason?: string;\n /** Suggested alternatives if unanswerable */\n suggestions?: string[];\n /** Error message if something failed */\n error?: string;\n}\n\nconst tools = {\n consult_sql_agent: tool({\n description: `Consult the SQL specialist agent to generate a query. The SQL agent may:\n- Return a SQL query with confidence level and assumptions\n- Ask for clarification if the question is ambiguous\n- Indicate if the question cannot be answered with available data\n\nBased on the response:\n- If clarification is needed, you can provide context or ask the user\n- If assumptions were made, verify them with the user for important queries\n- If unanswerable, relay the suggestions to the user`,\n inputSchema: z.object({\n question: z\n .string()\n .min(1)\n .describe('The question to translate into SQL.'),\n context: z\n .string()\n .optional()\n .describe('Additional context from the conversation that might help.'),\n previousClarification: z\n .string()\n .optional()\n .describe(\n 'Answer to a previous clarification question from the SQL agent.',\n ),\n }),\n execute: async (\n { question, context, previousClarification },\n options,\n ): Promise<CollaborativeQueryResult> => {\n const state = toState<Chat3State>(options);\n\n try {\n // Build the message for the SQL agent\n let fullQuestion = question;\n if (context) {\n fullQuestion = `${question}\\n\\nAdditional context: ${context}`;\n }\n if (previousClarification) {\n fullQuestion = `${fullQuestion}\\n\\nClarification provided: ${previousClarification}`;\n }\n\n const agentInstance = collaborativeSqlAgent.clone({\n model: wrapLanguageModel({\n model: collaborativeSqlAgent.model,\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.1 },\n }),\n }),\n });\n\n const { experimental_output: output } = await generate(\n agentInstance,\n [user(fullQuestion)],\n state,\n );\n\n // Handle the three response types\n if (output.status === 'success') {\n // Validate the SQL\n const validationError = await state.adapter.validate(output.sql);\n if (validationError) {\n return {\n success: false,\n error: `SQL validation failed: ${validationError}`,\n };\n }\n\n // Execute the SQL\n const data = await state.adapter.execute(output.sql);\n\n return {\n success: true,\n sql: output.sql,\n data,\n confidence: output.confidence,\n assumptions: output.assumptions,\n };\n }\n\n if (output.status === 'clarification_needed') {\n return {\n success: false,\n clarificationNeeded: output.question,\n clarificationContext: output.context,\n clarificationOptions: output.options,\n };\n }\n\n if (output.status === 'unanswerable') {\n return {\n success: false,\n unanswerableReason: output.reason,\n suggestions: output.suggestions,\n };\n }\n\n return {\n success: false,\n error: 'Unexpected response from SQL agent',\n };\n } catch (error) {\n return {\n success: false,\n error:\n error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n },\n }),\n\n execute_sql: tool({\n description: `Execute a SQL query directly. Use this when you have SQL that you want to run\n(e.g., after receiving SQL from consult_sql_agent or for follow-up queries).`,\n inputSchema: z.object({\n sql: z\n .string()\n .min(1)\n .refine(\n (sql) =>\n sql.trim().toUpperCase().startsWith('SELECT') ||\n sql.trim().toUpperCase().startsWith('WITH'),\n {\n message: 'Only read-only SELECT or WITH queries are allowed.',\n },\n )\n .describe('The SQL query to execute.'),\n }),\n execute: async ({ sql }, options) => {\n const state = toState<Chat3State>(options);\n\n try {\n // Validate first\n const validationError = await state.adapter.validate(sql);\n if (validationError) {\n return {\n success: false,\n error: `Validation failed: ${validationError}`,\n };\n }\n\n const data = await state.adapter.execute(sql);\n return {\n success: true,\n data,\n rowCount: Array.isArray(data) ? data.length : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Execution failed',\n };\n }\n },\n }),\n\n scratchpad: scratchpad_tool,\n};\n\n/**\n * Chat3 Agent - Table Augmented Generation with agent collaboration.\n *\n * This agent collaborates with a specialized SQL agent that can:\n * - Express confidence levels\n * - Surface assumptions\n * - Request clarification\n *\n * This enables higher quality SQL generation through dialogue.\n */\nexport const chat3Agent = agent<never, Chat3State>({\n name: 'chat3-collaborative',\n model: groq('openai/gpt-oss-20b'),\n tools,\n prompt: (state) => {\n return `\n${state?.teachings || ''}\n${state?.introspection || ''}\n\nWhen answering questions that require database queries, use the consult_sql_agent tool.\n\nThe SQL agent may respond in three ways:\n1. SUCCESS with SQL, confidence, and assumptions - review the confidence and assumptions\n2. CLARIFICATION_NEEDED with a question - either answer from context or ask the user\n3. UNANSWERABLE with reason and suggestions - relay this to the user helpfully\n\nFor medium/low confidence results, consider mentioning the assumptions to the user.\nFor clarification requests, try to answer from conversation context first before asking the user.\n`;\n },\n});\n\nexport { tools as chat3Tools };\n", "/**\n * Chat4 Agent - Question Decomposition Approach\n *\n * This variant breaks down the user's question into semantic components\n * before passing it to the SQL agent. Instead of:\n * \"Which customers bought the most expensive products last quarter?\"\n *\n * It passes a decomposition:\n * - entities: customers, products, purchases\n * - filters: expensive products, last quarter\n * - aggregation: most (count? value?)\n * - output: list of customers\n *\n * This helps the SQL agent understand the different aspects of the question\n * without being told HOW to implement it.\n */\nimport { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, tool, wrapLanguageModel } from 'ai';\nimport z from 'zod';\n\nimport { agent, generate, toState, user } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter } from '../adapters/adapter.ts';\nimport type { TeachablesStore } from '../memory/store.ts';\nimport {\n type Teachables,\n persona,\n toInstructions,\n} from '../teach/teachables.ts';\n\nexport type Chat4State = {\n /** Database adapter for query execution */\n adapter: Adapter;\n /** Schema introspection XML */\n introspection: string;\n /** Teachings/instructions for SQL generation */\n instructions: Teachables[];\n /** Combined teachings string for the agent prompt */\n teachings: string;\n /** Optional memory store for user teachables */\n memory?: TeachablesStore;\n /** User ID for memory operations */\n userId?: string;\n};\n\n/**\n * Schema for question decomposition\n */\nconst questionDecompositionSchema = z.object({\n originalQuestion: z\n .string()\n .describe('The original question being decomposed'),\n breakdown: z\n .array(z.string())\n .min(1)\n .describe(\n 'Semantic breakdown of the question into its component parts. Each part describes an aspect of what is being asked, NOT how to implement it.',\n ),\n entities: z\n .array(z.string())\n .optional()\n .describe(\n 'Key entities/concepts mentioned (e.g., customers, orders, products)',\n ),\n filters: z\n .array(z.string())\n .optional()\n .describe(\n 'Filtering criteria mentioned (e.g., \"last quarter\", \"above $100\")',\n ),\n aggregation: z\n .string()\n .optional()\n .describe(\n 'Type of aggregation if any (e.g., \"count\", \"sum\", \"average\", \"top N\")',\n ),\n ambiguities: z\n .array(z.string())\n .optional()\n .describe('Any ambiguous parts that might need clarification'),\n});\n\ntype QuestionDecomposition = z.infer<typeof questionDecompositionSchema>;\n\n/**\n * Output schema for the decomposition-aware SQL agent\n */\nconst decompositionSqlOutputSchema = z.union([\n z.object({\n sql: z\n .string()\n .describe('The SQL query that answers the decomposed question'),\n reasoning: z\n .string()\n .optional()\n .describe('How each breakdown component was addressed'),\n }),\n z.object({\n error: z\n .string()\n .describe('Error message if the question cannot be answered'),\n }),\n]);\n\ntype DecompositionSqlOutput = z.infer<typeof decompositionSqlOutputSchema>;\n\n/**\n * Internal agent for SQL generation from decomposed questions\n */\nconst decompositionSqlAgent = agent<DecompositionSqlOutput, Chat4State>({\n name: 'decomposition-sql',\n model: groq('openai/gpt-oss-20b'),\n output: decompositionSqlOutputSchema,\n prompt: (state) => {\n return `\n${toInstructions(\n 'instructions',\n persona({\n name: 'SQLDecomp',\n role: 'You are an expert SQL query generator. You receive questions broken down into semantic components and generate precise SQL.',\n }),\n ...(state?.instructions || []),\n)}\n${state?.introspection || ''}\n\nYou will receive questions in a decomposed format with:\n- breakdown: Semantic parts of the question\n- entities: Key concepts mentioned\n- filters: Filtering criteria\n- aggregation: Type of aggregation needed\n- ambiguities: Potentially unclear parts\n\nAddress each component of the breakdown in your SQL.\nIf there are ambiguities, make reasonable assumptions and note them in your reasoning.\n`;\n },\n});\n\n/**\n * Result from the decomposed query tool\n */\nexport interface DecomposedQueryResult {\n success: boolean;\n /** The original question */\n question?: string;\n /** How the question was decomposed */\n decomposition?: QuestionDecomposition;\n /** The generated SQL */\n sql?: string;\n /** Query results */\n data?: unknown[];\n /** How breakdown components were addressed */\n reasoning?: string;\n /** Error message if failed */\n error?: string;\n /** Number of generation attempts */\n attempts?: number;\n}\n\n/** Temperature progression for retries */\nconst RETRY_TEMPERATURES = [0, 0.2, 0.3];\n\nconst tools = {\n query_with_decomposition: tool({\n description: `Query the database using question decomposition. This tool:\n1. Breaks down your question into semantic components (entities, filters, aggregations)\n2. Passes the decomposition to the SQL specialist\n3. Generates and validates SQL\n4. Executes and returns results\n\nThis approach helps ensure all aspects of the question are addressed in the query.`,\n inputSchema: z.object({\n question: z.string().min(1).describe('The question to answer.'),\n breakdown: z\n .array(z.string())\n .min(1)\n .describe(\n 'Break down the question into its semantic parts. Each part should describe an ASPECT of what is being asked, not instructions. Example for \"top customers by revenue last month\": [\"customers who made purchases\", \"revenue from those purchases\", \"time period: last month\", \"ranking: top by total revenue\"]',\n ),\n entities: z\n .array(z.string())\n .optional()\n .describe(\n 'Key entities mentioned (e.g., [\"customers\", \"orders\", \"products\"])',\n ),\n filters: z\n .array(z.string())\n .optional()\n .describe('Filter criteria (e.g., [\"last month\", \"status = active\"])'),\n aggregation: z\n .string()\n .optional()\n .describe(\n 'Aggregation type if any (e.g., \"sum revenue\", \"count orders\", \"top 10\")',\n ),\n ambiguities: z\n .array(z.string())\n .optional()\n .describe('Note any ambiguous parts you identified'),\n }),\n execute: async (\n { question, breakdown, entities, filters, aggregation, ambiguities },\n options,\n ): Promise<DecomposedQueryResult> => {\n const state = toState<Chat4State>(options);\n\n const decomposition: QuestionDecomposition = {\n originalQuestion: question,\n breakdown,\n entities,\n filters,\n aggregation,\n ambiguities,\n };\n\n // Format the decomposition for the SQL agent\n const decomposedPrompt = formatDecomposition(decomposition);\n\n try {\n // Try SQL generation with retry logic\n let lastError: string | undefined;\n\n for (let attempt = 0; attempt < RETRY_TEMPERATURES.length; attempt++) {\n const temperature = RETRY_TEMPERATURES[attempt];\n\n const agentInstance = decompositionSqlAgent.clone({\n model: wrapLanguageModel({\n model: decompositionSqlAgent.model,\n middleware: defaultSettingsMiddleware({\n settings: { temperature },\n }),\n }),\n });\n\n const prompt = lastError\n ? `${decomposedPrompt}\\n\\nPrevious attempt failed with: ${lastError}. Please fix the query.`\n : decomposedPrompt;\n\n const { experimental_output: output } = await generate(\n agentInstance,\n [user(prompt)],\n state,\n );\n\n if ('error' in output) {\n return {\n success: false,\n question,\n decomposition,\n error: output.error,\n attempts: attempt + 1,\n };\n }\n\n // Validate the SQL\n const validationError = await state.adapter.validate(output.sql);\n if (validationError) {\n lastError = validationError;\n continue;\n }\n\n // Execute the SQL\n const data = await state.adapter.execute(output.sql);\n\n return {\n success: true,\n question,\n decomposition,\n sql: output.sql,\n data,\n reasoning: output.reasoning,\n attempts: attempt + 1,\n };\n }\n\n // All retries exhausted\n return {\n success: false,\n question,\n decomposition,\n error: `Failed after ${RETRY_TEMPERATURES.length} attempts. Last error: ${lastError}`,\n attempts: RETRY_TEMPERATURES.length,\n };\n } catch (error) {\n return {\n success: false,\n question,\n decomposition,\n error:\n error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n },\n }),\n\n execute_sql: tool({\n description: `Execute a SQL query directly. Use for follow-up queries or when you already have SQL.`,\n inputSchema: z.object({\n sql: z\n .string()\n .min(1)\n .refine(\n (sql) =>\n sql.trim().toUpperCase().startsWith('SELECT') ||\n sql.trim().toUpperCase().startsWith('WITH'),\n {\n message: 'Only read-only SELECT or WITH queries are allowed.',\n },\n )\n .describe('The SQL query to execute.'),\n }),\n execute: async ({ sql }, options) => {\n const state = toState<Chat4State>(options);\n\n try {\n const validationError = await state.adapter.validate(sql);\n if (validationError) {\n return {\n success: false,\n error: `Validation failed: ${validationError}`,\n };\n }\n\n const data = await state.adapter.execute(sql);\n return {\n success: true,\n data,\n rowCount: Array.isArray(data) ? data.length : undefined,\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Execution failed',\n };\n }\n },\n }),\n\n scratchpad: scratchpad_tool,\n};\n\n/**\n * Format a question decomposition into a prompt for the SQL agent\n */\nfunction formatDecomposition(decomposition: QuestionDecomposition): string {\n const parts: string[] = [\n `Original Question: ${decomposition.originalQuestion}`,\n '',\n 'Question Breakdown:',\n ...decomposition.breakdown.map((part, i) => ` ${i + 1}. ${part}`),\n ];\n\n if (decomposition.entities?.length) {\n parts.push('', `Entities: ${decomposition.entities.join(', ')}`);\n }\n\n if (decomposition.filters?.length) {\n parts.push('', `Filters: ${decomposition.filters.join(', ')}`);\n }\n\n if (decomposition.aggregation) {\n parts.push('', `Aggregation: ${decomposition.aggregation}`);\n }\n\n if (decomposition.ambiguities?.length) {\n parts.push(\n '',\n 'Potential Ambiguities:',\n ...decomposition.ambiguities.map((a) => ` - ${a}`),\n );\n }\n\n parts.push(\n '',\n 'Generate SQL that addresses each component of the breakdown.',\n );\n\n return parts.join('\\n');\n}\n\n/**\n * Chat4 Agent - Table Augmented Generation with question decomposition.\n *\n * This agent breaks down questions into semantic components before\n * generating SQL. This approach:\n * - Ensures all aspects of the question are addressed\n * - Makes the reasoning explicit\n * - Helps with complex multi-part questions\n */\nexport const chat4Agent = agent<never, Chat4State>({\n name: 'chat4-decomposition',\n model: groq('openai/gpt-oss-20b'),\n tools,\n prompt: (state) => {\n return `\n${state?.teachings || ''}\n${state?.introspection || ''}\n\nWhen answering questions that require database queries, use the query_with_decomposition tool.\n\nIMPORTANT: You must break down the question into semantic parts - describe WHAT is being asked, not HOW to implement it.\n\nGood breakdown example for \"Which customers bought the most expensive products last quarter?\":\n- \"customers who made purchases\" (entity relationship)\n- \"products they purchased\" (what products)\n- \"expensive products - need definition\" (filter criteria - note ambiguity)\n- \"last quarter\" (time filter)\n- \"most - ranking by count or value?\" (aggregation - note ambiguity)\n\nBad breakdown (too instructional):\n- \"JOIN customers with orders\" (this is HOW, not WHAT)\n- \"Use ORDER BY and LIMIT\" (this is implementation)\n\nBreak the question into its semantic aspects, and let the SQL specialist figure out the implementation.\n`;\n },\n});\n\nexport { tools as chat4Tools };\n", "/**\n * A question/SQL pair extracted or synthesized for training data.\n */\nexport interface ExtractedPair {\n question: string;\n sql: string;\n context?: string[];\n success: boolean;\n}\n\n/**\n * Interface for all pair producers (extractors and synthesizers).\n * Implementations encapsulate their specific inputs and logic.\n */\nexport abstract class PairProducer<T extends ExtractedPair = ExtractedPair> {\n /**\n * Produce question/SQL pairs.\n */\n abstract produce(): AsyncGenerator<T[], void, unknown>;\n\n protected from(producer: PairProducer<ExtractedPair> | ExtractedPair[]) {\n return Array.isArray(producer)\n ? (async function* (pairs: ExtractedPair[]) {\n yield pairs;\n })(producer)\n : producer.produce();\n }\n\n public toPairs(): Promise<T[]> {\n return toPairs(this);\n }\n}\n\n/**\n * Entry point for producing pairs from any source.\n */\nexport async function toPairs<T extends ExtractedPair>(\n producer: PairProducer<T>,\n): Promise<T[]> {\n const pairs: T[] = [];\n for await (const chunk of producer.produce()) {\n pairs.push(...chunk);\n }\n return pairs;\n}\n", "import {\n type Teachables,\n clarification,\n guardrail,\n hint,\n styleGuide,\n workflow,\n} from './teachables.ts';\n\nexport interface TeachingsOptions {\n /**\n * Controls date/time clarification behavior:\n * - 'strict': Ask for clarification when date range is missing (production default)\n * - false: Skip date clarifications, assume all matching data (useful for evals/benchmarks)\n */\n date?: 'strict' | false;\n}\n\nexport function guidelines(options: TeachingsOptions = {}): Teachables[] {\n const { date = 'strict' } = options;\n\n const baseTeachings: Teachables[] = [\n // Schema adherence\n hint(\n 'Use only tables and columns that exist in the schema. Never reference non-existent entities.',\n ),\n hint(\n 'If the user asks to show a table or entity without specifying columns, use SELECT *.',\n ),\n hint(\n 'When showing items associated with another entity, include the item ID and the related details requested.',\n ),\n hint(\n 'When asked to \"show\" items, list them unless the user explicitly asks to count or total.',\n ),\n hint(\n 'Use canonical/LowCardinality values verbatim for filtering; [rows/size] hints suggest when to aggregate instead of listing.',\n ),\n\n // Joins and relationships\n hint(\n 'Use appropriate JOINs based on the relationships defined in the schema.',\n ),\n hint(\n 'Favor PK/indexed columns for joins and filters; follow relationship metadata for join direction and cardinality.',\n ),\n\n // Aggregations and calculations\n hint(\n 'Apply proper aggregations (COUNT, SUM, AVG, etc.) when the question implies summarization.',\n ),\n hint(\n 'When asked \"how many X are there\" about types/categories/statuses (e.g., \"how many statuses are there?\"), use COUNT(DISTINCT column). This asks about variety, not row count.',\n ),\n hint(\n 'Use window functions when the question requires ranking, running totals, or comparisons across rows.',\n ),\n\n // Query semantics\n hint(\n 'Words like \"reach\", \"reached\", \"hit\" with a value (e.g., \"temperature reach 80\") mean >= (greater than or equal), not = (exact match).',\n ),\n hint(\n 'For \"shared by\" two groups or mutually exclusive conditions (e.g., population > 1500 AND < 500), use INTERSECT between separate queries. A single WHERE with contradictory AND returns nothing.',\n ),\n hint(\n 'When filtering by a specific value from a joined table (e.g., \"students who registered course statistics\"), always include that WHERE condition. Do not omit mentioned filters.',\n ),\n hint(\n 'Handle NULL values appropriately using IS NULL, IS NOT NULL, or COALESCE.',\n ),\n\n // Style and readability\n styleGuide({\n prefer:\n 'For table aliases, use the full table name (e.g., \"FROM users AS users\", \"JOIN order_items AS order_items\"). For column aliases, use descriptive names that reflect the data (e.g., \"COUNT(*) AS total_orders\").',\n never:\n 'Use abbreviated table aliases (u, oi, ca) or generic positional aliases (t1, t2, a, b).',\n }),\n styleGuide({\n prefer:\n 'Summaries should be concise, business-friendly, highlight key comparisons, and add a short helpful follow-up when useful.',\n }),\n\n // Guardrails - Query safety\n guardrail({\n rule: 'Generate ONLY valid, executable SQL.',\n reason: 'Invalid SQL wastes resources and confuses users.',\n action: 'Validate syntax and schema references before returning.',\n }),\n guardrail({\n rule: 'Only generate SELECT/WITH statements (read-only queries).',\n reason: 'Prevents accidental data modification.',\n action:\n 'Never generate INSERT, UPDATE, DELETE, DROP, or other DDL/DML statements.',\n }),\n guardrail({\n rule: 'Avoid unbounded scans on large tables.',\n reason: 'Protects performance and prevents runaway queries.',\n action:\n 'Ensure filters are applied on indexed columns before querying broad fact tables.',\n }),\n guardrail({\n rule: 'Do not add LIMIT unless explicitly requested.',\n action:\n 'Only add LIMIT when user explicitly asks for \"top N\", \"first N\", or similar. Do NOT add LIMIT for \"list all\", \"show all\", or simple \"list\" queries.',\n reason: 'Adding arbitrary limits changes query semantics.',\n }),\n guardrail({\n rule: 'Add ORDER BY where appropriate for deterministic results.',\n reason: 'Ensures consistent query output.',\n action:\n 'Include ORDER BY when results have a natural ordering or when combined with LIMIT.',\n }),\n guardrail({\n rule: 'Prevent cartesian or guesswork joins.',\n reason: 'Protect correctness and performance.',\n action:\n 'If join keys are missing or unclear, inspect relationships and ask for the intended join path before executing.',\n }),\n guardrail({\n rule: 'Ensure the query is optimized for the schema.',\n reason: 'Better performance and resource usage.',\n action:\n 'Use indexed columns for filtering, avoid SELECT * on large joins, prefer specific column selection when appropriate.',\n }),\n guardrail({\n rule: 'When facing genuine ambiguity with multiple valid interpretations, seek clarification.',\n reason: 'Prevents incorrect assumptions in edge cases.',\n action:\n 'Ask a focused clarifying question before proceeding with a guess.',\n }),\n\n // Clarifications\n clarification({\n when: 'The request uses ambiguous scoring or ranking language (e.g., \"top\", \"best\", \"active\") without a metric.',\n ask: 'Clarify the ranking metric or definition before writing the query.',\n reason: 'Ensures the correct aggregation/ordering is used.',\n }),\n\n // Workflow\n workflow({\n task: 'SQL generation plan',\n steps: [\n 'Scan column names for terms matching the question. If a phrase like \"total X\" or \"number of Y\" matches a column name (e.g., Total_X, Num_Y), select that column directly instead of aggregating.',\n 'Translate the question into SQL patterns (aggregation, segmentation, time range, ranking) only if no column name match.',\n 'Choose tables/relations that satisfy those patterns; note lookup tables and filter values implied by schema hints.',\n 'Sketch join/filter/aggregation order considering table sizes, indexes, and stats.',\n 'Generate precise, validated SQL that answers the question.',\n ],\n }),\n ];\n\n // Date-specific clarifications (only when strict)\n if (date === 'strict') {\n baseTeachings.push(\n clarification({\n when: 'The request targets time-based data without a date range.',\n ask: 'Confirm the intended timeframe (e.g., last 30/90 days, YTD, specific year).',\n reason: 'Prevents large scans and irrelevant results.',\n }),\n );\n } else {\n // When date is false, assume all matching data without asking\n baseTeachings.push(\n hint(\n 'When a month, day, or time period is mentioned without a year (e.g., \"in August\", \"on Monday\"), assume ALL occurrences of that period in the data. Do not ask for year clarification.',\n ),\n );\n }\n\n return baseTeachings;\n}\n"],
|
|
5
|
+
"mappings": ";AA+CO,SAAS,yBAA2C;AACzD,SAAO;AAAA,IACL,QAAQ,CAAC;AAAA,IACT,OAAO,CAAC;AAAA,IACR,eAAe,CAAC;AAAA,IAChB,MAAM;AAAA,EACR;AACF;;;AC0DO,IAAe,UAAf,MAAuB;AAAA,EAc5B,MAAM,WAAW,MAAM,uBAAuB,GAAG;AAC/C,UAAM,QAAoD,CAAC;AAC3D,eAAW,MAAM,KAAK,WAAW;AAC/B,YAAM,YAAY,GAAG,IAAI;AACzB,YAAM,KAAK;AAAA,QACT,KAAK,UAAU;AAAA,QACf,IAAI,MAAM,UAAU,QAAQ,GAAG;AAAA,MACjC,CAAC;AAAA,IACH;AACA,WAAO,MACJ,IAAI,CAAC,EAAE,IAAI,IAAI,MAAM;AACpB,YAAM,cAAc,GAAG;AACvB,UAAI,gBAAgB,MAAM;AACxB,eAAO;AAAA,MACT;AACA,aAAO,IAAI,GAAG;AAAA,EAAM,WAAW;AAAA,IAAO,GAAG;AAAA,IAC3C,CAAC,EACA,KAAK,IAAI;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EA+BA,SAAS,OAAoC;AAC3C,QAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GAAG;AACvD,aAAO;AAAA,IACT;AACA,QAAI,OAAO,UAAU,UAAU;AAC7B,aAAO,OAA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AAA,YAClB,SAAS;AAAA,UACX,CAAC;AAAA,QACH;AAEA,cAAM,KAAK,QAAQ,QAAQ,WAAW;AAAA,UACpC,IAAIA,IAAG;AAAA,UACP,QAAQ,OAAO;AAAA,UACf,MAAM,gBAAgB;AAAA,UACtB,SAAS;AAAA,QACX,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
|
|
6
|
+
"names": ["groq", "dedent", "z", "agent", "generate", "groq", "z", "agent", "term", "clarification", "teachable", "tag", "agent", "groq", "z", "context", "dedent", "z", "generate", "agent", "groq", "groq", "dedent", "z", "agent", "agent", "groq", "z", "dedent", "groq", "tool", "z", "agent", "toState", "scratchpad_tool", "tools", "tool", "z", "toState", "scratchpad_tool", "agent", "groq", "path", "process", "createHash", "existsSync", "hash", "path", "DatabaseSync", "path", "DatabaseSync", "v7", "generate", "user", "groq", "tool", "dedent", "z", "agent", "toState", "scratchpad_tool", "tools", "groq", "tool", "z", "agent", "toState", "scratchpad_tool", "tools", "tool", "z", "toState", "scratchpad_tool", "agent", "groq", "groq", "tool", "z", "agent", "toState", "scratchpad_tool", "tools", "tool", "z", "toState", "scratchpad_tool", "agent", "groq", "groq", "defaultSettingsMiddleware", "tool", "wrapLanguageModel", "z", "agent", "generate", "toState", "user", "scratchpad_tool", "z", "agent", "groq", "tools", "tool", "context", "toState", "wrapLanguageModel", "defaultSettingsMiddleware", "generate", "user", "scratchpad_tool", "groq", "defaultSettingsMiddleware", "tool", "wrapLanguageModel", "z", "agent", "generate", "toState", "user", "scratchpad_tool", "z", "agent", "groq", "RETRY_TEMPERATURES", "tools", "tool", "toState", "wrapLanguageModel", "defaultSettingsMiddleware", "generate", "user", "scratchpad_tool", "generate", "user", "agent", "tools", "v7"]
|
|
7
7
|
}
|