@deepagents/text2sql 0.2.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.
Files changed (45) hide show
  1. package/dist/index.d.ts +13 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +3102 -0
  4. package/dist/index.js.map +7 -0
  5. package/dist/lib/adapters/adapter.d.ts +80 -0
  6. package/dist/lib/adapters/adapter.d.ts.map +1 -0
  7. package/dist/lib/adapters/postgres.d.ts +31 -0
  8. package/dist/lib/adapters/postgres.d.ts.map +1 -0
  9. package/dist/lib/adapters/resolveTables.spec.d.ts +2 -0
  10. package/dist/lib/adapters/resolveTables.spec.d.ts.map +1 -0
  11. package/dist/lib/adapters/sqlite.d.ts +30 -0
  12. package/dist/lib/adapters/sqlite.d.ts.map +1 -0
  13. package/dist/lib/adapters/sqlserver.d.ts +31 -0
  14. package/dist/lib/adapters/sqlserver.d.ts.map +1 -0
  15. package/dist/lib/agents/brief.agent.d.ts +16 -0
  16. package/dist/lib/agents/brief.agent.d.ts.map +1 -0
  17. package/dist/lib/agents/explainer.agent.d.ts +8 -0
  18. package/dist/lib/agents/explainer.agent.d.ts.map +1 -0
  19. package/dist/lib/agents/suggestions.agents.d.ts +16 -0
  20. package/dist/lib/agents/suggestions.agents.d.ts.map +1 -0
  21. package/dist/lib/agents/synthesizer.agent.d.ts +6 -0
  22. package/dist/lib/agents/synthesizer.agent.d.ts.map +1 -0
  23. package/dist/lib/agents/teachables.agent.d.ts +14 -0
  24. package/dist/lib/agents/teachables.agent.d.ts.map +1 -0
  25. package/dist/lib/agents/text2sql.agent.d.ts +38 -0
  26. package/dist/lib/agents/text2sql.agent.d.ts.map +1 -0
  27. package/dist/lib/history/history.d.ts +41 -0
  28. package/dist/lib/history/history.d.ts.map +1 -0
  29. package/dist/lib/history/memory.history.d.ts +5 -0
  30. package/dist/lib/history/memory.history.d.ts.map +1 -0
  31. package/dist/lib/history/sqlite.history.d.ts +15 -0
  32. package/dist/lib/history/sqlite.history.d.ts.map +1 -0
  33. package/dist/lib/memory/user-profile.d.ts +39 -0
  34. package/dist/lib/memory/user-profile.d.ts.map +1 -0
  35. package/dist/lib/prompt.d.ts +7 -0
  36. package/dist/lib/prompt.d.ts.map +1 -0
  37. package/dist/lib/sql.d.ts +52 -0
  38. package/dist/lib/sql.d.ts.map +1 -0
  39. package/dist/lib/teach/teachables.d.ts +462 -0
  40. package/dist/lib/teach/teachables.d.ts.map +1 -0
  41. package/dist/lib/teach/teachings.d.ts +4 -0
  42. package/dist/lib/teach/teachings.d.ts.map +1 -0
  43. package/dist/lib/teach/xml.d.ts +6 -0
  44. package/dist/lib/teach/xml.d.ts.map +1 -0
  45. package/package.json +38 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/lib/agents/text2sql.agent.ts", "../src/lib/prompt.ts", "../src/lib/sql.ts", "../src/lib/adapters/adapter.ts", "../src/lib/adapters/sqlite.ts", "../src/lib/agents/brief.agent.ts", "../src/lib/agents/explainer.agent.ts", "../src/lib/agents/suggestions.agents.ts", "../src/lib/agents/synthesizer.agent.ts", "../src/lib/agents/teachables.agent.ts", "../src/lib/teach/xml.ts", "../src/lib/teach/teachables.ts", "../src/lib/history/history.ts", "../src/lib/memory/user-profile.ts", "../src/lib/adapters/postgres.ts", "../src/lib/adapters/sqlserver.ts", "../src/lib/history/sqlite.history.ts", "../src/lib/history/history.sqlite.sql", "../src/lib/history/memory.history.ts"],
