@deepagents/text2sql 4.3.0 → 6.0.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 (95) hide show
  1. package/CLICKHOUSE-DEPLOYMENT.md +181 -0
  2. package/README.md +33 -7
  3. package/dist/bin/sql.js +33 -51
  4. package/dist/index.js +68 -299
  5. package/dist/index.js.map +4 -4
  6. package/dist/lib/adapters/adapter.d.ts +8 -1
  7. package/dist/lib/adapters/adapter.d.ts.map +1 -1
  8. package/dist/lib/adapters/bigquery/bigquery.d.ts.map +1 -1
  9. package/dist/lib/adapters/bigquery/bigquery.sql-policy.d.ts +9 -0
  10. package/dist/lib/adapters/bigquery/bigquery.sql-policy.d.ts.map +1 -0
  11. package/dist/lib/adapters/bigquery/index.d.ts +1 -0
  12. package/dist/lib/adapters/bigquery/index.d.ts.map +1 -1
  13. package/dist/lib/adapters/bigquery/index.js +303 -259
  14. package/dist/lib/adapters/bigquery/index.js.map +4 -4
  15. package/dist/lib/adapters/clickhouse/clickhouse.d.ts +22 -0
  16. package/dist/lib/adapters/clickhouse/clickhouse.d.ts.map +1 -0
  17. package/dist/lib/adapters/clickhouse/clickhouse.sql-policy.d.ts +8 -0
  18. package/dist/lib/adapters/clickhouse/clickhouse.sql-policy.d.ts.map +1 -0
  19. package/dist/lib/adapters/clickhouse/constraint.clickhouse.grounding.d.ts +8 -0
  20. package/dist/lib/adapters/clickhouse/constraint.clickhouse.grounding.d.ts.map +1 -0
  21. package/dist/lib/adapters/clickhouse/index.d.ts +33 -0
  22. package/dist/lib/adapters/clickhouse/index.d.ts.map +1 -0
  23. package/dist/lib/adapters/clickhouse/index.js +1544 -0
  24. package/dist/lib/adapters/clickhouse/index.js.map +7 -0
  25. package/dist/lib/adapters/clickhouse/indexes.clickhouse.grounding.d.ts +8 -0
  26. package/dist/lib/adapters/clickhouse/indexes.clickhouse.grounding.d.ts.map +1 -0
  27. package/dist/lib/adapters/clickhouse/info.clickhouse.grounding.d.ts +8 -0
  28. package/dist/lib/adapters/clickhouse/info.clickhouse.grounding.d.ts.map +1 -0
  29. package/dist/lib/adapters/clickhouse/row-count.clickhouse.grounding.d.ts +8 -0
  30. package/dist/lib/adapters/clickhouse/row-count.clickhouse.grounding.d.ts.map +1 -0
  31. package/dist/lib/adapters/clickhouse/table.clickhouse.grounding.d.ts +11 -0
  32. package/dist/lib/adapters/clickhouse/table.clickhouse.grounding.d.ts.map +1 -0
  33. package/dist/lib/adapters/clickhouse/view.clickhouse.grounding.d.ts +9 -0
  34. package/dist/lib/adapters/clickhouse/view.clickhouse.grounding.d.ts.map +1 -0
  35. package/dist/lib/adapters/groundings/abstract.grounding.d.ts +11 -16
  36. package/dist/lib/adapters/groundings/abstract.grounding.d.ts.map +1 -1
  37. package/dist/lib/adapters/groundings/index.js +16 -0
  38. package/dist/lib/adapters/groundings/index.js.map +2 -2
  39. package/dist/lib/adapters/groundings/table.grounding.d.ts +1 -0
  40. package/dist/lib/adapters/groundings/table.grounding.d.ts.map +1 -1
  41. package/dist/lib/adapters/groundings/view.grounding.d.ts +1 -0
  42. package/dist/lib/adapters/groundings/view.grounding.d.ts.map +1 -1
  43. package/dist/lib/adapters/mysql/index.d.ts +1 -0
  44. package/dist/lib/adapters/mysql/index.d.ts.map +1 -1
  45. package/dist/lib/adapters/mysql/index.js +317 -259
  46. package/dist/lib/adapters/mysql/index.js.map +4 -4
  47. package/dist/lib/adapters/mysql/mysql.d.ts.map +1 -1
  48. package/dist/lib/adapters/mysql/mysql.sql-policy.d.ts +11 -0
  49. package/dist/lib/adapters/mysql/mysql.sql-policy.d.ts.map +1 -0
  50. package/dist/lib/adapters/parser-sql-policy.d.ts +23 -0
  51. package/dist/lib/adapters/parser-sql-policy.d.ts.map +1 -0
  52. package/dist/lib/adapters/postgres/index.d.ts +1 -0
  53. package/dist/lib/adapters/postgres/index.d.ts.map +1 -1
  54. package/dist/lib/adapters/postgres/index.js +323 -259
  55. package/dist/lib/adapters/postgres/index.js.map +4 -4
  56. package/dist/lib/adapters/postgres/postgres.d.ts.map +1 -1
  57. package/dist/lib/adapters/postgres/postgres.sql-policy.d.ts +10 -0
  58. package/dist/lib/adapters/postgres/postgres.sql-policy.d.ts.map +1 -0
  59. package/dist/lib/adapters/spreadsheet/index.js +301 -259
  60. package/dist/lib/adapters/spreadsheet/index.js.map +4 -4
  61. package/dist/lib/adapters/spreadsheet/parser.d.ts.map +1 -1
  62. package/dist/lib/adapters/sql-policy.d.ts +19 -0
  63. package/dist/lib/adapters/sql-policy.d.ts.map +1 -0
  64. package/dist/lib/adapters/sqlite/index.d.ts +1 -0
  65. package/dist/lib/adapters/sqlite/index.d.ts.map +1 -1
  66. package/dist/lib/adapters/sqlite/index.js +303 -259
  67. package/dist/lib/adapters/sqlite/index.js.map +4 -4
  68. package/dist/lib/adapters/sqlite/sqlite.d.ts.map +1 -1
  69. package/dist/lib/adapters/sqlite/sqlite.sql-policy.d.ts +8 -0
  70. package/dist/lib/adapters/sqlite/sqlite.sql-policy.d.ts.map +1 -0
  71. package/dist/lib/adapters/sqlserver/index.d.ts +1 -0
  72. package/dist/lib/adapters/sqlserver/index.d.ts.map +1 -1
  73. package/dist/lib/adapters/sqlserver/index.js +310 -259
  74. package/dist/lib/adapters/sqlserver/index.js.map +4 -4
  75. package/dist/lib/adapters/sqlserver/sqlserver.d.ts.map +1 -1
  76. package/dist/lib/adapters/sqlserver/sqlserver.sql-policy.d.ts +11 -0
  77. package/dist/lib/adapters/sqlserver/sqlserver.sql-policy.d.ts.map +1 -0
  78. package/dist/lib/agents/exceptions.d.ts +1 -1
  79. package/dist/lib/agents/sql-transform-plugins.d.ts +1 -2
  80. package/dist/lib/agents/sql-transform-plugins.d.ts.map +1 -1
  81. package/dist/lib/agents/sql.agent.d.ts.map +1 -1
  82. package/dist/lib/sql-command.d.ts.map +1 -1
  83. package/dist/lib/sql-hooks.d.ts +5 -1
  84. package/dist/lib/sql-hooks.d.ts.map +1 -1
  85. package/dist/lib/sql-meta-hook.d.ts +6 -2
  86. package/dist/lib/sql-meta-hook.d.ts.map +1 -1
  87. package/dist/lib/sql-scope-error.d.ts +3 -0
  88. package/dist/lib/sql-scope-error.d.ts.map +1 -0
  89. package/dist/lib/sql-validate-reminder.d.ts +3 -3
  90. package/dist/lib/sql-validate-reminder.d.ts.map +1 -1
  91. package/dist/lib/synthesis/index.js +32 -38
  92. package/dist/lib/synthesis/index.js.map +4 -4
  93. package/package.json +30 -24
  94. package/dist/lib/adapters/runtime-scope.d.ts +0 -16
  95. package/dist/lib/adapters/runtime-scope.d.ts.map +0 -1
