@deepagents/text2sql 5.0.0 → 6.1.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 (106) hide show
  1. package/CLICKHOUSE-DEPLOYMENT.md +181 -0
  2. package/README.md +32 -4
  3. package/dist/bin/sql.js +34 -51
  4. package/dist/index.js +58 -289
  5. package/dist/index.js.map +4 -4
  6. package/dist/lib/adapters/adapter.d.ts +9 -2
  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 +305 -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 +1546 -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/context.d.ts +3 -0
  38. package/dist/lib/adapters/groundings/context.d.ts.map +1 -1
  39. package/dist/lib/adapters/groundings/index.js +17 -0
  40. package/dist/lib/adapters/groundings/index.js.map +2 -2
  41. package/dist/lib/adapters/groundings/table.grounding.d.ts +1 -0
  42. package/dist/lib/adapters/groundings/table.grounding.d.ts.map +1 -1
  43. package/dist/lib/adapters/groundings/view.grounding.d.ts +1 -0
  44. package/dist/lib/adapters/groundings/view.grounding.d.ts.map +1 -1
  45. package/dist/lib/adapters/mysql/index.d.ts +1 -0
  46. package/dist/lib/adapters/mysql/index.d.ts.map +1 -1
  47. package/dist/lib/adapters/mysql/index.js +319 -259
  48. package/dist/lib/adapters/mysql/index.js.map +4 -4
  49. package/dist/lib/adapters/mysql/mysql.d.ts.map +1 -1
  50. package/dist/lib/adapters/mysql/mysql.sql-policy.d.ts +11 -0
  51. package/dist/lib/adapters/mysql/mysql.sql-policy.d.ts.map +1 -0
  52. package/dist/lib/adapters/parser-sql-policy.d.ts +23 -0
  53. package/dist/lib/adapters/parser-sql-policy.d.ts.map +1 -0
  54. package/dist/lib/adapters/postgres/index.d.ts +1 -0
  55. package/dist/lib/adapters/postgres/index.d.ts.map +1 -1
  56. package/dist/lib/adapters/postgres/index.js +325 -259
  57. package/dist/lib/adapters/postgres/index.js.map +4 -4
  58. package/dist/lib/adapters/postgres/postgres.d.ts.map +1 -1
  59. package/dist/lib/adapters/postgres/postgres.sql-policy.d.ts +10 -0
  60. package/dist/lib/adapters/postgres/postgres.sql-policy.d.ts.map +1 -0
  61. package/dist/lib/adapters/posthog/definitions.posthog.grounding.d.ts +19 -0
  62. package/dist/lib/adapters/posthog/definitions.posthog.grounding.d.ts.map +1 -0
  63. package/dist/lib/adapters/posthog/index.d.ts +22 -0
  64. package/dist/lib/adapters/posthog/index.d.ts.map +1 -0
  65. package/dist/lib/adapters/posthog/index.js +1303 -0
  66. package/dist/lib/adapters/posthog/index.js.map +7 -0
  67. package/dist/lib/adapters/posthog/info.posthog.grounding.d.ts +7 -0
  68. package/dist/lib/adapters/posthog/info.posthog.grounding.d.ts.map +1 -0
  69. package/dist/lib/adapters/posthog/posthog.d.ts +23 -0
  70. package/dist/lib/adapters/posthog/posthog.d.ts.map +1 -0
  71. package/dist/lib/adapters/posthog/posthog.sql-policy.d.ts +8 -0
  72. package/dist/lib/adapters/posthog/posthog.sql-policy.d.ts.map +1 -0
  73. package/dist/lib/adapters/posthog/schema.posthog.grounding.d.ts +16 -0
  74. package/dist/lib/adapters/posthog/schema.posthog.grounding.d.ts.map +1 -0
  75. package/dist/lib/adapters/posthog/transport.d.ts +16 -0
  76. package/dist/lib/adapters/posthog/transport.d.ts.map +1 -0
  77. package/dist/lib/adapters/posthog/types.d.ts +95 -0
  78. package/dist/lib/adapters/posthog/types.d.ts.map +1 -0
  79. package/dist/lib/adapters/spreadsheet/index.js +303 -259
  80. package/dist/lib/adapters/spreadsheet/index.js.map +4 -4
  81. package/dist/lib/adapters/spreadsheet/parser.d.ts.map +1 -1
  82. package/dist/lib/adapters/sql-policy.d.ts +19 -0
  83. package/dist/lib/adapters/sql-policy.d.ts.map +1 -0
  84. package/dist/lib/adapters/sqlite/index.d.ts +1 -0
  85. package/dist/lib/adapters/sqlite/index.d.ts.map +1 -1
  86. package/dist/lib/adapters/sqlite/index.js +305 -259
  87. package/dist/lib/adapters/sqlite/index.js.map +4 -4
  88. package/dist/lib/adapters/sqlite/sqlite.d.ts.map +1 -1
  89. package/dist/lib/adapters/sqlite/sqlite.sql-policy.d.ts +8 -0
  90. package/dist/lib/adapters/sqlite/sqlite.sql-policy.d.ts.map +1 -0
  91. package/dist/lib/adapters/sqlserver/index.d.ts +1 -0
  92. package/dist/lib/adapters/sqlserver/index.d.ts.map +1 -1
  93. package/dist/lib/adapters/sqlserver/index.js +312 -259
  94. package/dist/lib/adapters/sqlserver/index.js.map +4 -4
  95. package/dist/lib/adapters/sqlserver/sqlserver.d.ts.map +1 -1
  96. package/dist/lib/adapters/sqlserver/sqlserver.sql-policy.d.ts +11 -0
  97. package/dist/lib/adapters/sqlserver/sqlserver.sql-policy.d.ts.map +1 -0
  98. package/dist/lib/agents/exceptions.d.ts +1 -1
  99. package/dist/lib/agents/sql.agent.d.ts.map +1 -1
  100. package/dist/lib/sql-scope-error.d.ts +3 -0
  101. package/dist/lib/sql-scope-error.d.ts.map +1 -0
  102. package/dist/lib/synthesis/index.js +32 -38
  103. package/dist/lib/synthesis/index.js.map +4 -4
  104. package/package.json +35 -23
  105. package/dist/lib/adapters/runtime-scope.d.ts +0 -16
  106. 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, ClickHouse, and PostHog HogQL 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,8 @@ 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