4
+ "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { type Tool, tool } from 'ai';\nimport z from 'zod';\n\nimport {\n type StepBackExample,\n agent,\n stepBackPrompt,\n toState,\n} from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport type { Adapter, Introspection } from '../adapters/adapter.ts';\nimport { databaseSchemaPrompt } from '../prompt.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: `Get a few sample rows from a table to understand data formatting and values. Use this when you are unsure about the content of a column (e.g. date formats, status codes, string variations).`,\n inputSchema: z.object({\n tableName: z.string().describe('The name of the table to sample.'),\n }),\n execute: ({ tableName }, options) => {\n tableName = tableName.replace(/[^a-zA-Z0-9_.]/g, '');\n const state = toState<{ adapter: Adapter }>(options);\n return state.adapter.execute(`SELECT * FROM ${tableName} LIMIT 3`);\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 getRenderingGuidance = (renderingTools?: RenderingTools) => {\n const renderingToolNames = Object.keys(renderingTools ?? {}).filter(\n (toolName) => toolName.startsWith('render_'),\n );\n\n if (!renderingToolNames.length) {\n return { constraint: undefined, section: '' };\n }\n\n return {\n constraint:\n '**Rendering**: Use a render_* visualization tool for trend/over time/monthly requests or explicit chart asks; otherwise provide the insight in text.',\n section: `\n <rendering_tools>\n Rendering tools available: ${renderingToolNames.join(', ')}.\n Use the matching render_* tool when the user requests a chart or mentions trends/over time/monthly performance. Prefer a line chart for those time-based requests. Always include a concise text insight alongside any visualization; if no suitable render_* tool fits, deliver the insight in text only.\n </rendering_tools>\n `,\n };\n};\n\nconst SQL_STEP_BACK_EXAMPLES: StepBackExample[] = [\n {\n originalQuestion: 'Who are our top 5 customers by spending?',\n stepBackQuestion:\n 'What are the SQL principles for ranking and aggregation queries?',\n stepBackAnswer:\n 'Ranking queries require: 1) Aggregation functions (SUM, COUNT, AVG) grouped by the entity to rank, 2) JOINs to connect related data across tables (e.g., Customer to Invoice), 3) ORDER BY to sort by the aggregated metric, 4) LIMIT to restrict to top N results. For customer spending, join Customer and Invoice tables, sum invoice totals, group by customer identifier, order by total descending.',\n finalAnswer:\n 'SELECT c.FirstName, c.LastName, SUM(i.Total) as total_spent FROM Customer c JOIN Invoice i ON c.CustomerId = i.CustomerId GROUP BY c.CustomerId ORDER BY total_spent DESC LIMIT 5',\n },\n {\n originalQuestion: 'Show me sales by month for 2013',\n stepBackQuestion:\n 'What are the principles of time-based grouping and aggregation in SQL?',\n stepBackAnswer:\n 'Time-based queries require: 1) Date extraction functions (e.g., DATE_TRUNC, strftime, YEAR/FORMAT) to bucket timestamps, 2) WHERE clauses to filter the date range, 3) GROUP BY the derived period, 4) Aggregations such as SUM for revenue and COUNT for transactions, 5) ORDER BY the period chronologically.',\n finalAnswer:\n \"SELECT date_trunc('month', InvoiceDate) as month, COUNT(*) as sales_count, SUM(Total) as revenue FROM Invoice WHERE EXTRACT(year FROM InvoiceDate) = 2013 GROUP BY month ORDER BY month -- replace date_trunc/EXTRACT with your dialect's month/year helpers\",\n },\n {\n originalQuestion: 'What are the best-selling tracks by genre?',\n stepBackQuestion:\n 'What are the SQL principles for multi-dimensional aggregation with categories?',\n stepBackAnswer:\n 'Multi-dimensional queries require: 1) Multiple JOINs to connect entities through foreign key relationships (Genre \u2192 Track \u2192 InvoiceLine), 2) GROUP BY all categorical dimensions you want to analyze (GenreId, TrackId), 3) Aggregation at the intersection of these dimensions (COUNT of sales per track per genre), 4) Proper table aliasing for query readability, 5) Understanding the data model relationships (which tables link to which).',\n finalAnswer:\n 'SELECT g.Name as genre, t.Name as track, COUNT(*) as times_sold FROM Genre g JOIN Track t ON g.GenreId = t.GenreId JOIN InvoiceLine il ON t.TrackId = il.TrackId GROUP BY g.GenreId, t.TrackId ORDER BY times_sold DESC LIMIT 10',\n },\n];\n\nconst text2sqlAgent = agent<\n { sql: string },\n {\n introspection: Introspection;\n context: string;\n adapterInfo: string;\n renderingTools?: RenderingTools;\n teachings: string;\n userProfile?: string;\n }\n>({\n name: 'text2sql',\n model: groq('openai/gpt-oss-20b'),\n prompt: (state) => {\n const renderingGuidance = getRenderingGuidance(state?.renderingTools);\n const constraints = [\n '**Max Output Rows**: Never output more than 100 rows of raw data. Use aggregation or pagination otherwise.',\n '**Validation**: You must validate your query before final execution. Follow the pattern: Draft Query \u2192 `validate_query` \u2192 Fix (if needed) \u2192 `db_query`.',\n '**Data Inspection**: If you are unsure about column values (e.g. status codes, date formats), use `get_sample_rows` to inspect the data before writing the query.',\n '**Tool Usage**: If you have not produced a SQL snippet, do not call `db_query`. First produce the query string, then validate.',\n renderingGuidance.constraint,\n '**Scratchpad**: Use the `scratchpad` tool for strategic reflection during SQL query generation.',\n ].filter(Boolean);\n\n const constraintsSection = constraints\n .map((constraint, index) => ` ${index + 1}. ${constraint}`)\n .join('\\n');\n\n return `\n <identity>\n You are an expert SQL query generator, answering business questions with accurate queries.\n Your tone should be concise and business-friendly.\n </identity>\n\n ${state?.userProfile || ''}\n\n ${databaseSchemaPrompt(state!)}\n\n ${state?.teachings || ''}\n\n <query_reasoning_strategy>\n ${stepBackPrompt('general', {\n examples: SQL_STEP_BACK_EXAMPLES,\n stepBackQuestionTemplate:\n 'What are the SQL patterns, database principles, and schema relationships needed to answer this question?',\n })}\n\n Skip Step-Back only if the question is a direct \u201CSELECT * FROM \u2026\u201D or a simple aggregation with a clear target.\n </query_reasoning_strategy>\n\n <constraints>\n${constraintsSection}\n </constraints>\n${renderingGuidance.section}\n `;\n },\n});\n\nexport const text2sqlOnly = text2sqlAgent.clone({\n tools: {},\n output: z.object({\n sql: z\n .string()\n .describe('The SQL query generated to answer the user question.'),\n }),\n prompt: (state) => {\n return `\n <identity>\n You are an expert SQL query generator, answering business questions with accurate queries.\n Your tone should be concise and business-friendly.\n </identity>\n\n ${databaseSchemaPrompt(state!)}\n\n <constraints>\n 1. **Output**: Provide ONLY the SQL query. Do not include markdown formatting like \\`\\`\\`sql ... \\`\\`\\`.\n 2. **Dialect**: Use standard SQL compatible with SQLite unless specified otherwise.\n </constraints>\n `;\n },\n});\n\nexport const text2sqlMonolith = text2sqlAgent.clone({\n model: groq('openai/gpt-oss-20b'),\n // model: openai('gpt-5.1-codex'),\n tools,\n});\n", "import pluralize from 'pluralize';\n\nimport type { Introspection } from './adapters/adapter.ts';\n\nconst describeTables = (introspection: Introspection) => {\n if (!introspection.tables.length) {\n return 'Schema unavailable.';\n }\n\n return introspection.tables\n .map((table) => {\n const rowCountInfo =\n table.rowCount != null\n ? ` [rows: ${table.rowCount}${table.sizeHint ? `, size: ${table.sizeHint}` : ''}]`\n : '';\n const columns = table.columns\n .map((column) => {\n const annotations: string[] = [];\n if (column.isPrimaryKey) {\n annotations.push('PK');\n }\n if (column.isIndexed && !column.isPrimaryKey) {\n annotations.push('Indexed');\n }\n if (column.kind === 'LowCardinality' && column.values?.length) {\n annotations.push(`LowCardinality: ${column.values.join(', ')}`);\n }\n if (column.stats) {\n const statParts: string[] = [];\n if (column.stats.min != null || column.stats.max != null) {\n const minText = column.stats.min ?? 'n/a';\n const maxText = column.stats.max ?? 'n/a';\n statParts.push(`range ${minText} \u2192 ${maxText}`);\n }\n if (\n column.stats.nullFraction != null &&\n Number.isFinite(column.stats.nullFraction)\n ) {\n const percent = Math.round(column.stats.nullFraction * 1000) / 10;\n statParts.push(`null\u2248${percent}%`);\n }\n if (statParts.length) {\n annotations.push(statParts.join(', '));\n }\n }\n const annotationText = annotations.length ? ` [${annotations.join(', ')}]` : '';\n return ` - ${column.name} (${column.type})${annotationText}`;\n })\n .join('\\n');\n const indexes =\n table.indexes?.length\n ? `\\n Indexes:\\n${table.indexes\n .map((index) => {\n const props: string[] = [];\n if (index.primary) {\n props.push('PRIMARY');\n } else if (index.unique) {\n props.push('UNIQUE');\n }\n if (index.type) {\n props.push(index.type);\n }\n const propsText = props.length ? ` (${props.join(', ')})` : '';\n const columnsText = index.columns?.length ? index.columns.join(', ') : 'expression';\n return ` - ${index.name}${propsText}: ${columnsText}`;\n })\n .join('\\n')}`\n : '';\n return `- Table: ${table.name}${rowCountInfo}\\n Columns:\\n${columns}${indexes}`;\n })\n .join('\\n\\n');\n};\n\nconst formatTableLabel = (tableName: string) => {\n const base = tableName.split('.').pop() ?? tableName;\n return base.replace(/_/g, ' ');\n};\n\nconst describeRelationships = (introspection: Introspection) => {\n if (!introspection.relationships.length) {\n return 'None detected';\n }\n\n const tableMap = new Map(introspection.tables.map((table) => [table.name, table]));\n\n return introspection.relationships\n .map((relationship) => {\n const sourceLabel = formatTableLabel(relationship.table);\n const targetLabel = formatTableLabel(relationship.referenced_table);\n const singularSource = pluralize.singular(sourceLabel);\n const pluralSource = pluralize(sourceLabel);\n const singularTarget = pluralize.singular(targetLabel);\n const pluralTarget = pluralize(targetLabel);\n const sourceTable = tableMap.get(relationship.table);\n const targetTable = tableMap.get(relationship.referenced_table);\n const sourceCount = sourceTable?.rowCount;\n const targetCount = targetTable?.rowCount;\n const ratio =\n sourceCount != null && targetCount != null && targetCount > 0\n ? sourceCount / targetCount\n : null;\n\n let cardinality = 'each';\n if (ratio != null) {\n if (ratio > 5) {\n cardinality = `many-to-one (\u2248${sourceCount} vs ${targetCount})`;\n } else if (ratio < 1.2 && ratio > 0.8) {\n cardinality = `roughly 1:1 (${sourceCount} vs ${targetCount})`;\n } else if (ratio < 0.2) {\n cardinality = `one-to-many (${sourceCount} vs ${targetCount})`;\n }\n }\n const mappings = relationship.from\n .map((fromCol, idx) => {\n const targetCol = relationship.to[idx] ?? relationship.to[0] ?? fromCol;\n return `${relationship.table}.${fromCol} -> ${relationship.referenced_table}.${targetCol}`;\n })\n .join(', ');\n\n return `- ${relationship.table} (${relationship.from.join(', ')}) -> ${relationship.referenced_table} (${relationship.to.join(', ')}) [${cardinality}]`;\n })\n .join('\\n');\n};\n\nexport function databaseSchemaPrompt(options: {\n introspection: Introspection;\n context?: string;\n adapterInfo?: string;\n}) {\n const tablesSummary = describeTables(options.introspection);\n const relationshipsSummary = describeRelationships(options.introspection);\n const contextInfo = options.context || '';\n const adapterInfo = options.adapterInfo;\n const lines = [\n adapterInfo ? `<dialect_info>${adapterInfo}</dialect_info>` : '',\n contextInfo ? `<context>${contextInfo}</context>` : '',\n `<tables>\\n${tablesSummary}\\n</tables>`,\n `<relationships>\\n${relationshipsSummary}\\n</relationships>`,\n ];\n return `<schema_context>${lines.filter(Boolean).join('\\n\\n')}</schema_context>`\n}\n", "import {\n type InferUIMessageChunk,\n InvalidToolInputError,\n NoSuchToolError,\n ToolCallRepairError,\n type UIDataTypes,\n type UIMessage,\n type UIMessageChunk,\n type UITools,\n tool,\n} from 'ai';\nimport dedent from 'dedent';\nimport { v7 } from 'uuid';\nimport z from 'zod';\n\nimport { generate, pipe, stream, user } from '@deepagents/agent';\n\nimport type { Adapter } from './adapters/adapter.ts';\nimport { Sqlite } from './adapters/sqlite.ts';\nimport { BriefCache, generateBrief, toBrief } from './agents/brief.agent.ts';\nimport { explainerAgent } from './agents/explainer.agent.ts';\nimport { suggestionsAgent } from './agents/suggestions.agents.ts';\nimport { synthesizerAgent } from './agents/synthesizer.agent.ts';\nimport { teachablesAuthorAgent } from './agents/teachables.agent.ts';\nimport {\n type RenderingTools,\n text2sqlMonolith,\n text2sqlOnly,\n} from './agents/text2sql.agent.ts';\nimport { History } from './history/history.ts';\nimport { UserProfileStore } from './memory/user-profile.ts';\nimport {\n type Teachables,\n toInstructions,\n toTeachables,\n} from './teach/teachables.ts';\n\nexport class Text2Sql {\n #config: {\n adapter: Adapter;\n cache: BriefCache;\n history: History;\n tools?: RenderingTools;\n instructions: Teachables[];\n };\n constructor(config: {\n adapter: Adapter;\n cache: BriefCache;\n history: History;\n tools?: RenderingTools;\n instructions?: Teachables[];\n }) {\n this.#config = {\n ...config,\n instructions: config.instructions ?? [],\n tools: config.tools ?? {},\n };\n }\n async #getSql(\n stream: ReadableStream<\n InferUIMessageChunk<UIMessage<unknown, UIDataTypes, UITools>>\n >,\n ) {\n const chunks = (await Array.fromAsync(\n stream as AsyncIterable<UIMessageChunk>,\n )) as UIMessageChunk[];\n const sql = chunks.at(-1);\n if (sql && sql.type === 'data-text-delta') {\n return (sql.data as { text: string }).text;\n }\n throw new Error('No SQL generated');\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) {\n const [introspection, adapterInfo] = await Promise.all([\n this.#config.adapter.introspect(),\n this.#config.adapter.info(),\n ]);\n const context = await generateBrief(introspection, this.#config.cache);\n\n return {\n generate: async () => {\n const { experimental_output: output } = await generate(\n text2sqlOnly,\n [user(input)],\n {\n adapterInfo: this.#config.adapter.formatInfo(adapterInfo),\n context,\n introspection,\n teachings: toInstructions(...this.#config.instructions),\n },\n );\n return output.sql;\n },\n };\n }\n\n public async inspect() {\n const [introspection, adapterInfo] = await Promise.all([\n this.#config.adapter.introspect(),\n this.#config.adapter.info(),\n ]);\n const context = await generateBrief(introspection, this.#config.cache);\n\n return text2sqlOnly.instructions({\n adapterInfo: this.#config.adapter.formatInfo(adapterInfo),\n context,\n introspection,\n teachings: toInstructions(...this.#config.instructions),\n });\n }\n\n public instruct(...dataset: Teachables[]) {\n this.#config.instructions.push(...dataset);\n }\n\n public async teach(input: string) {\n const [introspection, adapterInfo] = await Promise.all([\n this.#config.adapter.introspect(),\n this.#config.adapter.info(),\n ]);\n const context = await generateBrief(introspection, this.#config.cache);\n const { experimental_output } = await generate(\n teachablesAuthorAgent,\n [user(input)],\n {\n introspection,\n adapterInfo: this.#config.adapter.formatInfo(adapterInfo),\n context,\n },\n );\n const teachables = toTeachables(experimental_output.teachables);\n this.#config.instructions.push(...teachables);\n return {\n teachables,\n teachings: toInstructions(...this.#config.instructions),\n };\n }\n\n public async tag(input: string) {\n const [introspection, adapterInfo] = await Promise.all([\n this.#config.adapter.introspect(),\n this.#config.adapter.info(),\n ]);\n const pipeline = pipe(\n {\n input,\n adapter: this.#config.adapter,\n cache: this.#config.cache,\n introspection,\n adapterInfo: this.#config.adapter.formatInfo(adapterInfo),\n messages: [user(input)],\n renderingTools: this.#config.tools || {},\n teachings: toInstructions(...this.#config.instructions),\n },\n toBrief(),\n async (state, update) => {\n const { experimental_output: output } = await generate(\n text2sqlOnly,\n state.messages,\n state,\n );\n update({\n messages: [\n user(\n dedent`\n Based on the data provided, please explain in clear, conversational language what insights this reveals.\n\n <user_question>${state.input}</user_question>\n <data>${JSON.stringify(this.#config.adapter.execute(output.sql))}</data>\n `,\n ),\n ],\n });\n return output.sql;\n },\n synthesizerAgent,\n );\n const stream = pipeline();\n return {\n generate: async () => {\n const sql = await this.#getSql(stream);\n return sql;\n },\n stream: () => {\n return stream;\n },\n };\n }\n\n public async suggest() {\n const [introspection, adapterInfo] = await Promise.all([\n this.#config.adapter.introspect(),\n this.#config.adapter.info(),\n ]);\n const context = await generateBrief(introspection, this.#config.cache);\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 introspection,\n adapterInfo: this.#config.adapter.formatInfo(adapterInfo),\n context,\n },\n );\n return output.suggestions;\n }\n\n public async single(input: string) {\n const [introspection, adapterInfo] = await Promise.all([\n this.#config.adapter.introspect(),\n this.#config.adapter.info(),\n ]);\n // console.log(text2sqlMonolith.instructions({\n // adapterInfo: this.#config.adapter.formatInfo(adapterInfo),\n // context: await generateBrief(introspection, this.#config.cache),\n // introspection,\n // }));\n return stream(\n text2sqlMonolith.clone({\n tools: {\n ...text2sqlMonolith.handoff.tools,\n ...this.#config.tools,\n },\n }),\n [user(input)],\n {\n teachings: toInstructions(...this.#config.instructions),\n adapter: this.#config.adapter,\n introspection,\n adapterInfo: this.#config.adapter.formatInfo(adapterInfo),\n context: await generateBrief(introspection, this.#config.cache),\n renderingTools: this.#config.tools || {},\n },\n );\n }\n public async chat(\n messages: UIMessage[],\n params: {\n chatId: string;\n userId: string;\n },\n ) {\n const [introspection, adapterInfo] = await Promise.all([\n this.#config.adapter.introspect(),\n this.#config.adapter.info(),\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 userProfileStore = new UserProfileStore(params.userId);\n const userProfileXml = await userProfileStore.toXml();\n\n const result = stream(\n text2sqlMonolith.clone({\n tools: {\n ...text2sqlMonolith.handoff.tools,\n ...this.#config.tools,\n update_user_profile: tool({\n description: `Update the user's profile with new facts, preferences, or present context.\n Use this when the user explicitly states a preference (e.g., \"I like dark mode\", \"Call me Ezz\")\n or when their working context changes (e.g., \"I'm working on a hackathon\").`,\n inputSchema: z.object({\n type: z\n .enum(['fact', 'preference', 'present'])\n .describe('The type of information to update.'),\n text: z\n .string()\n .describe(\n 'The content of the fact, preference, or present context.',\n ),\n action: z\n .enum(['add', 'remove'])\n .default('add')\n .describe('Whether to add or remove the item.'),\n }),\n execute: async ({ type, text, action }) => {\n if (action === 'remove') {\n await userProfileStore.remove(type, text);\n return `Removed ${type}: ${text}`;\n }\n\n await userProfileStore.add(type, text);\n return `Added ${type}: ${text}`;\n },\n }),\n },\n }),\n [...chat.messages.map((it) => it.content), ...messages],\n {\n teachings: toInstructions(...this.#config.instructions),\n adapter: this.#config.adapter,\n renderingTools: this.#config.tools || {},\n introspection,\n adapterInfo: this.#config.adapter.formatInfo(adapterInfo),\n context: await generateBrief(introspection, this.#config.cache),\n userProfile: userProfileXml,\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: messages,\n onFinish: async ({ messages }) => {\n const userMessage = messages.at(-2);\n const botMessage = messages.at(-1);\n if (!userMessage || !botMessage) {\n throw new Error('Not implemented yet');\n }\n await this.#config.history.addMessage({\n id: v7(),\n chatId: params.chatId,\n role: userMessage.role,\n content: userMessage,\n });\n await this.#config.history.addMessage({\n id: v7(),\n chatId: params.chatId,\n role: botMessage.role,\n content: botMessage,\n });\n },\n });\n }\n}\nif (import.meta.main) {\n // const { DatabaseSync } = await import('node:sqlite');\n // const sqliteClient = new DatabaseSync('claude_creation.db', {\n // readOnly: true,\n // });\n // const adapter = new Sqlite({\n // execute: (sql) => sqliteClient.prepare(sql).all(),\n // });\n\n // console.log((await adapter.getTables()).map((t) => t.name));\n // console.log(await adapter.resolveTables(['ProductCategory']));\n\n // const text2sql = new Text2Sql({\n // instructions: teachings,\n // cache: new BriefCache('brief'),\n // history: new SqliteHistory('./text2sql_history.sqlite'),\n // adapter: new Sqlite({\n // execute: (sql) => sqliteClient.prepare(sql).all(),\n // }),\n // });\n\n // const sql = await text2sql.chat(\n // [\n // user(\n // 'What is trending in sales lately, last calenar year, monthly timeframe?',\n // ),\n // ],\n // {\n // userId: 'default',\n // chatId: '019a9b5a-f118-76a9-9dee-609e282c60b7',\n // },\n // );\n // await printer.readableStream(sql);\n}\n", "export interface Table {\n name: string;\n schema?: string;\n rawName?: string;\n columns: {\n name: string;\n type: string;\n kind?: 'LowCardinality';\n values?: string[];\n isPrimaryKey?: boolean;\n isIndexed?: boolean;\n stats?: ColumnStats;\n }[];\n rowCount?: number;\n sizeHint?: 'tiny' | 'small' | 'medium' | 'large' | 'huge';\n indexes?: TableIndex[];\n}\n\nexport interface TableIndex {\n name: string;\n columns: string[];\n unique?: boolean;\n primary?: boolean;\n type?: 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 host?: string;\n details?: Record<string, unknown>;\n}\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 type AdapterInfoProvider =\n | AdapterInfo\n | (() => Promise<AdapterInfo> | AdapterInfo);\n\nexport interface IntrospectOptions {\n onProgress?: OnProgress;\n}\n\nexport abstract class Adapter {\n abstract introspect(options?: IntrospectOptions): Promise<Introspection> | Introspection;\n\n abstract execute(sql: string): Promise<any[]> | any[];\n abstract validate(sql: string): Promise<string | void> | string | void;\n abstract info(): Promise<AdapterInfo> | AdapterInfo;\n abstract formatInfo(info: AdapterInfo): string;\n\n abstract getTables(): Promise<Table[]> | Table[];\n abstract getRelationships(): Promise<Relationship[]> | Relationship[];\n\n async resolveTables(filter: TablesFilter): Promise<string[]> {\n const allTables = await this.getTables();\n const relationships = await this.getRelationships();\n return getTablesWithRelated(allTables, relationships, filter);\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 {\n Adapter,\n type AdapterInfo,\n type AdapterInfoProvider,\n type IntrospectOptions,\n type Introspection,\n type OnProgress,\n type Relationship,\n type Table,\n type TablesFilter,\n applyTablesFilter,\n} from './adapter.ts';\n\nconst SQL_ERROR_MAP: Array<{\n pattern: RegExp;\n type: string;\n hint: string;\n}> = [\n {\n pattern: /^no such table: .+$/,\n type: 'MISSING_TABLE',\n hint: 'Check the database schema for the correct table name. The table you referenced does not exist.',\n },\n {\n pattern: /^no such column: .+$/,\n type: 'INVALID_COLUMN',\n hint: 'Check the table schema for correct column names. The column may not exist or is ambiguous (exists in multiple joined tables).',\n },\n {\n pattern: /^ambiguous column name: .+$/,\n type: 'INVALID_COLUMN',\n hint: 'Check the table schema for correct column names. The column may not exist or is ambiguous (exists in multiple joined tables).',\n },\n {\n pattern: /^near \".+\": syntax error$/,\n type: 'SYNTAX_ERROR',\n hint: 'There is a SQL syntax error. Review the query structure, keywords, and punctuation.',\n },\n {\n pattern: /^no tables specified$/,\n type: 'SYNTAX_ERROR',\n hint: 'There is a SQL syntax error. Review the query structure, keywords, and punctuation.',\n },\n {\n pattern: /^attempt to write a readonly database$/,\n type: 'CONSTRAINT_ERROR',\n hint: 'A database constraint was violated. This should not happen with read-only queries.',\n },\n];\n\ntype ExecuteFunction = (sql: string) => Promise<any> | any;\ntype ValidateFunction = (sql: string) => Promise<string | void> | string | void;\ntype IntrospectFunction = () => Promise<Introspection> | Introspection;\n\nexport type SqliteAdapterOptions = {\n execute: ExecuteFunction;\n validate?: ValidateFunction;\n introspect?: IntrospectFunction;\n info?: AdapterInfoProvider;\n tables?: TablesFilter;\n};\n\ntype TableNameRow = {\n name: string | null | undefined;\n};\n\ntype ColumnRow = {\n name: string | null | undefined;\n type: string | null | undefined;\n pk?: number | null | undefined;\n};\n\ntype IndexListRow = {\n seq?: number | null | undefined;\n name?: string | null | undefined;\n unique?: number | null | undefined;\n origin?: string | null | undefined;\n};\n\ntype IndexInfoRow = {\n seqno?: number | null | undefined;\n cid?: number | null | undefined;\n name?: string | null | undefined;\n};\ntype ForeignKeyRow = {\n id: number | null | undefined;\n table: string | null | undefined;\n from: string | null | undefined;\n to: string | null | undefined;\n};\n\nconst LOW_CARDINALITY_LIMIT = 20;\n\nexport function formatError(sql: string, error: unknown) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : typeof error === 'string'\n ? error\n : 'Unknown error occurred';\n const errorInfo = SQL_ERROR_MAP.find((it) => it.pattern.test(errorMessage));\n\n if (!errorInfo) {\n return {\n error: errorMessage,\n error_type: 'UNKNOWN_ERROR',\n suggestion: 'Review the query and try again',\n sql_attempted: sql,\n };\n }\n\n return {\n error: errorMessage,\n error_type: errorInfo.type,\n suggestion: errorInfo.hint,\n sql_attempted: sql,\n };\n}\n\nexport class Sqlite extends Adapter {\n #options: SqliteAdapterOptions;\n #introspection: Introspection | null = null;\n #info: AdapterInfo | null = null;\n\n constructor(options: SqliteAdapterOptions) {\n super();\n if (!options || typeof options.execute !== 'function') {\n throw new Error('Sqlite adapter requires an execute function.');\n }\n this.#options = options;\n }\n\n override async introspect(\n options?: IntrospectOptions,\n ): Promise<Introspection> {\n const onProgress = options?.onProgress;\n\n if (this.#introspection) {\n return this.#introspection;\n }\n\n if (this.#options.introspect) {\n this.#introspection = await this.#options.introspect();\n return this.#introspection;\n }\n\n const allTables = await this.#loadTables();\n const allRelationships = await this.#loadRelationships(\n allTables.map((t) => t.name),\n );\n const { tables, relationships } = this.#applyTablesFilter(\n allTables,\n allRelationships,\n );\n onProgress?.({\n phase: 'tables',\n message: `Loaded ${tables.length} tables`,\n total: tables.length,\n });\n\n onProgress?.({ phase: 'row_counts', message: 'Counting table rows...' });\n await this.#annotateRowCounts(tables, onProgress);\n\n onProgress?.({\n phase: 'column_stats',\n message: 'Collecting column statistics...',\n });\n await this.#annotateColumnStats(tables, onProgress);\n\n onProgress?.({ phase: 'indexes', message: 'Loading index information...' });\n await this.#annotateIndexes(tables, onProgress);\n\n onProgress?.({\n phase: 'low_cardinality',\n message: 'Identifying low cardinality columns...',\n });\n await this.#annotateLowCardinalityColumns(tables, onProgress);\n\n onProgress?.({\n phase: 'relationships',\n message: 'Loading foreign key relationships...',\n });\n\n this.#introspection = { tables, relationships };\n return this.#introspection;\n }\n\n override async execute(sql: string) {\n return this.#options.execute(sql);\n }\n\n override async validate(sql: string) {\n const validator: ValidateFunction =\n this.#options.validate ??\n (async (text: string) => {\n await this.#options.execute(`EXPLAIN ${text}`);\n });\n\n try {\n return await validator(sql);\n } catch (error) {\n return JSON.stringify(formatError(sql, error));\n }\n }\n\n override async info(): Promise<AdapterInfo> {\n if (this.#info) {\n return this.#info;\n }\n this.#info = await this.#resolveInfo();\n return this.#info;\n }\n\n override formatInfo(info: AdapterInfo): string {\n const lines = [`Dialect: ${info.dialect ?? 'unknown'}`];\n if (info.version) {\n lines.push(`Version: ${info.version}`);\n }\n if (info.database) {\n lines.push(`Database: ${info.database}`);\n }\n if (info.host) {\n lines.push(`Host: ${info.host}`);\n }\n if (info.details && Object.keys(info.details).length) {\n lines.push(`Details: ${JSON.stringify(info.details)}`);\n }\n return lines.join('\\n');\n }\n\n override async getTables(): Promise<Table[]> {\n const allTables = await this.#loadTables();\n const allRelationships = await this.#loadRelationships(\n allTables.map((t) => t.name),\n );\n return this.#applyTablesFilter(allTables, allRelationships).tables;\n }\n\n async #loadTables(): Promise<Table[]> {\n const rows = await this.#runQuery<{ name: string | null | undefined }>(\n `SELECT name FROM sqlite_master WHERE type='table' ORDER BY name`,\n );\n\n const tableNames = rows\n .map((row) => row.name)\n .filter(\n (name): name is string =>\n typeof name === 'string' && !name.startsWith('sqlite_'),\n );\n const tables = await Promise.all(\n tableNames.map(async (tableName) => {\n const columns = await this.#runQuery<ColumnRow>(\n `PRAGMA table_info(${this.#quoteIdentifier(tableName)})`,\n );\n\n return {\n name: tableName,\n rawName: tableName,\n columns: columns.map((col) => ({\n name: col.name ?? 'unknown',\n type: col.type ?? 'unknown',\n isPrimaryKey: (col.pk ?? 0) > 0,\n })),\n };\n }),\n );\n\n return tables;\n }\n\n async getRelationships(): Promise<Relationship[]> {\n const allTables = await this.#loadTables();\n const allRelationships = await this.#loadRelationships(\n allTables.map((t) => t.name),\n );\n return this.#applyTablesFilter(allTables, allRelationships).relationships;\n }\n\n async #loadRelationships(tableNames?: string[]): Promise<Relationship[]> {\n const names =\n tableNames ?? (await this.#loadTables()).map((table) => table.name);\n\n const relationshipGroups = await Promise.all(\n names.map(async (tableName) => {\n const rows = await this.#runQuery<ForeignKeyRow>(\n `PRAGMA foreign_key_list(${this.#quoteIdentifier(tableName)})`,\n );\n\n const groups = new Map<number, Relationship>();\n\n for (const row of rows) {\n if (\n row.id == null ||\n row.table == null ||\n row.from == null ||\n row.to == null\n ) {\n continue;\n }\n\n const id = Number(row.id);\n const existing = groups.get(id);\n if (!existing) {\n groups.set(id, {\n table: tableName,\n from: [String(row.from)],\n referenced_table: String(row.table),\n to: [String(row.to)],\n });\n } else {\n existing.from.push(String(row.from));\n existing.to.push(String(row.to));\n }\n }\n\n return Array.from(groups.values());\n }),\n );\n\n return relationshipGroups.flat();\n }\n\n async #annotateRowCounts(tables: Table[], onProgress?: OnProgress) {\n const total = tables.length;\n for (let i = 0; i < tables.length; i++) {\n const table = tables[i];\n const tableIdentifier = this.#formatTableIdentifier(table);\n onProgress?.({\n phase: 'row_counts',\n message: `Counting rows in ${table.name}...`,\n current: i + 1,\n total,\n });\n try {\n const rows = await this.#runQuery<{ count: number | string | bigint }>(\n `SELECT COUNT(*) as count FROM ${tableIdentifier}`,\n );\n const rowCount = this.#toNumber(rows[0]?.count);\n if (rowCount != null) {\n table.rowCount = rowCount;\n table.sizeHint = this.#classifyRowCount(rowCount);\n }\n } catch {\n continue;\n }\n }\n }\n\n async #annotateColumnStats(tables: Table[], onProgress?: OnProgress) {\n const total = tables.length;\n for (let i = 0; i < tables.length; i++) {\n const table = tables[i];\n const tableIdentifier = this.#formatTableIdentifier(table);\n onProgress?.({\n phase: 'column_stats',\n message: `Collecting stats for ${table.name}...`,\n current: i + 1,\n total,\n });\n for (const column of table.columns) {\n if (!this.#shouldCollectStats(column.type)) {\n continue;\n }\n const columnIdentifier = this.#quoteSqlIdentifier(column.name);\n const sql = `\n SELECT\n MIN(${columnIdentifier}) AS min_value,\n MAX(${columnIdentifier}) AS max_value,\n AVG(CASE WHEN ${columnIdentifier} IS NULL THEN 1.0 ELSE 0.0 END) AS null_fraction\n FROM ${tableIdentifier}\n `;\n try {\n const rows = await this.#runQuery<{\n min_value: unknown;\n max_value: unknown;\n null_fraction: number | string | null;\n }>(sql);\n if (!rows.length) {\n continue;\n }\n const min = this.#normalizeValue(rows[0]?.min_value);\n const max = this.#normalizeValue(rows[0]?.max_value);\n const nullFraction = this.#toNumber(rows[0]?.null_fraction);\n if (min != null || max != null || nullFraction != null) {\n column.stats = {\n min: min ?? undefined,\n max: max ?? undefined,\n nullFraction:\n nullFraction != null && Number.isFinite(nullFraction)\n ? Math.max(0, Math.min(1, nullFraction))\n : undefined,\n };\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n async #annotateIndexes(tables: Table[], onProgress?: OnProgress) {\n const total = tables.length;\n for (let i = 0; i < tables.length; i++) {\n const table = tables[i];\n const tableIdentifier = this.#quoteIdentifier(\n table.rawName ?? table.name,\n );\n onProgress?.({\n phase: 'indexes',\n message: `Loading indexes for ${table.name}...`,\n current: i + 1,\n total,\n });\n\n let indexes: Table['indexes'] = [];\n try {\n const indexList = await this.#runQuery<IndexListRow>(\n `PRAGMA index_list(${tableIdentifier})`,\n );\n indexes = await Promise.all(\n indexList\n .filter((index) => index.name)\n .map(async (index) => {\n const indexName = String(index.name);\n const indexInfo = await this.#runQuery<IndexInfoRow>(\n `PRAGMA index_info('${indexName.replace(/'/g, \"''\")}')`,\n );\n const columns = indexInfo\n .map((col) => col.name)\n .filter((name): name is string => Boolean(name));\n for (const columnName of columns) {\n const column = table.columns.find(\n (col) => col.name === columnName,\n );\n if (column) {\n column.isIndexed = true;\n }\n }\n return {\n name: indexName,\n columns,\n unique: index.unique === 1,\n primary: index.origin === 'pk',\n type: index.origin ?? undefined,\n };\n }),\n );\n } catch {\n indexes = [];\n }\n if (indexes.length) {\n table.indexes = indexes;\n }\n }\n }\n\n async #annotateLowCardinalityColumns(\n tables: Table[],\n onProgress?: OnProgress,\n ) {\n const total = tables.length;\n for (let i = 0; i < tables.length; i++) {\n const table = tables[i];\n const tableIdentifier = this.#formatTableIdentifier(table);\n onProgress?.({\n phase: 'low_cardinality',\n message: `Analyzing cardinality in ${table.name}...`,\n current: i + 1,\n total,\n });\n for (const column of table.columns) {\n const columnIdentifier = this.#quoteSqlIdentifier(column.name);\n // add one to the limit to detect if it exceeds the limit\n const limit = LOW_CARDINALITY_LIMIT + 1;\n const sql = `\n SELECT DISTINCT ${columnIdentifier} AS value\n FROM ${tableIdentifier}\n WHERE ${columnIdentifier} IS NOT NULL\n LIMIT ${limit}\n `;\n\n let rows: Array<{ value: unknown }> = [];\n try {\n rows = await this.#runQuery<{ value: unknown }>(sql);\n } catch {\n continue;\n }\n\n if (!rows.length || rows.length > LOW_CARDINALITY_LIMIT) {\n continue;\n }\n\n const values: string[] = [];\n let shouldSkip = false;\n for (const row of rows) {\n const formatted = this.#normalizeValue(row.value);\n if (formatted == null) {\n shouldSkip = true;\n break;\n }\n values.push(formatted);\n }\n\n if (shouldSkip || !values.length) {\n continue;\n }\n\n column.kind = 'LowCardinality';\n column.values = values;\n }\n }\n }\n\n #quoteIdentifier(name: string) {\n return `'${name.replace(/'/g, \"''\")}'`;\n }\n\n #quoteSqlIdentifier(identifier: string) {\n return `\"${identifier.replace(/\"/g, '\"\"')}\"`;\n }\n\n #applyTablesFilter(tables: Table[], relationships: Relationship[]) {\n return applyTablesFilter(tables, relationships, this.#options.tables);\n }\n\n #formatTableIdentifier(table: Table) {\n const name = table.rawName ?? table.name;\n if (table.schema) {\n return `${this.#quoteSqlIdentifier(table.schema)}.${this.#quoteSqlIdentifier(name)}`;\n }\n return this.#quoteSqlIdentifier(name);\n }\n\n #toNumber(value: unknown): number | null {\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 : null;\n }\n return null;\n }\n\n #classifyRowCount(count: number): Table['sizeHint'] {\n if (count < 100) {\n return 'tiny';\n }\n if (count < 1000) {\n return 'small';\n }\n if (count < 10000) {\n return 'medium';\n }\n if (count < 100000) {\n return 'large';\n }\n return 'huge';\n }\n\n #shouldCollectStats(type: string | undefined) {\n if (!type) {\n return false;\n }\n const normalized = type.toLowerCase();\n return /int|real|numeric|double|float|decimal|date|time|bool/.test(\n normalized,\n );\n }\n\n #normalizeValue(value: unknown): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n return String(value);\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {\n return value.toString('utf-8');\n }\n return null;\n }\n\n async #runQuery<Row>(sql: string): Promise<Row[]> {\n const result = await this.#options.execute(sql);\n\n if (Array.isArray(result)) {\n return result as Row[];\n }\n\n if (\n result &&\n typeof result === 'object' &&\n 'rows' in result &&\n Array.isArray((result as { rows?: unknown }).rows)\n ) {\n return (result as { rows: Row[] }).rows;\n }\n\n throw new Error(\n 'Sqlite adapter execute() must return an array of rows or an object with a rows array when introspecting.',\n );\n }\n\n async #resolveInfo(): Promise<AdapterInfo> {\n const { info } = this.#options;\n if (!info) {\n return { dialect: 'sqlite' };\n }\n if (typeof info === 'function') {\n return info();\n }\n return info;\n }\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { createUIMessageStream, tool } from 'ai';\nimport dedent from 'dedent';\nimport { 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';\nimport z from 'zod';\n\nimport {\n type StreamFunction,\n agent,\n generate,\n toState,\n user,\n} from '@deepagents/agent';\n\nimport { Adapter, type Introspection } from '../adapters/adapter.ts';\nimport { databaseSchemaPrompt } from '../prompt.ts';\n\nexport class BriefCache {\n public path: string;\n constructor(watermark: string) {\n const hash = createHash('md5').update(watermark).digest('hex');\n this.path = path.join(tmpdir(), `db-brief-${hash}.txt`);\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(brief: string) {\n return writeFile(this.path, brief, 'utf-8');\n }\n}\n\nconst briefAgent = agent<\n unknown,\n {\n introspection: Introspection;\n }\n>({\n name: 'db-brief-agent',\n model: groq('openai/gpt-oss-20b'),\n prompt: (state) => dedent`\n <identity>\n You are a database analyst expert. Your job is to understand what a database represents and provide business context about it.\n You have READ-ONLY access to the database.\n </identity>\n\n ${databaseSchemaPrompt(state!)}\n\n <instructions>\n Write a business context that helps another agent answer questions accurately.\n\n For EACH table, do queries ONE AT A TIME:\n 1. SELECT COUNT(*) to get row count\n 2. SELECT * LIMIT 3 to see sample data\n\n Then write a report with:\n - What business this database is for\n - For each table: purpose, row count, and example of what the data looks like\n\n Include concrete examples like \"Track prices are $0.99\", \"Customer names like 'Lu\\u00eds Gon\\u00e7alves'\", etc.\n\n Keep it 400-600 words, conversational style.\n </instructions>\n `,\n tools: {\n query_database: tool({\n description:\n 'Execute a SELECT query to explore the database and gather insights.',\n inputSchema: z.object({\n sql: z.string().describe('The SELECT query to execute'),\n purpose: z\n .string()\n .describe('What insight you are trying to gather with this query'),\n }),\n execute: ({ sql }, options) => {\n const state = toState<Adapter>(options);\n return state.execute(sql);\n },\n }),\n },\n});\n\nasync function runAndCache(introspection: Introspection, cache: BriefCache) {\n const { text } = await generate(\n briefAgent,\n [\n user(\n 'Please analyze the database and write a contextual report about what this database represents.',\n ),\n ],\n { introspection },\n );\n\n await cache.set(text);\n return text;\n}\n\nexport async function generateBrief(\n introspection: Introspection,\n cache: BriefCache,\n) {\n const brief = await cache.get();\n if (!brief) {\n return runAndCache(introspection, cache);\n }\n return brief;\n}\n\nexport function toBrief(forceRefresh = false): StreamFunction<\n {\n cache: BriefCache;\n introspection: Introspection;\n },\n { context: string }\n> {\n return (state, setState) => {\n return createUIMessageStream({\n execute: async ({ writer }) => {\n if (forceRefresh) {\n const brief = await runAndCache(state.introspection, state.cache);\n writer.write({\n type: 'data-brief-agent',\n data: {\n cache: 'forced',\n brief: brief,\n },\n });\n setState({ context: brief });\n } else {\n let brief = await state.cache.get();\n if (!brief) {\n writer.write({\n type: 'data-brief-agent',\n data: {\n cache: 'miss',\n },\n });\n brief = await runAndCache(state.introspection, state.cache);\n writer.write({\n type: 'data-brief-agent',\n data: {\n cache: 'new',\n brief: brief,\n },\n });\n } else {\n writer.write({\n type: 'data-brief-agent',\n data: {\n cache: 'hit',\n brief: brief,\n },\n });\n }\n }\n },\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 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 introspection: Introspection;\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 ${databaseSchemaPrompt(state!)}\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 dedent from 'dedent';\n\nimport { agent } from '@deepagents/agent';\n\ntype SynthesizerContext = {\n context?: string;\n};\n\nexport const synthesizerAgent = agent<unknown, SynthesizerContext>({\n name: 'synthesizer_agent',\n model: groq('openai/gpt-oss-20b'),\n handoffDescription:\n 'Use this tool to synthesizes the final user-facing response. This agent understands how the user interface works and can tailor the response accordingly.',\n prompt: (state) => {\n const contextInfo = state?.context ?? 'No additional context provided.';\n\n return dedent`\n <identity>\n You are a data insights companion helping users understand information using clear, everyday language.\n You communicate in a friendly, conversational manner.\n You only see the user's question and the results from internal systems. You do not know how those results were produced, so never reference technical systems or implementation details.\n </identity>\n\n <context>\n ${contextInfo}\n </context>\n\n <response-strategy>\n 1. Re-read the user's question, then inspect the <data> provided to understand what it represents.\n 2. Translate technical field names into friendly descriptions based on the domain context.\n 3. Explain the core insight in 2-4 sentences focused on what the data reveals.\n 4. When multiple records are present, highlight only the most relevant ones (max 5) with comparisons or rankings.\n 5. If data is empty or contains an error, state that plainly and suggest what to clarify or try next.\n 6. Close with an optional follow-up recommendation or next step based on the insights.\n </response-strategy>\n\n <guardrails>\n - Never mention technical implementation details, data structures, or internal systems.\n - Keep tone casual, confident, and insight-driven; do not narrate your process.\n - Base every statement strictly on the <data> provided plus the context - no speculation.\n </guardrails>\n `;\n },\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';\nimport { type GeneratedTeachable } from '../teach/teachables.ts';\n\nconst teachableSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('term'),\n name: z.string(),\n definition: z.string(),\n }),\n z.object({\n type: z.literal('hint'),\n text: z.string(),\n }),\n z.object({\n type: z.literal('guardrail'),\n rule: z.string(),\n reason: z.string().optional(),\n action: z.string().optional(),\n }),\n z.object({\n type: z.literal('explain'),\n concept: z.string(),\n explanation: z.string(),\n therefore: z.string().optional(),\n }),\n z.object({\n type: z.literal('example'),\n question: z.string(),\n sql: z.string(),\n note: z.string().optional(),\n }),\n z.object({\n type: z.literal('clarification'),\n when: z.string(),\n ask: z.string(),\n reason: z.string(),\n }),\n z.object({\n type: z.literal('workflow'),\n task: z.string(),\n steps: z.array(z.string()).min(2),\n triggers: z.array(z.string()).optional(),\n notes: z.string().optional(),\n }),\n z.object({\n type: z.literal('quirk'),\n issue: z.string(),\n workaround: z.string(),\n }),\n z.object({\n type: z.literal('styleGuide'),\n prefer: z.string(),\n never: z.string().optional(),\n always: z.string().optional(),\n }),\n z.object({\n type: z.literal('analogy'),\n concept: z.array(z.string()).min(2),\n relationship: z.string(),\n insight: z.string().optional(),\n therefore: z.string().optional(),\n pitfall: z.string().optional(),\n }),\n]) as z.ZodType<GeneratedTeachable>;\n\nexport const teachablesAuthorAgent = agent<\n { teachables: GeneratedTeachable[] },\n {\n introspection: Introspection;\n context?: string;\n adapterInfo?: string;\n }\n>({\n name: 'teachables-author',\n model: groq('openai/gpt-oss-20b'),\n output: z.object({\n teachables: z\n .array(teachableSchema)\n .min(3)\n .max(10)\n .describe(\n 'A concise, high-value set of teachables grounded in the provided schema.',\n ),\n }),\n prompt: (state) => dedent`\n ${thirdPersonPrompt()}\n\n <identity>\n You design \"teachables\" for a Text2SQL system. Teachables become structured XML instructions.\n Choose only high-impact items that improve accuracy, safety, or clarity for this database.\n </identity>\n\n ${databaseSchemaPrompt(state!)}\n\n <teachables_catalog>\n term: name + definition for domain vocabulary.\n hint: behavioral rule/constraint to apply by default.\n guardrail: hard safety/performance boundary with action and optional reason.\n explain: deeper concept metaphor/explanation (+ optional therefore).\n example: question + SQL (+ optional note).\n clarification: when/ask/reason to prompt the user before querying.\n workflow: task + ordered steps (+ optional triggers/notes).\n quirk: data edge case with workaround.\n styleGuide: prefer/never/always guidance for SQL output.\n analogy: comparison of two concepts with relationship (+ optional insight/therefore/pitfall).\n </teachables_catalog>\n\n <instructions>\n - Ground everything in the provided schema/context; do not invent tables/columns.\n - Prefer guardrails + clarifications for performance, safety, and ambiguity.\n - Use examples only when a clear, schema-valid pattern is evident.\n - Keep the set lean (3-10 items) and non-duplicative; combine overlapping ideas.\n - Return JSON that satisfies the output schema; do not wrap in prose.\n </instructions>\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 return value\n .replaceAll(/&/g, '&amp;')\n .replaceAll(/</g, '&lt;')\n .replaceAll(/>/g, '&gt;')\n .replaceAll(/\"/g, '&quot;')\n .replaceAll(/'/g, '&apos;');\n}\n", "import { indentBlock, leaf, list, wrapBlock } from './xml.ts';\n\nexport interface Teachables {\n type:\n | 'term'\n | 'hint'\n | 'guardrail'\n | 'explain'\n | 'example'\n | 'clarification'\n | 'workflow'\n | 'quirk'\n | 'styleGuide'\n | 'analogy'\n | 'user_profile';\n format: () => 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; sql: 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\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 format: () =>\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 format: () => 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 format: () =>\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 format: () =>\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.sql - The correct SQL query that answers 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 * sql: \"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 * sql: \"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 * sql: \"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 sql: string;\n note?: string;\n}): Teachables {\n const { question, sql, note } = input;\n return {\n type: 'example',\n format: () =>\n wrapBlock('example', [\n leaf('question', question),\n leaf('sql', sql),\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 format: () =>\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 format: () =>\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 format: () =>\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 format: () =>\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 format: () =>\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\nexport function toInstructions(...teachables: Teachables[]): 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 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.format().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 if (!sections.length) {\n return '';\n }\n\n const content = indentBlock(sections.join('\\n'), 2);\n return `<teachings>\\n${content}\\n</teachings>`;\n}\n\nconst SECTION_ORDER: Array<{ type: Teachables['type']; tag: string }> = [\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: 'example', tag: 'examples' },\n];\n\nexport function toTeachables(generated: GeneratedTeachable[]): Teachables[] {\n return generated.map((item) => {\n switch (item.type) {\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 sql: item.sql,\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 }\n });\n}\n\nexport function userProfile(input: {\n preferences: string;\n identity: string;\n working_context: string;\n}): Teachables {\n return {\n type: 'user_profile',\n format: () => {\n return '';\n },\n };\n}\n\n// userProfile({\n// identity:\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 { existsSync } from 'node:fs';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport path from 'node:path';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type UserProfileItem = {\n type: 'fact' | 'preference' | 'present';\n text: string;\n};\n\nexport type UserProfileData = {\n items: UserProfileItem[];\n lastUpdated: string;\n};\n\n// ============================================================================\n// Store Implementation\n// ============================================================================\n\nexport class UserProfileStore {\n private path: string;\n\n constructor(private userId: string) {\n // Sanitize userId to be safe for filenames\n const safeUserId = userId.replace(/[^a-z0-9]/gi, '_').toLowerCase();\n this.path = path.join(tmpdir(), `user-profile-${safeUserId}.json`);\n }\n\n /**\n * Retrieve the full user profile data.\n */\n async get(): Promise<UserProfileData> {\n if (existsSync(this.path)) {\n try {\n const content = await readFile(this.path, 'utf-8');\n return JSON.parse(content);\n } catch (error) {\n console.error('Failed to read user profile:', error);\n }\n }\n\n // Default empty profile\n return {\n items: [],\n lastUpdated: new Date().toISOString(),\n };\n }\n\n /**\n * Save the user profile data.\n */\n private async save(data: UserProfileData): Promise<void> {\n data.lastUpdated = new Date().toISOString();\n await writeFile(this.path, JSON.stringify(data, null, 2), 'utf-8');\n }\n\n /**\n * Add an item to the profile.\n */\n async add(type: UserProfileItem['type'], text: string): Promise<void> {\n const data = await this.get();\n\n // Check for exact duplicates\n const exists = data.items.some(\n (item) => item.type === type && item.text === text,\n );\n\n if (!exists) {\n data.items.push({ type, text });\n await this.save(data);\n }\n }\n\n /**\n * Remove a specific item from the profile.\n */\n async remove(type: UserProfileItem['type'], text: string): Promise<void> {\n const data = await this.get();\n\n const filtered = data.items.filter((item) => {\n return !(item.type === type && item.text === text);\n });\n\n await this.save({ ...data, items: filtered });\n }\n\n /**\n * Clear the entire profile.\n */\n async clear(): Promise<void> {\n await this.save({ items: [], lastUpdated: new Date().toISOString() });\n }\n\n /**\n * Get the formatted XML string for the system prompt.\n */\n async toXml(): Promise<string> {\n const data = await this.get();\n return toUserProfileXml(data.items);\n }\n}\n\n// ============================================================================\n// Formatter\n// ============================================================================\n\nexport function toUserProfileXml(items: UserProfileItem[]): string {\n if (items.length === 0) {\n return '';\n }\n\n const facts = items.filter((i) => i.type === 'fact');\n const preferences = items.filter((i) => i.type === 'preference');\n const present = items.filter((i) => i.type === 'present');\n\n const sections: string[] = [];\n\n // 1. Identity Section\n if (facts.length > 0) {\n const lines = facts.map((f) => `- ${f.text}`);\n sections.push(wrapBlock('identity', lines));\n }\n\n // 2. Preferences Section\n if (preferences.length > 0) {\n const lines = preferences.map((p) => `- ${p.text}`);\n sections.push(wrapBlock('preferences', lines));\n }\n\n // 3. Working Context Section\n if (present.length > 0) {\n const lines = present.map((c) => `- ${c.text}`);\n sections.push(wrapBlock('working_context', lines));\n }\n\n if (sections.length === 0) return '';\n\n return `<user_profile>\\n${indentBlock(sections.join('\\n'), 2)}\\n</user_profile>`;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction wrapBlock(tag: string, lines: string[]): string {\n if (lines.length === 0) return '';\n return `<${tag}>\\n${indentBlock(lines.join('\\n'), 2)}\\n</${tag}>`;\n}\n\nfunction indentBlock(text: string, spaces: number): string {\n const padding = ' '.repeat(spaces);\n return text\n .split('\\n')\n .map((line) => (line.length ? padding + line : padding))\n .join('\\n');\n}\n", "import {\n Adapter,\n type AdapterInfo,\n type AdapterInfoProvider,\n type IntrospectOptions,\n type Introspection,\n type OnProgress,\n type Relationship,\n type Table,\n type TableIndex,\n type TablesFilter,\n applyTablesFilter,\n} from './adapter.ts';\n\ntype ExecuteFunction = (sql: string) => Promise<any> | any;\ntype ValidateFunction = (sql: string) => Promise<string | void> | string | void;\ntype IntrospectFunction = () => Promise<Introspection> | Introspection;\n\nexport type PostgresAdapterOptions = {\n execute: ExecuteFunction;\n validate?: ValidateFunction;\n introspect?: IntrospectFunction;\n schemas?: string[];\n info?: AdapterInfoProvider;\n tables?: TablesFilter;\n};\n\ntype TableRow = {\n table_schema: string | null;\n table_name: string | null;\n column_name: string | null;\n data_type: string | null;\n};\n\ntype RelationshipRow = {\n table_schema: string | null;\n table_name: string | null;\n column_name: string | null;\n foreign_table_schema: string | null;\n foreign_table_name: string | null;\n foreign_column_name: string | null;\n constraint_name: string | null;\n};\n\ntype PrimaryKeyRow = {\n table_schema: string | null;\n table_name: string | null;\n column_name: string | null;\n};\n\ntype IndexRow = {\n table_schema: string | null;\n table_name: string | null;\n index_name: string | null;\n column_name: string | null;\n indisunique: boolean | null;\n indisprimary: boolean | null;\n indisclustered: boolean | null;\n method: string | null;\n};\n\nconst POSTGRES_ERROR_MAP: Record<string, { type: string; hint: string }> = {\n '42P01': {\n type: 'MISSING_TABLE',\n hint: 'Check the database schema for the correct table name. Include the schema prefix if necessary.',\n },\n '42703': {\n type: 'INVALID_COLUMN',\n hint: 'Verify the column exists on the referenced table and use table aliases to disambiguate.',\n },\n '42601': {\n type: 'SYNTAX_ERROR',\n hint: 'There is a SQL syntax error. Review keywords, punctuation, and the overall query shape.',\n },\n '42P10': {\n type: 'INVALID_COLUMN',\n hint: 'Columns referenced in GROUP BY/SELECT must exist. Double-check the column names and aliases.',\n },\n '42883': {\n type: 'INVALID_FUNCTION',\n hint: 'The function or operator you used is not recognized. Confirm its name and argument types.',\n },\n};\n\nconst LOW_CARDINALITY_LIMIT = 20;\n\nfunction isPostgresError(\n error: unknown,\n): error is { code?: string; message?: string } {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n typeof (error as { code?: unknown }).code === 'string'\n );\n}\n\nexport function formatPostgresError(sql: string, error: unknown) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : typeof error === 'string'\n ? error\n : 'Unknown error occurred';\n\n if (isPostgresError(error)) {\n const metadata = POSTGRES_ERROR_MAP[error.code ?? ''];\n if (metadata) {\n return {\n error: errorMessage,\n error_type: metadata.type,\n suggestion: metadata.hint,\n sql_attempted: sql,\n };\n }\n }\n\n return {\n error: errorMessage,\n error_type: 'UNKNOWN_ERROR',\n suggestion: 'Review the query and try again',\n sql_attempted: sql,\n };\n}\n\nexport class Postgres extends Adapter {\n #options: PostgresAdapterOptions;\n #introspection: Introspection | null = null;\n #info: AdapterInfo | null = null;\n\n constructor(options: PostgresAdapterOptions) {\n super();\n if (!options || typeof options.execute !== 'function') {\n throw new Error('Postgres adapter requires an execute function.');\n }\n this.#options = {\n ...options,\n schemas: options.schemas?.length ? options.schemas : undefined,\n };\n }\n\n override async introspect(options?: IntrospectOptions): Promise<Introspection> {\n const onProgress = options?.onProgress;\n\n if (this.#introspection) {\n return this.#introspection;\n }\n\n if (this.#options.introspect) {\n this.#introspection = await this.#options.introspect();\n return this.#introspection;\n }\n\n const allTables = await this.#loadTables();\n const allRelationships = await this.#loadRelationships();\n const { tables, relationships } = this.#applyTablesFilter(\n allTables,\n allRelationships,\n );\n onProgress?.({\n phase: 'tables',\n message: `Loaded ${tables.length} tables`,\n total: tables.length,\n });\n\n onProgress?.({ phase: 'row_counts', message: 'Counting table rows...' });\n await this.#annotateRowCounts(tables, onProgress);\n\n onProgress?.({ phase: 'primary_keys', message: 'Detecting primary keys...' });\n await this.#annotatePrimaryKeys(tables);\n onProgress?.({ phase: 'primary_keys', message: 'Primary keys annotated' });\n\n onProgress?.({ phase: 'indexes', message: 'Loading index information...' });\n await this.#annotateIndexes(tables);\n onProgress?.({ phase: 'indexes', message: 'Indexes annotated' });\n\n onProgress?.({ phase: 'column_stats', message: 'Collecting column statistics...' });\n await this.#annotateColumnStats(tables, onProgress);\n\n onProgress?.({ phase: 'low_cardinality', message: 'Identifying low cardinality columns...' });\n await this.#annotateLowCardinalityColumns(tables, onProgress);\n\n onProgress?.({\n phase: 'relationships',\n message: `Loaded ${relationships.length} relationships`,\n });\n\n this.#introspection = { tables, relationships };\n return this.#introspection;\n }\n\n override async execute(sql: string) {\n return this.#options.execute(sql);\n }\n\n override async validate(sql: string) {\n const validator: ValidateFunction =\n this.#options.validate ??\n (async (text: string) => {\n await this.#options.execute(`EXPLAIN ${text}`);\n });\n\n try {\n return await validator(sql);\n } catch (error) {\n return JSON.stringify(formatPostgresError(sql, error));\n }\n }\n\n override async info(): Promise<AdapterInfo> {\n if (this.#info) {\n return this.#info;\n }\n this.#info = await this.#resolveInfo();\n return this.#info;\n }\n\n override formatInfo(info: AdapterInfo): string {\n const lines = [`Dialect: ${info.dialect ?? 'unknown'}`];\n if (info.version) {\n lines.push(`Version: ${info.version}`);\n }\n if (info.database) {\n lines.push(`Database: ${info.database}`);\n }\n if (info.host) {\n lines.push(`Host: ${info.host}`);\n }\n if (info.details && Object.keys(info.details).length) {\n lines.push(`Details: ${JSON.stringify(info.details)}`);\n }\n return lines.join('\\n');\n }\n\n override async getTables(): Promise<Table[]> {\n const allTables = await this.#loadTables();\n const allRelationships = await this.#loadRelationships();\n return this.#applyTablesFilter(allTables, allRelationships).tables;\n }\n\n async #loadTables(): Promise<Table[]> {\n const rows = await this.#runIntrospectionQuery<TableRow>(`\n SELECT\n c.table_schema,\n c.table_name,\n c.column_name,\n c.data_type\n FROM information_schema.columns AS c\n JOIN information_schema.tables AS t\n ON c.table_schema = t.table_schema\n AND c.table_name = t.table_name\n WHERE t.table_type = 'BASE TABLE'\n ${this.#buildSchemaFilter('c.table_schema')}\n ORDER BY c.table_schema, c.table_name, c.ordinal_position\n `);\n\n const tables = new Map<string, Table>();\n\n for (const row of rows) {\n if (!row.table_name) {\n continue;\n }\n const schema = row.table_schema ?? 'public';\n const tableName = row.table_name;\n const qualifiedName = `${schema}.${tableName}`;\n const table = tables.get(qualifiedName) ?? {\n name: qualifiedName,\n schema,\n rawName: tableName,\n columns: [],\n };\n table.columns.push({\n name: row.column_name ?? 'unknown',\n type: row.data_type ?? 'unknown',\n });\n tables.set(qualifiedName, table);\n }\n\n return Array.from(tables.values());\n }\n\n async getRelationships(): Promise<Relationship[]> {\n const allTables = await this.#loadTables();\n const allRelationships = await this.#loadRelationships();\n return this.#applyTablesFilter(allTables, allRelationships).relationships;\n }\n\n async #loadRelationships(): Promise<Relationship[]> {\n const rows = await this.#runIntrospectionQuery<RelationshipRow>(`\n SELECT\n tc.constraint_name,\n tc.table_schema,\n tc.table_name,\n kcu.column_name,\n ccu.table_schema AS foreign_table_schema,\n ccu.table_name AS foreign_table_name,\n ccu.column_name AS foreign_column_name\n FROM information_schema.table_constraints AS tc\n JOIN information_schema.key_column_usage AS kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n JOIN information_schema.constraint_column_usage AS ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\n WHERE tc.constraint_type = 'FOREIGN KEY'\n ${this.#buildSchemaFilter('tc.table_schema')}\n ORDER BY tc.table_schema, tc.table_name, tc.constraint_name, kcu.ordinal_position\n `);\n\n const relationships = new Map<string, Relationship>();\n\n for (const row of rows) {\n if (!row.table_name || !row.foreign_table_name || !row.constraint_name) {\n continue;\n }\n\n const schema = row.table_schema ?? 'public';\n const referencedSchema = row.foreign_table_schema ?? 'public';\n const key = `${schema}.${row.table_name}:${row.constraint_name}`;\n\n const relationship = relationships.get(key) ?? {\n table: `${schema}.${row.table_name}`,\n from: [],\n referenced_table: `${referencedSchema}.${row.foreign_table_name}`,\n to: [],\n };\n\n relationship.from.push(row.column_name ?? 'unknown');\n relationship.to.push(row.foreign_column_name ?? 'unknown');\n\n relationships.set(key, relationship);\n }\n\n return Array.from(relationships.values());\n }\n\n async #annotateRowCounts(tables: Table[], onProgress?: OnProgress) {\n const total = tables.length;\n for (let i = 0; i < tables.length; i++) {\n const table = tables[i];\n const tableIdentifier = this.#formatQualifiedTableName(table);\n onProgress?.({\n phase: 'row_counts',\n message: `Counting rows in ${table.name}...`,\n current: i + 1,\n total,\n });\n try {\n const rows = await this.#runIntrospectionQuery<{\n count: number | string | bigint | null;\n }>(`SELECT COUNT(*) as count FROM ${tableIdentifier}`);\n const rowCount = this.#toNumber(rows[0]?.count);\n if (rowCount != null) {\n table.rowCount = rowCount;\n table.sizeHint = this.#classifyRowCount(rowCount);\n }\n } catch {\n continue;\n }\n }\n }\n\n async #annotatePrimaryKeys(tables: Table[]) {\n if (!tables.length) {\n return;\n }\n const tableMap = new Map(tables.map((table) => [table.name, table]));\n const rows = await this.#runIntrospectionQuery<PrimaryKeyRow>(`\n SELECT\n tc.table_schema,\n tc.table_name,\n kcu.column_name\n FROM information_schema.table_constraints AS tc\n JOIN information_schema.key_column_usage AS kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\n WHERE tc.constraint_type = 'PRIMARY KEY'\n ${this.#buildSchemaFilter('tc.table_schema')}\n `);\n for (const row of rows) {\n if (!row.table_name) {\n continue;\n }\n const schema = row.table_schema ?? 'public';\n const qualifiedName = `${schema}.${row.table_name}`;\n const table = tableMap.get(qualifiedName);\n if (!table) {\n continue;\n }\n const column = table.columns.find((col) => col.name === row.column_name);\n if (column) {\n column.isPrimaryKey = true;\n }\n }\n }\n\n async #annotateIndexes(tables: Table[]) {\n if (!tables.length) {\n return;\n }\n const tableMap = new Map(tables.map((table) => [table.name, table]));\n const rows = await this.#runIntrospectionQuery<IndexRow>(`\n SELECT\n n.nspname AS table_schema,\n t.relname AS table_name,\n i.relname AS index_name,\n a.attname AS column_name,\n ix.indisunique,\n ix.indisprimary,\n ix.indisclustered,\n am.amname AS method\n FROM pg_index ix\n JOIN pg_class t ON t.oid = ix.indrelid\n JOIN pg_namespace n ON n.oid = t.relnamespace\n JOIN pg_class i ON i.oid = ix.indexrelid\n JOIN pg_am am ON am.oid = i.relam\n LEFT JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS key(attnum, ordinality) ON TRUE\n LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = key.attnum\n WHERE t.relkind = 'r'\n ${this.#buildSchemaFilter('n.nspname')}\n ORDER BY n.nspname, t.relname, i.relname, key.ordinality\n `);\n\n const indexMap = new Map<string, TableIndex>();\n\n for (const row of rows) {\n if (!row.table_name || !row.index_name) {\n continue;\n }\n const schema = row.table_schema ?? 'public';\n const tableKey = `${schema}.${row.table_name}`;\n const table = tableMap.get(tableKey);\n if (!table) {\n continue;\n }\n const indexKey = `${tableKey}:${row.index_name}`;\n let index = indexMap.get(indexKey);\n if (!index) {\n index = {\n name: row.index_name,\n columns: [],\n unique: Boolean(row.indisunique ?? false),\n primary: Boolean(row.indisprimary ?? false),\n type: row.indisclustered ? 'clustered' : (row.method ?? undefined),\n };\n indexMap.set(indexKey, index);\n if (!table.indexes) {\n table.indexes = [];\n }\n table.indexes.push(index);\n }\n if (row.column_name) {\n index.columns.push(row.column_name);\n const column = table.columns.find(\n (col) => col.name === row.column_name,\n );\n if (column) {\n column.isIndexed = true;\n }\n }\n }\n }\n\n async #annotateColumnStats(tables: Table[], onProgress?: OnProgress) {\n if (!tables.length) {\n return;\n }\n const total = tables.length;\n for (let i = 0; i < tables.length; i++) {\n const table = tables[i];\n const tableIdentifier = this.#formatQualifiedTableName(table);\n onProgress?.({\n phase: 'column_stats',\n message: `Collecting stats for ${table.name}...`,\n current: i + 1,\n total,\n });\n for (const column of table.columns) {\n if (!this.#shouldCollectStats(column.type)) {\n continue;\n }\n const columnIdentifier = this.#quoteIdentifier(column.name);\n const sql = `\n SELECT\n MIN(${columnIdentifier})::text AS min_value,\n MAX(${columnIdentifier})::text AS max_value,\n AVG(CASE WHEN ${columnIdentifier} IS NULL THEN 1.0 ELSE 0.0 END)::float AS null_fraction\n FROM ${tableIdentifier}\n `;\n try {\n const rows = await this.#runIntrospectionQuery<{\n min_value: string | null;\n max_value: string | null;\n null_fraction: number | string | null;\n }>(sql);\n if (!rows.length) {\n continue;\n }\n const min = rows[0]?.min_value ?? undefined;\n const max = rows[0]?.max_value ?? undefined;\n const nullFraction = this.#toNumber(rows[0]?.null_fraction);\n if (min != null || max != null || nullFraction != null) {\n column.stats = {\n min,\n max,\n nullFraction:\n nullFraction != null && Number.isFinite(nullFraction)\n ? Math.max(0, Math.min(1, nullFraction))\n : undefined,\n };\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n async #annotateLowCardinalityColumns(tables: Table[], onProgress?: OnProgress) {\n const total = tables.length;\n for (let i = 0; i < tables.length; i++) {\n const table = tables[i];\n const tableIdentifier = this.#formatQualifiedTableName(table);\n onProgress?.({\n phase: 'low_cardinality',\n message: `Analyzing cardinality in ${table.name}...`,\n current: i + 1,\n total,\n });\n for (const column of table.columns) {\n const columnIdentifier = this.#quoteIdentifier(column.name);\n const limit = LOW_CARDINALITY_LIMIT + 1;\n const sql = `\n SELECT DISTINCT ${columnIdentifier} AS value\n FROM ${tableIdentifier}\n WHERE ${columnIdentifier} IS NOT NULL\n LIMIT ${limit}\n `;\n\n let rows: Array<{ value: unknown }> = [];\n try {\n rows = await this.#runIntrospectionQuery<{ value: unknown }>(sql);\n } catch {\n continue;\n }\n\n if (!rows.length || rows.length > LOW_CARDINALITY_LIMIT) {\n continue;\n }\n\n const values: string[] = [];\n let shouldSkip = false;\n for (const row of rows) {\n const formatted = this.#normalizeValue(row.value);\n if (formatted == null) {\n shouldSkip = true;\n break;\n }\n values.push(formatted);\n }\n\n if (shouldSkip || !values.length) {\n continue;\n }\n\n column.kind = 'LowCardinality';\n column.values = values;\n }\n }\n }\n\n #buildSchemaFilter(columnName: string) {\n if (this.#options.schemas && this.#options.schemas.length > 0) {\n const values = this.#options.schemas\n .map((schema) => `'${schema.replace(/'/g, \"''\")}'`)\n .join(', ');\n return `AND ${columnName} IN (${values})`;\n }\n\n return `AND ${columnName} NOT IN ('pg_catalog', 'information_schema')`;\n }\n\n async #runIntrospectionQuery<Row>(sql: string): Promise<Row[]> {\n const result = await this.#options.execute(sql);\n\n if (Array.isArray(result)) {\n return result as Row[];\n }\n\n if (\n result &&\n typeof result === 'object' &&\n 'rows' in result &&\n Array.isArray((result as { rows?: unknown }).rows)\n ) {\n return (result as { rows: Row[] }).rows;\n }\n\n throw new Error(\n 'Postgres adapter execute() must return an array of rows or an object with a rows array when introspecting.',\n );\n }\n\n #quoteIdentifier(name: string) {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n }\n\n #applyTablesFilter(tables: Table[], relationships: Relationship[]) {\n return applyTablesFilter(tables, relationships, this.#options.tables);\n }\n\n #formatQualifiedTableName(table: Table) {\n if (table.schema && table.rawName) {\n return `${this.#quoteIdentifier(table.schema)}.${this.#quoteIdentifier(table.rawName)}`;\n }\n\n if (table.name.includes('.')) {\n const [schemaPart, ...rest] = table.name.split('.');\n const tablePart = rest.join('.') || schemaPart;\n if (rest.length === 0) {\n return this.#quoteIdentifier(schemaPart);\n }\n return `${this.#quoteIdentifier(schemaPart)}.${this.#quoteIdentifier(tablePart)}`;\n }\n\n return this.#quoteIdentifier(table.name);\n }\n\n #toNumber(value: unknown): number | null {\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 : null;\n }\n return null;\n }\n\n #shouldCollectStats(type: string | undefined) {\n if (!type) {\n return false;\n }\n const normalized = type.toLowerCase();\n return /int|numeric|decimal|double|real|money|date|time|timestamp|bool/.test(\n normalized,\n );\n }\n\n #classifyRowCount(count: number): Table['sizeHint'] {\n if (count < 100) {\n return 'tiny';\n }\n if (count < 1000) {\n return 'small';\n }\n if (count < 10000) {\n return 'medium';\n }\n if (count < 100000) {\n return 'large';\n }\n return 'huge';\n }\n\n #normalizeValue(value: unknown): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n return String(value);\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {\n return value.toString('utf-8');\n }\n return null;\n }\n\n async #resolveInfo(): Promise<AdapterInfo> {\n const { info } = this.#options;\n if (!info) {\n return { dialect: 'postgresql' };\n }\n if (typeof info === 'function') {\n return info();\n }\n return info;\n }\n}\n", "import {\n Adapter,\n type AdapterInfo,\n type AdapterInfoProvider,\n type IntrospectOptions,\n type Introspection,\n type OnProgress,\n type Relationship,\n type Table,\n type TableIndex,\n type TablesFilter,\n applyTablesFilter,\n} from './adapter.ts';\n\ntype ExecuteFunction = (sql: string) => Promise<any> | any;\ntype ValidateFunction = (sql: string) => Promise<string | void> | string | void;\ntype IntrospectFunction = () => Promise<Introspection> | Introspection;\n\nexport type SqlServerAdapterOptions = {\n execute: ExecuteFunction;\n validate?: ValidateFunction;\n introspect?: IntrospectFunction;\n schemas?: string[];\n info?: AdapterInfoProvider;\n tables?: TablesFilter;\n};\n\ntype ColumnRow = {\n table_schema: string | null;\n table_name: string | null;\n column_name: string | null;\n data_type: string | null;\n};\n\ntype RelationshipRow = {\n constraint_name: string | null;\n table_schema: string | null;\n table_name: string | null;\n column_name: string | null;\n referenced_table_schema: string | null;\n referenced_table_name: string | null;\n referenced_column_name: string | null;\n};\n\ntype PrimaryKeyRow = {\n table_schema: string | null;\n table_name: string | null;\n column_name: string | null;\n};\n\ntype IndexRow = {\n schema_name: string | null;\n table_name: string | null;\n index_name: string | null;\n column_name: string | null;\n is_unique: boolean | number | null;\n is_primary_key: boolean | number | null;\n type_desc: string | null;\n is_included_column: boolean | number | null;\n};\n\nconst SQL_SERVER_ERROR_MAP: Record<string, { type: string; hint: string }> = {\n '208': {\n type: 'MISSING_TABLE',\n hint: 'Check that the table exists and include the schema prefix (e.g., dbo.TableName).',\n },\n '207': {\n type: 'INVALID_COLUMN',\n hint: 'Verify the column exists on the table and that any aliases are referenced correctly.',\n },\n '156': {\n type: 'SYNTAX_ERROR',\n hint: 'There is a SQL syntax error. Review keywords, punctuation, and clauses such as GROUP BY.',\n },\n '4104': {\n type: 'INVALID_COLUMN',\n hint: 'Columns must be qualified with table aliases when ambiguous. Double-check join aliases.',\n },\n '1934': {\n type: 'CONSTRAINT_ERROR',\n hint: 'The query violates a constraint. Re-check join logic and filtering.',\n },\n};\n\nconst LOW_CARDINALITY_LIMIT = 20;\n\nfunction getErrorCode(error: unknown) {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'number' in error &&\n typeof (error as { number?: unknown }).number === 'number'\n ) {\n return String((error as { number: number }).number);\n }\n\n if (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n typeof (error as { code?: unknown }).code === 'string'\n ) {\n return (error as { code: string }).code;\n }\n\n return null;\n}\n\nexport function formatSqlServerError(sql: string, error: unknown) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : typeof error === 'string'\n ? error\n : 'Unknown error occurred';\n\n const code = getErrorCode(error);\n const metadata = code ? SQL_SERVER_ERROR_MAP[code] : undefined;\n\n if (metadata) {\n return {\n error: errorMessage,\n error_type: metadata.type,\n suggestion: metadata.hint,\n sql_attempted: sql,\n };\n }\n\n return {\n error: errorMessage,\n error_type: 'UNKNOWN_ERROR',\n suggestion: 'Review the query and try again',\n sql_attempted: sql,\n };\n}\n\nexport class SqlServer extends Adapter {\n #options: SqlServerAdapterOptions;\n #introspection: Introspection | null = null;\n #info: AdapterInfo | null = null;\n\n constructor(options: SqlServerAdapterOptions) {\n super();\n if (!options || typeof options.execute !== 'function') {\n throw new Error('SqlServer adapter requires an execute function.');\n }\n this.#options = {\n ...options,\n schemas: options.schemas?.length ? options.schemas : undefined,\n };\n }\n\n override async introspect(options?: IntrospectOptions): Promise<Introspection> {\n const onProgress = options?.onProgress;\n\n if (this.#introspection) {\n return this.#introspection;\n }\n\n if (this.#options.introspect) {\n this.#introspection = await this.#options.introspect();\n return this.#introspection;\n }\n\n const allTables = await this.#loadTables();\n const allRelationships = await this.#loadRelationships();\n const { tables, relationships } = this.#applyTablesFilter(\n allTables,\n allRelationships,\n );\n onProgress?.({\n phase: 'tables',\n message: `Loaded ${tables.length} tables`,\n total: tables.length,\n });\n\n onProgress?.({ phase: 'row_counts', message: 'Counting table rows...' });\n await this.#annotateRowCounts(tables, onProgress);\n\n onProgress?.({ phase: 'primary_keys', message: 'Detecting primary keys...' });\n await this.#annotatePrimaryKeys(tables);\n onProgress?.({ phase: 'primary_keys', message: 'Primary keys annotated' });\n\n onProgress?.({ phase: 'indexes', message: 'Loading index information...' });\n await this.#annotateIndexes(tables);\n onProgress?.({ phase: 'indexes', message: 'Indexes annotated' });\n\n onProgress?.({ phase: 'column_stats', message: 'Collecting column statistics...' });\n await this.#annotateColumnStats(tables, onProgress);\n\n onProgress?.({ phase: 'low_cardinality', message: 'Identifying low cardinality columns...' });\n await this.#annotateLowCardinalityColumns(tables, onProgress);\n\n onProgress?.({\n phase: 'relationships',\n message: `Loaded ${relationships.length} relationships`,\n });\n\n this.#introspection = { tables, relationships };\n return this.#introspection;\n }\n\n override async execute(sql: string) {\n return this.#options.execute(sql);\n }\n\n override async validate(sql: string) {\n const validator: ValidateFunction =\n this.#options.validate ??\n (async (text: string) => {\n await this.#options.execute(\n `SET PARSEONLY ON; ${text}; SET PARSEONLY OFF;`,\n );\n });\n\n try {\n return await validator(sql);\n } catch (error) {\n return JSON.stringify(formatSqlServerError(sql, error));\n }\n }\n\n override async info(): Promise<AdapterInfo> {\n if (this.#info) {\n return this.#info;\n }\n this.#info = await this.#resolveInfo();\n return this.#info;\n }\n\n override formatInfo(info: AdapterInfo): string {\n const lines = [`Dialect: ${info.dialect ?? 'unknown'}`];\n if (info.version) {\n lines.push(`Version: ${info.version}`);\n }\n if (info.database) {\n lines.push(`Database: ${info.database}`);\n }\n if (info.host) {\n lines.push(`Host: ${info.host}`);\n }\n if (info.details && Object.keys(info.details).length) {\n lines.push(`Details: ${JSON.stringify(info.details)}`);\n }\n return lines.join('\\n');\n }\n\n override async getTables(): Promise<Table[]> {\n const allTables = await this.#loadTables();\n const allRelationships = await this.#loadRelationships();\n return this.#applyTablesFilter(allTables, allRelationships).tables;\n }\n\n async #loadTables(): Promise<Table[]> {\n const rows = await this.#runIntrospectionQuery<ColumnRow>(`\n SELECT\n c.TABLE_SCHEMA AS table_schema,\n c.TABLE_NAME AS table_name,\n c.COLUMN_NAME AS column_name,\n c.DATA_TYPE AS data_type\n FROM INFORMATION_SCHEMA.COLUMNS AS c\n JOIN INFORMATION_SCHEMA.TABLES AS t\n ON c.TABLE_SCHEMA = t.TABLE_SCHEMA\n AND c.TABLE_NAME = t.TABLE_NAME\n WHERE t.TABLE_TYPE = 'BASE TABLE'\n ${this.#buildSchemaFilter('c.TABLE_SCHEMA')}\n ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.ORDINAL_POSITION\n `);\n\n const tables = new Map<string, Table>();\n\n for (const row of rows) {\n if (!row.table_name) {\n continue;\n }\n const schema = row.table_schema ?? 'dbo';\n const tableName = row.table_name;\n const qualifiedName = `${schema}.${tableName}`;\n\n const table = tables.get(qualifiedName) ?? {\n name: qualifiedName,\n schema,\n rawName: tableName,\n columns: [],\n };\n\n table.columns.push({\n name: row.column_name ?? 'unknown',\n type: row.data_type ?? 'unknown',\n });\n\n tables.set(qualifiedName, table);\n }\n\n return Array.from(tables.values());\n }\n\n override async getRelationships(): Promise<Relationship[]> {\n const allTables = await this.#loadTables();\n const allRelationships = await this.#loadRelationships();\n return this.#applyTablesFilter(allTables, allRelationships).relationships;\n }\n\n async #loadRelationships(): Promise<Relationship[]> {\n const rows = await this.#runIntrospectionQuery<RelationshipRow>(`\n SELECT\n fk.CONSTRAINT_NAME AS constraint_name,\n fk.TABLE_SCHEMA AS table_schema,\n fk.TABLE_NAME AS table_name,\n fk.COLUMN_NAME AS column_name,\n pk.TABLE_SCHEMA AS referenced_table_schema,\n pk.TABLE_NAME AS referenced_table_name,\n pk.COLUMN_NAME AS referenced_column_name\n FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS rc\n JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS fk\n ON fk.CONSTRAINT_NAME = rc.CONSTRAINT_NAME\n JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS pk\n ON pk.CONSTRAINT_NAME = rc.UNIQUE_CONSTRAINT_NAME\n AND pk.ORDINAL_POSITION = fk.ORDINAL_POSITION\n WHERE 1 = 1\n ${this.#buildSchemaFilter('fk.TABLE_SCHEMA')}\n ORDER BY fk.TABLE_SCHEMA, fk.TABLE_NAME, fk.CONSTRAINT_NAME, fk.ORDINAL_POSITION\n `);\n\n const relationships = new Map<string, Relationship>();\n\n for (const row of rows) {\n if (\n !row.constraint_name ||\n !row.table_name ||\n !row.referenced_table_name\n ) {\n continue;\n }\n\n const schema = row.table_schema ?? 'dbo';\n const referencedSchema = row.referenced_table_schema ?? 'dbo';\n const key = `${schema}.${row.table_name}:${row.constraint_name}`;\n\n const relationship = relationships.get(key) ?? {\n table: `${schema}.${row.table_name}`,\n from: [],\n referenced_table: `${referencedSchema}.${row.referenced_table_name}`,\n to: [],\n };\n\n relationship.from.push(row.column_name ?? 'unknown');\n relationship.to.push(row.referenced_column_name ?? 'unknown');\n\n relationships.set(key, relationship);\n }\n\n return Array.from(relationships.values());\n }\n\n async #annotateRowCounts(tables: Table[], onProgress?: OnProgress) {\n const total = tables.length;\n for (let i = 0; i < tables.length; i++) {\n const table = tables[i];\n const tableIdentifier = this.#formatQualifiedTableName(table);\n onProgress?.({\n phase: 'row_counts',\n message: `Counting rows in ${table.name}...`,\n current: i + 1,\n total,\n });\n try {\n const rows = await this.#runIntrospectionQuery<{\n count: number | string | bigint | null;\n }>(`SELECT COUNT(*) as count FROM ${tableIdentifier}`);\n const rowCount = this.#toNumber(rows[0]?.count);\n if (rowCount != null) {\n table.rowCount = rowCount;\n table.sizeHint = this.#classifyRowCount(rowCount);\n }\n } catch {\n continue;\n }\n }\n }\n\n async #annotatePrimaryKeys(tables: Table[]) {\n if (!tables.length) {\n return;\n }\n const tableMap = new Map(tables.map((table) => [table.name, table]));\n const rows = await this.#runIntrospectionQuery<PrimaryKeyRow>(`\n SELECT\n kc.TABLE_SCHEMA AS table_schema,\n kc.TABLE_NAME AS table_name,\n kc.COLUMN_NAME AS column_name\n FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc\n JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS kc\n ON tc.CONSTRAINT_NAME = kc.CONSTRAINT_NAME\n AND tc.TABLE_SCHEMA = kc.TABLE_SCHEMA\n WHERE tc.CONSTRAINT_TYPE = 'PRIMARY KEY'\n ${this.#buildSchemaFilter('kc.TABLE_SCHEMA')}\n `);\n for (const row of rows) {\n if (!row.table_name || !row.column_name) {\n continue;\n }\n const schema = row.table_schema ?? 'dbo';\n const tableKey = `${schema}.${row.table_name}`;\n const table = tableMap.get(tableKey);\n if (!table) {\n continue;\n }\n const column = table.columns.find((col) => col.name === row.column_name);\n if (column) {\n column.isPrimaryKey = true;\n }\n }\n }\n\n async #annotateIndexes(tables: Table[]) {\n if (!tables.length) {\n return;\n }\n const tableMap = new Map(tables.map((table) => [table.name, table]));\n const rows = await this.#runIntrospectionQuery<IndexRow>(`\n SELECT\n sch.name AS schema_name,\n t.name AS table_name,\n ind.name AS index_name,\n col.name AS column_name,\n ind.is_unique,\n ind.is_primary_key,\n ind.type_desc,\n ic.is_included_column\n FROM sys.indexes AS ind\n JOIN sys.tables AS t ON ind.object_id = t.object_id\n JOIN sys.schemas AS sch ON t.schema_id = sch.schema_id\n JOIN sys.index_columns AS ic\n ON ind.object_id = ic.object_id\n AND ind.index_id = ic.index_id\n JOIN sys.columns AS col\n ON ic.object_id = col.object_id\n AND ic.column_id = col.column_id\n WHERE ind.is_hypothetical = 0\n AND ind.name IS NOT NULL\n ${this.#buildSchemaFilter('sch.name')}\n ORDER BY sch.name, t.name, ind.name, ic.key_ordinal\n `);\n\n const indexMap = new Map<string, TableIndex>();\n\n for (const row of rows) {\n if (!row.table_name || !row.index_name) {\n continue;\n }\n const schema = row.schema_name ?? 'dbo';\n const tableKey = `${schema}.${row.table_name}`;\n const table = tableMap.get(tableKey);\n if (!table) {\n continue;\n }\n const indexKey = `${tableKey}:${row.index_name}`;\n let index = indexMap.get(indexKey);\n if (!index) {\n index = {\n name: row.index_name,\n columns: [],\n unique: Boolean(row.is_unique),\n primary: Boolean(row.is_primary_key),\n type: row.type_desc ?? undefined,\n };\n indexMap.set(indexKey, index);\n if (!table.indexes) {\n table.indexes = [];\n }\n table.indexes.push(index);\n }\n if (row.is_included_column) {\n continue;\n }\n if (row.column_name) {\n index.columns.push(row.column_name);\n const column = table.columns.find(\n (col) => col.name === row.column_name,\n );\n if (column) {\n column.isIndexed = true;\n }\n }\n }\n }\n\n async #annotateColumnStats(tables: Table[], onProgress?: OnProgress) {\n if (!tables.length) {\n return;\n }\n const total = tables.length;\n for (let i = 0; i < tables.length; i++) {\n const table = tables[i];\n const tableIdentifier = this.#formatQualifiedTableName(table);\n onProgress?.({\n phase: 'column_stats',\n message: `Collecting stats for ${table.name}...`,\n current: i + 1,\n total,\n });\n for (const column of table.columns) {\n if (!this.#shouldCollectStats(column.type)) {\n continue;\n }\n const columnIdentifier = this.#quoteIdentifier(column.name);\n const sql = `\n SELECT\n CONVERT(NVARCHAR(4000), MIN(${columnIdentifier})) AS min_value,\n CONVERT(NVARCHAR(4000), MAX(${columnIdentifier})) AS max_value,\n AVG(CASE WHEN ${columnIdentifier} IS NULL THEN 1.0 ELSE 0.0 END) AS null_fraction\n FROM ${tableIdentifier}\n `;\n try {\n const rows = await this.#runIntrospectionQuery<{\n min_value: string | null;\n max_value: string | null;\n null_fraction: number | string | null;\n }>(sql);\n if (!rows.length) {\n continue;\n }\n const nullFraction = this.#toNumber(rows[0]?.null_fraction);\n if (\n rows[0]?.min_value != null ||\n rows[0]?.max_value != null ||\n nullFraction != null\n ) {\n column.stats = {\n min: rows[0]?.min_value ?? undefined,\n max: rows[0]?.max_value ?? undefined,\n nullFraction:\n nullFraction != null && Number.isFinite(nullFraction)\n ? Math.max(0, Math.min(1, nullFraction))\n : undefined,\n };\n }\n } catch {\n continue;\n }\n }\n }\n }\n\n async #annotateLowCardinalityColumns(tables: Table[], onProgress?: OnProgress) {\n const total = tables.length;\n for (let i = 0; i < tables.length; i++) {\n const table = tables[i];\n const tableIdentifier = this.#formatQualifiedTableName(table);\n onProgress?.({\n phase: 'low_cardinality',\n message: `Analyzing cardinality in ${table.name}...`,\n current: i + 1,\n total,\n });\n for (const column of table.columns) {\n const columnIdentifier = this.#quoteIdentifier(column.name);\n const limit = LOW_CARDINALITY_LIMIT + 1;\n const sql = `\n SELECT DISTINCT TOP (${limit}) ${columnIdentifier} AS value\n FROM ${tableIdentifier}\n WHERE ${columnIdentifier} IS NOT NULL\n `;\n\n let rows: Array<{ value: unknown }> = [];\n try {\n rows = await this.#runIntrospectionQuery<{ value: unknown }>(sql);\n } catch {\n continue;\n }\n\n if (!rows.length || rows.length > LOW_CARDINALITY_LIMIT) {\n continue;\n }\n\n const values: string[] = [];\n let shouldSkip = false;\n for (const row of rows) {\n const formatted = this.#normalizeValue(row.value);\n if (formatted == null) {\n shouldSkip = true;\n break;\n }\n values.push(formatted);\n }\n\n if (shouldSkip || !values.length) {\n continue;\n }\n\n column.kind = 'LowCardinality';\n column.values = values;\n }\n }\n }\n\n #buildSchemaFilter(columnName: string) {\n if (this.#options.schemas && this.#options.schemas.length > 0) {\n const values = this.#options.schemas\n .map((schema) => `'${schema.replace(/'/g, \"''\")}'`)\n .join(', ');\n return `AND ${columnName} IN (${values})`;\n }\n\n return `AND ${columnName} NOT IN ('INFORMATION_SCHEMA', 'sys')`;\n }\n\n async #runIntrospectionQuery<Row>(sql: string): Promise<Row[]> {\n const result = await this.#options.execute(sql);\n\n if (Array.isArray(result)) {\n return result as Row[];\n }\n\n if (result && typeof result === 'object') {\n if (\n 'rows' in result &&\n Array.isArray((result as { rows?: unknown }).rows)\n ) {\n return (result as { rows: Row[] }).rows;\n }\n\n if (\n 'recordset' in result &&\n Array.isArray((result as { recordset?: unknown }).recordset)\n ) {\n return (result as { recordset: Row[] }).recordset;\n }\n\n if (\n 'recordsets' in result &&\n Array.isArray((result as { recordsets?: unknown }).recordsets) &&\n Array.isArray((result as { recordsets: unknown[] }).recordsets[0])\n ) {\n return (result as { recordsets: Row[][] }).recordsets[0];\n }\n }\n\n throw new Error(\n 'SqlServer adapter execute() must return an array of rows or an object with rows/recordset properties when introspecting.',\n );\n }\n\n #quoteIdentifier(name: string) {\n return `[${name.replace(/]/g, ']]')}]`;\n }\n\n #applyTablesFilter(tables: Table[], relationships: Relationship[]) {\n return applyTablesFilter(tables, relationships, this.#options.tables);\n }\n\n #formatQualifiedTableName(table: Table) {\n if (table.schema && table.rawName) {\n return `${this.#quoteIdentifier(table.schema)}.${this.#quoteIdentifier(table.rawName)}`;\n }\n\n if (table.name.includes('.')) {\n const [schemaPart, ...rest] = table.name.split('.');\n const tablePart = rest.join('.') || schemaPart;\n if (rest.length === 0) {\n return this.#quoteIdentifier(schemaPart);\n }\n return `${this.#quoteIdentifier(schemaPart)}.${this.#quoteIdentifier(tablePart)}`;\n }\n\n return this.#quoteIdentifier(table.name);\n }\n\n #toNumber(value: unknown): number | null {\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 : null;\n }\n return null;\n }\n\n #classifyRowCount(count: number): Table['sizeHint'] {\n if (count < 100) {\n return 'tiny';\n }\n if (count < 1000) {\n return 'small';\n }\n if (count < 10000) {\n return 'medium';\n }\n if (count < 100000) {\n return 'large';\n }\n return 'huge';\n }\n\n #shouldCollectStats(type: string | undefined) {\n if (!type) {\n return false;\n }\n const normalized = type.toLowerCase();\n return /int|numeric|decimal|float|real|money|date|time|timestamp|bool/.test(\n normalized,\n );\n }\n\n #normalizeValue(value: unknown): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number' || typeof value === 'bigint') {\n return String(value);\n }\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {\n return value.toString('utf-8');\n }\n return null;\n }\n\n async #resolveInfo(): Promise<AdapterInfo> {\n const { info } = this.#options;\n if (!info) {\n return { dialect: 'sqlserver' };\n }\n if (typeof info === 'function') {\n return info();\n }\n return info;\n }\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"],
5
+ "mappings": ";AAAA,SAAS,YAAY;AACrB,SAAoB,YAAY;AAChC,OAAO,OAAO;AAEd;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;;;ACVhC,OAAO,eAAe;AAItB,IAAM,iBAAiB,CAAC,kBAAiC;AACvD,MAAI,CAAC,cAAc,OAAO,QAAQ;AAChC,WAAO;AAAA,EACT;AAEA,SAAO,cAAc,OAClB,IAAI,CAAC,UAA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C5D,UAAM,YAAY,QAAQ,YACtB,QAAQ,UAAU,YAAY,KAC9B,oBAAI,KAAK,GAAE,YAAY;AAC3B,SAAK,IACF;AAAA,MACC;AAAA,IACF,EACC;AAAA,MACC,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR;AAAA,MACA,KAAK,UAAU,QAAQ,OAAO;AAAA,IAChC;AAAA,EACJ;AAAA,EAEA,MAAM,cAAc,SAAgD;AAClE,UAAM,YAAY,QAAQ,YACtB,QAAQ,UAAU,YAAY,KAC9B,oBAAI,KAAK,GAAE,YAAY;AAC3B,SAAK,IACF;AAAA,MACC;AAAA;AAAA,IAEF,EACC;AAAA,MACC,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR;AAAA,MACA,KAAK,UAAU,QAAQ,OAAO;AAAA,IAChC;AACF,WAAO;AAAA,MACL,GAAG;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,cAAc,WAAkC;AACpD,SAAK,IAAI,QAAQ,mCAAmC,EAAE,IAAI,SAAS;AAAA,EACrE;AACF;;;AE9IO,IAAM,kBAAN,cAA8B,cAAc;AAAA,EACjD,cAAc;AACZ,UAAM,UAAU;AAAA,EAClB;AACF;",
6
+ "names": ["tool", "dedent", "z", "generate", "user", "groq", "tool", "z", "agent", "toState", "agent", "groq", "tool", "z", "toState", "groq", "dedent", "z", "agent", "groq", "dedent", "z", "agent", "agent", "groq", "z", "dedent", "groq", "dedent", "agent", "groq", "dedent", "z", "agent", "thirdPersonPrompt", "z", "agent", "groq", "dedent", "thirdPersonPrompt", "existsSync", "readFile", "writeFile", "tmpdir", "path", "wrapBlock", "indentBlock", "stream", "generate", "user", "dedent", "tool", "z", "messages", "LOW_CARDINALITY_LIMIT", "LOW_CARDINALITY_LIMIT", "path"]
7
+ }
@@ -0,0 +1,80 @@
1
+ export interface Table {
2
+ name: string;
3
+ schema?: string;
4
+ rawName?: string;
5
+ columns: {
6
+ name: string;
7
+ type: string;
8
+ kind?: 'LowCardinality';
9
+ values?: string[];
10
+ isPrimaryKey?: boolean;
11
+ isIndexed?: boolean;
12
+ stats?: ColumnStats;
13
+ }[];
14
+ rowCount?: number;
15
+ sizeHint?: 'tiny' | 'small' | 'medium' | 'large' | 'huge';
16
+ indexes?: TableIndex[];
17
+ }
18
+ export interface TableIndex {
19
+ name: string;
20
+ columns: string[];
21
+ unique?: boolean;
22
+ primary?: boolean;
23
+ type?: string;
24
+ }
25
+ export interface ColumnStats {
26
+ min?: string;
27
+ max?: string;
28
+ nullFraction?: number;
29
+ }
30
+ export type Relationship = {
31
+ table: string;
32
+ from: string[];
33
+ referenced_table: string;
34
+ to: string[];
35
+ };
36
+ export type TablesFilter = string[] | RegExp;
37
+ export interface Introspection {
38
+ tables: Table[];
39
+ relationships: Relationship[];
40
+ }
41
+ export interface AdapterInfo {
42
+ dialect: string;
43
+ version?: string;
44
+ database?: string;
45
+ host?: string;
46
+ details?: Record<string, unknown>;
47
+ }
48
+ export type IntrospectionPhase = 'tables' | 'row_counts' | 'primary_keys' | 'indexes' | 'column_stats' | 'low_cardinality' | 'relationships';
49
+ export interface IntrospectionProgress {
50
+ phase: IntrospectionPhase;
51
+ message: string;
52
+ current?: number;
53
+ total?: number;
54
+ }
55
+ export type OnProgress = (progress: IntrospectionProgress) => void;
56
+ export type AdapterInfoProvider = AdapterInfo | (() => Promise<AdapterInfo> | AdapterInfo);
57
+ export interface IntrospectOptions {
58
+ onProgress?: OnProgress;
59
+ }
60
+ export declare abstract class Adapter {
61
+ abstract introspect(options?: IntrospectOptions): Promise<Introspection> | Introspection;
62
+ abstract execute(sql: string): Promise<any[]> | any[];
63
+ abstract validate(sql: string): Promise<string | void> | string | void;
64
+ abstract info(): Promise<AdapterInfo> | AdapterInfo;
65
+ abstract formatInfo(info: AdapterInfo): string;
66
+ abstract getTables(): Promise<Table[]> | Table[];
67
+ abstract getRelationships(): Promise<Relationship[]> | Relationship[];
68
+ resolveTables(filter: TablesFilter): Promise<string[]>;
69
+ }
70
+ export declare function filterTablesByName<T extends {
71
+ name: string;
72
+ }>(tables: T[], filter: TablesFilter | undefined): T[];
73
+ export declare function filterRelationshipsByTables(relationships: Relationship[], tableNames: Set<string> | undefined): Relationship[];
74
+ export declare function applyTablesFilter(tables: Table[], relationships: Relationship[], filter: TablesFilter | undefined): {
75
+ tables: Table[];
76
+ relationships: Relationship[];
77
+ };
78
+ export declare function matchesFilter(tableName: string, filter: TablesFilter): boolean;
79
+ export declare function getTablesWithRelated(allTables: Table[], relationships: Relationship[], filter: TablesFilter): string[];
80
+ //# sourceMappingURL=adapter.d.ts.map