@@ -0,0 +1,181 @@
1
+ # ClickHouse adapter
2
+
3
+ `@deepagents/text2sql/clickhouse` provides a client-independent ClickHouse
4
+ adapter. It uses ClickHouse itself to classify SQL and resolve physical
5
+ relations before either the consumer validator or the candidate query can run.
6
+
7
+ ## Supported versions
8
+
9
+ The real-server behavior suite is pinned to:
10
+
11
+ - `25.8.28.1`, the minimum supported version and previous LTS line; and
12
+ - `26.6.1.1193`, the current stable line when this adapter was implemented.
13
+
14
+ ClickHouse identifies 25.8 as an LTS release in the official
15
+ [25.8 release material](https://clickhouse.com/blog/clickhouse-release-25-08),
16
+ and published the current [26.6 release](https://clickhouse.com/blog/clickhouse-release-26-06)
17
+ on July 3, 2026. Re-evaluate and extend the pinned matrix before changing this
18
+ range. The official [support policy](https://clickhouse.com/legal/support-services-policy)
19
+ defines the rolling stable and LTS support windows.
20
+
21
+ ## Usage
22
+
23
+ The package does not depend on a ClickHouse client. Supply one raw query
24
+ callback and keep protocol-specific result handling outside the adapter:
25
+
26
+ ```ts
27
+ import {
28
+ ClickHouse,
29
+ constraints,
30
+ indexes,
31
+ info,
32
+ rowCount,
33
+ tables,
34
+ views,
35
+ } from '@deepagents/text2sql/clickhouse';
36
+
37
+ const query = async (sql: string) => {
38
+ const result = await client.query({ query: sql, format: 'JSON' });
39
+ return result.json();
40
+ };
41
+
42
+ const database = new ClickHouse({
43
+ defaultDatabase: 'analytics',
44
+ execute: query,
45
+ // EXPLAIN QUERY TREE already performs server-side semantic validation.
46
+ // Keep this hook for any additional application validation.
47
+ validate: async () => undefined,
48
+ grounding: [
49
+ info(),
50
+ tables({ filter: ['analytics.users', 'analytics.orders'] }),
51
+ views(),
52
+ rowCount(),
53
+ constraints(),
54
+ indexes(),
55
+ ],
56
+ });
57
+ ```
58
+
59
+ The raw callback must:
60
+
61
+ - return row objects as an array, `{ data: rows }`, or `{ rows }`;
62
+ - throw when ClickHouse reports an exception, including HTTP responses that
63
+ carry an `exception` field with a successful HTTP status;
64
+ - select JSON as a client/protocol option (or HTTP `default_format`), not by
65
+ appending `FORMAT JSON` to the SQL; and
66
+ - never call `database.execute()`, which would recurse through policy analysis.
67
+
68
+ `execute` is intentionally the same raw callback used for policy inspection,
69
+ grounding queries, and the final accepted SELECT.
70
+
71
+ ## Required database role
72
+
73
+ Create a dedicated user with one dedicated role. Do not add direct grants or
74
+ additional default roles to this user.
75
+
76
+ ```sql
77
+ CREATE ROLE deepagents_readonly;
78
+
79
+ GRANT SELECT ON analytics.* TO deepagents_readonly;
80
+
81
+ -- Required by SQL policy analysis to reject SQL, executable, and WASM UDFs.
82
+ GRANT SELECT ON system.functions TO deepagents_readonly;
83
+
84
+ -- Required only when indexes() grounding is configured.
85
+ GRANT SELECT ON system.data_skipping_indices TO deepagents_readonly;
86
+
87
+ ALTER ROLE deepagents_readonly SETTINGS
88
+ readonly = 1,
89
+ max_execution_time = 30,
90
+ max_memory_usage = 2000000000,
91
+ max_rows_to_read = 100000000,
92
+ max_bytes_to_read = 5000000000,
93
+ max_result_rows = 100000,
94
+ max_threads = 4;
95
+
96
+ CREATE USER deepagents
97
+ IDENTIFIED WITH sha256_password BY 'replace-with-a-secret';
98
+
99
+ GRANT deepagents_readonly TO deepagents;
100
+ ALTER USER deepagents DEFAULT ROLE deepagents_readonly;
101
+ ```
102
+
103
+ Use `readonly = 1`. The adapter checks the effective value together with
104
+ `currentDatabase()` on first use, caches that successful check, and fails closed
105
+ unless the callback returns exactly one valid row. Keep ClickHouse permissions
106
+ and resource settings in place: server-assisted analysis is an additional
107
+ boundary, not a replacement for RBAC.
108
+
109
+ ClickHouse's official
110
+ [agentic analytics guidance](https://clickhouse.com/blog/how-to-set-up-clickhouse-for-agentic-analytics)
111
+ recommends a SELECT-only role, `readonly = 1`, and workload limits. In
112
+ ClickHouse Cloud, use a read-only service for this workload as well. A read-only
113
+ service can still export data through table functions, so service isolation
114
+ does not replace the adapter checks.
115
+
116
+ Use ClickHouse row policies for tenant filtering. The adapter does not rewrite
117
+ arbitrary SQL and `EXPLAIN` output is not a mutable AST.
118
+
119
+ ## Policy behavior
120
+
121
+ Both `validate()` and `execute()` independently run this sequence before a
122
+ candidate can reach the corresponding consumer callback:
123
+
124
+ 1. verify effective `readonly = 1` and capture the effective database;
125
+ 2. inspect `EXPLAIN AST` and require one SELECT root;
126
+ 3. reject `INTO OUTFILE`, every table function, dictionary/Join-engine lookup
127
+ functions, and every non-system UDF origin;
128
+ 4. inspect `EXPLAIN QUERY TREE run_passes = 0` to retain unused CTEs;
129
+ 5. inspect the analyzed query tree to validate and resolve physical names; and
130
+ 6. compare the union of relations with grounded entities using exact,
131
+ case-sensitive, database-qualified names.
132
+
133
+ Unknown response columns, AST nodes, query-tree nodes, relation shapes,
134
+ function origins, parse failures, multiple statements, and malformed SQL all
135
+ fail closed. Views and Distributed tables are authorized by the relation name
136
+ reported by ClickHouse and must be grounded explicitly.
137
+ Dictionary access through `dict*` and Join-engine access through `joinGet*` are
138
+ not supported because those functions do not expose their data source as a
139
+ normal relation.
140
+
141
+ The pinned allowlist includes ordinary SELECTs, CTEs, views, joins, subqueries,
142
+ unions, `ARRAY JOIN`, `PREWHERE`, grouping, `HAVING`, `LIMIT BY`, windows, and
143
+ `QUALIFY`. Unapproved structural features remain rejected. For example, the
144
+ current real-server fixtures deliberately fail closed on column transformers
145
+ such as `* EXCEPT` and `ORDER BY ... WITH FILL` query-tree nodes.
146
+
147
+ ClickHouse documents the AST and query-tree modes in its
148
+ [EXPLAIN reference](https://clickhouse.com/docs/sql-reference/statements/explain).
149
+ Because their textual diagnostics are not a stable parser API, extend an
150
+ allowlist only after capturing output on both pinned versions and adding a
151
+ public real-server behavior test.
152
+
153
+ ## Grounding behavior
154
+
155
+ The subpath exports `info`, `tables`, `views`, `rowCount`, `constraints`, and
156
+ `indexes` grounding factories.
157
+
158
+ - `tables()` and `views()` read access-filtered `system.tables` and
159
+ `system.columns` metadata.
160
+ - `constraints()` reports ClickHouse nullability, default expressions, and
161
+ primary-key columns. ClickHouse primary keys organize data and do not imply
162
+ uniqueness.
163
+ - `indexes()` reports primary-key and data-skipping indexes; it needs the
164
+ explicit `system.data_skipping_indices` grant shown above.
165
+ - `rowCount()` executes `count()` against each grounded table. Configure it
166
+ only when exact counts are worth the scan and retain the resource limits.
167
+ - ClickHouse does not expose conventional foreign-key relationships, so table
168
+ traversal does not synthesize them.
169
+
170
+ Keep grounding limited to curated databases and tables. A broad SELECT grant
171
+ also broadens what schema metadata and physical relations can be authorized.
172
+
173
+ ## Compatibility testing
174
+
175
+ The ClickHouse integration file uses only the public package subpath and starts
176
+ real Docker servers. With Docker available, it runs both pinned images by
177
+ default. Set `CLICKHOUSE_TEST_IMAGE` to one pinned image for a focused run.
178
+
179
+ Do not replace the policy tests with mocked EXPLAIN payloads. New ClickHouse
180
+ versions must prove their actual AST/query-tree shapes and security behavior
181
+ against a real server before being added to the supported matrix.
package/README.md CHANGED
@@ -5,7 +5,7 @@ AI-powered natural language to SQL. Ask questions in plain English, get executab
5
5
  ## Features
6
6
 
7
7
  - **Natural Language to SQL** - Convert questions to validated, executable queries
8
- - **Multi-Database Support** - PostgreSQL, SQLite, SQL Server, MySQL/MariaDB, and BigQuery adapters
8
+ - **Multi-Database Support** - PostgreSQL, SQLite, SQL Server, MySQL/MariaDB, BigQuery, and ClickHouse adapters
9
9
  - **Schema-Aware** - Automatic introspection of tables, relationships, indexes, and constraints
10
10
  - **Domain Knowledge** - Inject business terms, guardrails, and query patterns via fragments
11
11
  - **Conversational** - Multi-turn conversations with context persistence
@@ -24,6 +24,7 @@ npm install pg # PostgreSQL
24
24
  npm install mssql # SQL Server
25
25
  npm install mysql2 # MySQL / MariaDB
26
26
  npm install @google-cloud/bigquery # BigQuery
27
+ npm install @clickhouse/client # ClickHouse, or use your preferred client
27
28
  ```
28
29
 
29
30
  Requires Node.js LTS
@@ -184,9 +185,13 @@ model must pass to `sql validate <db>` and `sql run <db>`. Add or replace the
184
185
  instructions with your own domain fragments as needed.
185
186
 
186
187
  `sqlValidateReminder()` returns a context reminder fragment backed by
187
- `SQL_VALIDATE_REMINDER`. It adds a tool-output system reminder when the current
188
- assistant turn calls `sql run <db> "..."` without a prior `sql validate <db>
189
- "..."` for the same configured adapter name and exact SQL text.
188
+ `SQL_VALIDATE_REMINDER`. After a successful `sql run <db> "..."`, it adds a
189
+ model-only tool-output reminder before the next generation when no prior
190
+ `sql validate <db> "..."` used the same configured adapter name and exact SQL
191
+ text. The raw SQL command result remains unchanged. During streamed `chat()`
192
+ turns, the reminder is persisted as a synthetic user message for replay and
193
+ prompt caching; bare `createPrepareStep()` integrations and
194
+ `agent.generate()` own persistence of their generated assistant history.
190
195
 
191
196
  ## Advanced: SQL CLI in Sandboxes
192
197
 
@@ -267,9 +272,29 @@ blocks raw database access so read-only and scope checks stay behind
267
272
  metadata from the host adapter map without putting that concern into the real
268
273
  CLI.
269
274
 
270
- Read-only enforcement accepts a single `SELECT`/`WITH` statement even when it
271
- starts with whitespace or SQL comments (`-- ...`, `/* ... */`). It still
272
- rejects comment-only input, multi-statement batches, and write operations.
275
+ Read-only enforcement parses a single `SELECT`/`WITH` statement even when it
276
+ starts with whitespace or SQL comments (`-- ...`, `/* ... */`). Before any
277
+ adapter validator or executor runs, the dialect policy rejects write
278
+ statements, multi-statement batches, parser failures, `SELECT INTO`, locking
279
+ reads/hints, assignments, known state/file/extension/remote-access functions,
280
+ BigQuery external queries, qualified BigQuery persistent routines, and
281
+ ClickHouse table functions or unsafe UDF origins.
282
+
283
+ Scope checks compare referenced base tables and views against the entities
284
+ produced by `tables()` and `views()` groundings. Entity-free queries such as
285
+ `SELECT 1` do not run grounding just to resolve an empty allowlist, and metadata
286
+ groundings such as `indexes()`, `constraints()`, `rowCount()`,
287
+ `columnStats()`, and `columnValues()` annotate schema context without expanding
288
+ the validation allowlist.
289
+
290
+ This parser policy is one safety layer, not a database permission boundary.
291
+ Static analysis cannot prove arbitrary unqualified user-defined functions are
292
+ side-effect free, and an otherwise valid `SELECT` can still consume excessive
293
+ CPU, memory, bytes, locks, or time. Production connections must use a dedicated
294
+ least-privilege identity with `SELECT` only on intended relations; disable or
295
+ withhold extension, file, remote-query, and routine execution capabilities; and
296
+ configure dialect-appropriate statement timeouts, byte/result limits, and
297
+ compute/memory limits.
273
298
 
274
299
  ## Fragments
275
300
 
@@ -516,6 +541,7 @@ Full documentation available at [januarylabs.github.io/deepagents](https://janua
516
541
  - [SQL Server](https://januarylabs.github.io/deepagents/docs/text2sql/sqlserver)
517
542
  - [MySQL / MariaDB](https://januarylabs.github.io/deepagents/docs/text2sql/mysql)
518
543
  - [BigQuery](https://januarylabs.github.io/deepagents/docs/text2sql/bigquery)
544
+ - [ClickHouse](https://januarylabs.github.io/deepagents/docs/text2sql/clickhouse)
519
545
 
520
546
  ## Repository
521
547
 
package/dist/bin/sql.js CHANGED
@@ -143,10 +143,10 @@ function validateAdapterNames(names) {
143
143
  import { format as formatSql } from "sql-formatter";
144
144
 
145
145
  // packages/text2sql/src/lib/agents/exceptions.ts
146
- var sqlValidationMarker = Symbol("SQLValidationError");
147
- var unanswerableSqlMarker = Symbol("UnanswerableSQLError");
148
- var sqlScopeMarker = Symbol("SQLScopeError");
149
- var sqlReadOnlyMarker = Symbol("SQLReadOnlyError");
146
+ var sqlValidationMarker = /* @__PURE__ */ Symbol("SQLValidationError");
147
+ var unanswerableSqlMarker = /* @__PURE__ */ Symbol("UnanswerableSQLError");
148
+ var sqlScopeMarker = /* @__PURE__ */ Symbol("SQLScopeError");
149
+ var sqlReadOnlyMarker = /* @__PURE__ */ Symbol("SQLReadOnlyError");
150
150
  var SQLValidationError = class _SQLValidationError extends Error {
151
151
  [sqlValidationMarker];
152
152
  constructor(message) {
@@ -219,22 +219,6 @@ function createGroundingContext(options = {}) {
219
219
  };
220
220
  }
221
221
 
222
- // packages/text2sql/src/lib/adapters/runtime-scope.ts
223
- import nodeSqlParser from "node-sql-parser";
224
- var { Parser } = nodeSqlParser;
225
- var parser = new Parser();
226
- function buildScopeParseErrorPayload(sql, dialect, error) {
227
- const parserError = error instanceof Error ? error.message : String(error ?? "Unknown error");
228
- return {
229
- error: `SQL scope analysis failed before validation/execution: ${parserError}`,
230
- error_type: "SQL_SCOPE_PARSE_ERROR",
231
- suggestion: "Rewrite the query into simpler SQL that can be analyzed safely, or extend parser coverage for this dialect feature.",
232
- sql_attempted: sql,
233
- parser_dialect: dialect,
234
- parser_error: parserError
235
- };
236
- }
237
-
238
222
  // packages/text2sql/src/lib/adapter-index.ts
239
223
  var noopProgressHandler = () => {
240
224
  };
@@ -443,16 +427,24 @@ import {
443
427
  user,
444
428
  workflow
445
429
  } from "@deepagents/context";
430
+
431
+ // packages/text2sql/src/lib/sql-scope-error.ts
432
+ function buildScopeParseErrorPayload(sql, parserDialect, error) {
433
+ const parserError = error instanceof Error ? error.message : String(error ?? "Unknown error");
434
+ return {
435
+ error: `SQL scope analysis failed before validation/execution: ${parserError}`,
436
+ error_type: "SQL_SCOPE_PARSE_ERROR",
437
+ suggestion: "Rewrite the query into simpler SQL that can be analyzed safely, or extend parser coverage for this dialect feature.",
438
+ sql_attempted: sql,
439
+ parser_dialect: parserDialect,
440
+ parser_error: parserError
441
+ };
442
+ }
443
+
444
+ // packages/text2sql/src/lib/agents/sql.agent.ts
446
445
  var RETRY_TEMPERATURES = [0, 0.2, 0.3];
447
446
  var SQL_AGENT_ROLE = "Expert SQL query generator.";
448
447
  var SQL_AGENT_OBJECTIVE = "Generate precise SQL grounded in provided schema.";
449
- var FORMATTER_SCOPE_DIALECTS = /* @__PURE__ */ new Map([
450
- ["sqlite", "sqlite"],
451
- ["postgresql", "postgresql"],
452
- ["bigquery", "bigquery"],
453
- ["transactsql", "transactsql"],
454
- ["mysql", "mysql"]
455
- ]);
456
448
  var SQL_AGENT_POLICIES = [
457
449
  fragment2(
458
450
  "schema_mapping",
@@ -658,26 +650,6 @@ function extractSql(output) {
658
650
  const match = output.match(/```sql\n?([\s\S]*?)```/);
659
651
  return match ? match[1].trim() : output.trim();
660
652
  }
661
- function scopeDialectFor(adapter) {
662
- const dialect = FORMATTER_SCOPE_DIALECTS.get(adapter.formatterLanguage);
663
- if (!dialect) {
664
- throw new TypeError(
665
- `No scope dialect mapping for formatter language "${adapter.formatterLanguage}".`
666
- );
667
- }
668
- return dialect;
669
- }
670
- function fencedMarkdownParseError(sql, adapter) {
671
- return new SQLValidationError(
672
- JSON.stringify(
673
- buildScopeParseErrorPayload(
674
- sql,
675
- scopeDialectFor(adapter),
676
- new Error("SQL response was fenced markdown, not executable SQL.")
677
- )
678
- )
679
- );
680
- }
681
653
  async function toSql(options) {
682
654
  const { maxRetries = 3 } = options;
683
655
  return withRetry(
@@ -759,7 +731,17 @@ Question: ${options.input}
759
731
  }
760
732
  const sql = options.adapter.format(extractedSql);
761
733
  if (rawSql.trimStart().startsWith("```") && extractedSql === rawSql.trim()) {
762
- throw fencedMarkdownParseError(sql, options.adapter);
734
+ throw new SQLValidationError(
735
+ JSON.stringify(
736
+ buildScopeParseErrorPayload(
737
+ sql,
738
+ options.adapter.formatterLanguage,
739
+ new Error(
740
+ "SQL response was fenced markdown, not executable SQL."
741
+ )
742
+ )
743
+ )
744
+ );
763
745
  }
764
746
  const validationError = await options.adapter.validate(sql);
765
747
  if (validationError) {
@@ -867,8 +849,8 @@ async function withRetry(computation, options = { retries: 3 }) {
867
849
  }
868
850
 
869
851
  // packages/text2sql/src/lib/sql.ts
870
- var text2SqlValidationMarker = Symbol("Text2SqlValidationError");
871
- var text2SqlUnknownAdapterMarker = Symbol("Text2SqlUnknownAdapterError");
852
+ var text2SqlValidationMarker = /* @__PURE__ */ Symbol("Text2SqlValidationError");
853
+ var text2SqlUnknownAdapterMarker = /* @__PURE__ */ Symbol("Text2SqlUnknownAdapterError");
872
854
  var Text2SqlValidationError = class _Text2SqlValidationError extends Error {
873
855
  [text2SqlValidationMarker];
874
856
  constructor(message) {
@@ -896,7 +878,7 @@ var Text2SqlUnknownAdapterError = class _Text2SqlUnknownAdapterError extends Err
896
878
  return error instanceof _Text2SqlUnknownAdapterError && error[text2SqlUnknownAdapterMarker] === true;
897
879
  }
898
880
  };
899
- var text2SqlUnknownDatabaseMarker = Symbol("Text2SqlUnknownDatabaseError");
881
+ var text2SqlUnknownDatabaseMarker = /* @__PURE__ */ Symbol("Text2SqlUnknownDatabaseError");
900
882
  var Text2SqlUnknownDatabaseError = class _Text2SqlUnknownDatabaseError extends Error {
901
883
  [text2SqlUnknownDatabaseMarker];
902
884
  requested;