28
+ # PostHog uses native fetch and needs no additional client package
27
29
  ```
28
30
 
29
31
  Requires Node.js LTS
@@ -271,9 +273,33 @@ blocks raw database access so read-only and scope checks stay behind
271
273
  metadata from the host adapter map without putting that concern into the real
272
274
  CLI.
273
275
 
274
- Read-only enforcement accepts a single `SELECT`/`WITH` statement even when it
275
- starts with whitespace or SQL comments (`-- ...`, `/* ... */`). It still
276
- rejects comment-only input, multi-statement batches, and write operations.
276
+ Read-only enforcement parses a single `SELECT`/`WITH` statement even when it
277
+ starts with whitespace or SQL comments (`-- ...`, `/* ... */`). Before any
278
+ adapter validator or executor runs, the dialect policy rejects write
279
+ statements, multi-statement batches, parser failures, `SELECT INTO`, locking
280
+ reads/hints, assignments, known state/file/extension/remote-access functions,
281
+ BigQuery external queries, qualified BigQuery persistent routines, and
282
+ ClickHouse table functions or unsafe UDF origins.
283
+
284
+ Scope checks compare referenced base tables and views against the entities
285
+ produced by `tables()` and `views()` groundings. Entity-free queries such as
286
+ `SELECT 1` do not run grounding just to resolve an empty allowlist, and metadata
287
+ groundings such as `indexes()`, `constraints()`, `rowCount()`,
288
+ `columnStats()`, and `columnValues()` annotate schema context without expanding
289
+ the validation allowlist.
290
+
291
+ This parser policy is one safety layer, not a database permission boundary.
292
+ Static analysis cannot prove arbitrary unqualified user-defined functions are
293
+ side-effect free, and an otherwise valid `SELECT` can still consume excessive
294
+ CPU, memory, bytes, locks, or time. Production connections must use a dedicated
295
+ least-privilege identity with `SELECT` only on intended relations; disable or
296
+ withhold extension, file, remote-query, and routine execution capabilities; and
297
+ configure dialect-appropriate statement timeouts, byte/result limits, and
298
+ compute/memory limits.
299
+
300
+ The PostHog adapter does not pass HogQL through the local SQL parser. It asks
301
+ PostHog to parse each query with `HogQLMetadata`, checks the returned base-table
302
+ names against grounded schema, and only then sends a `HogQLQuery` for execution.
277
303
 
278
304
  ## Fragments
279
305
 
@@ -520,6 +546,8 @@ Full documentation available at [januarylabs.github.io/deepagents](https://janua
520
546
  - [SQL Server](https://januarylabs.github.io/deepagents/docs/text2sql/sqlserver)
521
547
  - [MySQL / MariaDB](https://januarylabs.github.io/deepagents/docs/text2sql/mysql)
522
548
  - [BigQuery](https://januarylabs.github.io/deepagents/docs/text2sql/bigquery)
549
+ - [ClickHouse](https://januarylabs.github.io/deepagents/docs/text2sql/clickhouse)
550
+ - [PostHog](https://januarylabs.github.io/deepagents/docs/text2sql/posthog)
523
551
 
524
552
  ## Repository
525
553
 
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) {
@@ -214,27 +214,12 @@ function createGroundingContext(options = {}) {
214
214
  views: [],
215
215
  relationships: [],
216
216
  info: void 0,
217
+ fragments: [],
217
218
  cache: /* @__PURE__ */ new Map(),
218
219
  onProgress: timestampProgress(options.onProgress)
219
220
  };
220
221
  }
221
222
 
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
223
  // packages/text2sql/src/lib/adapter-index.ts
239
224
  var noopProgressHandler = () => {
240
225
  };
@@ -443,16 +428,24 @@ import {
443
428
  user,
444
429
  workflow
445
430
  } from "@deepagents/context";
431
+
432
+ // packages/text2sql/src/lib/sql-scope-error.ts
433
+ function buildScopeParseErrorPayload(sql, parserDialect, error) {
434
+ const parserError = error instanceof Error ? error.message : String(error ?? "Unknown error");
435
+ return {
436
+ error: `SQL scope analysis failed before validation/execution: ${parserError}`,
437
+ error_type: "SQL_SCOPE_PARSE_ERROR",
438
+ suggestion: "Rewrite the query into simpler SQL that can be analyzed safely, or extend parser coverage for this dialect feature.",
439
+ sql_attempted: sql,
440
+ parser_dialect: parserDialect,
441
+ parser_error: parserError
442
+ };
443
+ }
444
+
445
+ // packages/text2sql/src/lib/agents/sql.agent.ts
446
446
  var RETRY_TEMPERATURES = [0, 0.2, 0.3];
447
447
  var SQL_AGENT_ROLE = "Expert SQL query generator.";
448
448
  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
449
  var SQL_AGENT_POLICIES = [
457
450
  fragment2(
458
451
  "schema_mapping",
@@ -658,26 +651,6 @@ function extractSql(output) {
658
651
  const match = output.match(/```sql\n?([\s\S]*?)```/);
659
652
  return match ? match[1].trim() : output.trim();
660
653
  }
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
654
  async function toSql(options) {
682
655
  const { maxRetries = 3 } = options;
683
656
  return withRetry(
@@ -759,7 +732,17 @@ Question: ${options.input}
759
732
  }
760
733
  const sql = options.adapter.format(extractedSql);
761
734
  if (rawSql.trimStart().startsWith("```") && extractedSql === rawSql.trim()) {
762
- throw fencedMarkdownParseError(sql, options.adapter);
735
+ throw new SQLValidationError(
736
+ JSON.stringify(
737
+ buildScopeParseErrorPayload(
738
+ sql,
739
+ options.adapter.formatterLanguage,
740
+ new Error(
741
+ "SQL response was fenced markdown, not executable SQL."
742
+ )
743
+ )
744
+ )
745
+ );
763
746
  }
764
747
  const validationError = await options.adapter.validate(sql);
765
748
  if (validationError) {
@@ -867,8 +850,8 @@ async function withRetry(computation, options = { retries: 3 }) {
867
850
  }
868
851
 
869
852
  // packages/text2sql/src/lib/sql.ts
870
- var text2SqlValidationMarker = Symbol("Text2SqlValidationError");
871
- var text2SqlUnknownAdapterMarker = Symbol("Text2SqlUnknownAdapterError");
853
+ var text2SqlValidationMarker = /* @__PURE__ */ Symbol("Text2SqlValidationError");
854
+ var text2SqlUnknownAdapterMarker = /* @__PURE__ */ Symbol("Text2SqlUnknownAdapterError");
872
855
  var Text2SqlValidationError = class _Text2SqlValidationError extends Error {
873
856
  [text2SqlValidationMarker];
874
857
  constructor(message) {
@@ -896,7 +879,7 @@ var Text2SqlUnknownAdapterError = class _Text2SqlUnknownAdapterError extends Err
896
879
  return error instanceof _Text2SqlUnknownAdapterError && error[text2SqlUnknownAdapterMarker] === true;
897
880
  }
898
881
  };
899
- var text2SqlUnknownDatabaseMarker = Symbol("Text2SqlUnknownDatabaseError");
882
+ var text2SqlUnknownDatabaseMarker = /* @__PURE__ */ Symbol("Text2SqlUnknownDatabaseError");
900
883
  var Text2SqlUnknownDatabaseError = class _Text2SqlUnknownDatabaseError extends Error {
901
884
  [text2SqlUnknownDatabaseMarker];
902
885
  requested;