@deepagents/text2sql 7.13.0 → 7.14.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 (30) hide show
  1. package/README.md +106 -1
  2. package/dist/index.js.map +1 -1
  3. package/dist/lib/adapters/bigquery/index.js +24 -5
  4. package/dist/lib/adapters/bigquery/index.js.map +2 -2
  5. package/dist/lib/adapters/clickhouse/index.js.map +1 -1
  6. package/dist/lib/adapters/duckdb/index.js.map +1 -1
  7. package/dist/lib/adapters/mysql/index.js +24 -5
  8. package/dist/lib/adapters/mysql/index.js.map +2 -2
  9. package/dist/lib/adapters/policy/in-scope.d.ts.map +1 -1
  10. package/dist/lib/adapters/policy/index.js +24 -5
  11. package/dist/lib/adapters/policy/index.js.map +2 -2
  12. package/dist/lib/adapters/policy/source-policy.d.ts +6 -0
  13. package/dist/lib/adapters/policy/source-policy.d.ts.map +1 -1
  14. package/dist/lib/adapters/postgres/index.js +24 -5
  15. package/dist/lib/adapters/postgres/index.js.map +2 -2
  16. package/dist/lib/adapters/posthog/index.js.map +1 -1
  17. package/dist/lib/adapters/spreadsheet/index.js +24 -5
  18. package/dist/lib/adapters/spreadsheet/index.js.map +2 -2
  19. package/dist/lib/adapters/sqlite/index.js +24 -5
  20. package/dist/lib/adapters/sqlite/index.js.map +2 -2
  21. package/dist/lib/adapters/sqlserver/index.d.ts +1 -0
  22. package/dist/lib/adapters/sqlserver/index.d.ts.map +1 -1
  23. package/dist/lib/adapters/sqlserver/index.js +130 -5
  24. package/dist/lib/adapters/sqlserver/index.js.map +4 -4
  25. package/dist/lib/adapters/sqlserver/sqlserver-plan.d.ts +66 -0
  26. package/dist/lib/adapters/sqlserver/sqlserver-plan.d.ts.map +1 -0
  27. package/dist/lib/sql-scope-error.d.ts +12 -1
  28. package/dist/lib/sql-scope-error.d.ts.map +1 -1
  29. package/dist/lib/synthesis/index.js.map +1 -1
  30. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"in-scope.d.ts","sources":["../../../../src/lib/adapters/policy/in-scope.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE5D,mFAAmF;AACnF,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;CAC9E;AAED;;;GAGG;AACH,qBAAa,OAAQ,YAAW,IAAI,CAAC,SAAS,CAAC;;IAG7C,YAAY,KAAK,EAAE,WAAW,EAE7B;IAED,QAAQ,CAAC,KAAK,UACL,SAAS,SACT,WAAW,KACjB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAanC;CACH;AAED;;;;GAIG;AACH,qBAAa,aAAc,YAAW,WAAW;IACzC,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,sBAQrB,MAAM,cAOzB;CACF"}
1
+ {"version":3,"file":"in-scope.d.ts","sources":["../../../../src/lib/adapters/policy/in-scope.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE5D,mFAAmF;AACnF,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;CAC9E;AAED;;;GAGG;AACH,qBAAa,OAAQ,YAAW,IAAI,CAAC,SAAS,CAAC;;IAG7C,YAAY,KAAK,EAAE,WAAW,EAE7B;IAED,QAAQ,CAAC,KAAK,UACL,SAAS,SACT,WAAW,KACjB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAgBnC;CACH;AAED;;;;GAIG;AACH,qBAAa,aAAc,YAAW,WAAW;IACzC,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,sBAQrB,MAAM,cAOzB;CACF"}
@@ -50,14 +50,22 @@ function buildScopeParseErrorPayload(sql, parserDialect, error) {
50
50
  parser_error: parserError
51
51
  };
52
52
  }
53
- function buildOutOfScopePayload(sql, referencedEntities, allowedEntities) {
53
+ function buildOutOfScopePayload(sql, scope) {
54
+ if ("denial" in scope) {
55
+ return {
56
+ error: scope.denial,
57
+ error_type: "OUT_OF_SCOPE",
58
+ suggestion: "Read only the tables and views that the database grants, in one SELECT that writes nothing.",
59
+ sql_attempted: sql
60
+ };
61
+ }
54
62
  return {
55
- error: `Query references entities outside grounded scope: ${referencedEntities.join(", ")}`,
63
+ error: `Query references entities outside grounded scope: ${scope.referenced.join(", ")}`,
56
64
  error_type: "OUT_OF_SCOPE",
57
65
  suggestion: "Restrict the query to grounded tables/views or expand grounding to include the referenced entities.",
58
66
  sql_attempted: sql,
59
- referenced_entities: referencedEntities,
60
- allowed_entities: allowedEntities
67
+ referenced_entities: scope.referenced,
68
+ allowed_entities: scope.allowed
61
69
  };
62
70
  }
63
71
 
@@ -75,7 +83,10 @@ var InScope = class {
75
83
  const outOfScope = relations.filter((relation) => !isAllowed(relation));
76
84
  return outOfScope.length === 0 ? null : {
77
85
  kind: "scope",
78
- payload: buildOutOfScopePayload(check.sql, outOfScope, [...allowed])
86
+ payload: buildOutOfScopePayload(check.sql, {
87
+ referenced: outOfScope,
88
+ allowed: [...allowed]
89
+ })
79
90
  };
80
91
  };
81
92
  };
@@ -106,8 +117,16 @@ var OneSelect = class {
106
117
  };
107
118
 
108
119
  // packages/text2sql/src/lib/adapters/policy/source-policy.ts
120
+ var unreadable = /* @__PURE__ */ Symbol.for("@deepagents/text2sql/UnreadableSql");
109
121
  var UnreadableSql = class extends Error {
110
122
  name = "UnreadableSql";
123
+ constructor(message, options) {
124
+ super(message, options);
125
+ Object.defineProperty(this, unreadable, { value: true });
126
+ }
127
+ static [Symbol.hasInstance](value) {
128
+ return Error.isError(value) && Object.hasOwn(value, unreadable);
129
+ }
111
130
  };
112
131
  var SourcePolicy = class {
113
132
  #source;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/lib/adapters/policy/read-only.ts", "../../../../src/lib/adapters/policy/denied-calls.ts", "../../../../src/lib/adapters/policy/forbid.ts", "../../../../src/lib/sql-scope-error.ts", "../../../../src/lib/adapters/policy/in-scope.ts", "../../../../src/lib/adapters/policy/one-select.ts", "../../../../src/lib/adapters/policy/source-policy.ts", "../../../../src/lib/adapters/policy/sql-text.ts"],
4
- "sourcesContent": ["import type { SqlPolicyViolation } from '../sql-policy.ts';\n\n/** The violation of SQL that could write, lock or leave the database. */\nexport const readOnly: SqlPolicyViolation = Object.freeze({\n kind: 'read-only',\n message: 'only SELECT or WITH queries allowed',\n});\n", "import type { Calls } from './facts.ts';\nimport { readOnly } from './read-only.ts';\nimport type { Rule } from './source-policy.ts';\n\nexport interface CallDenials {\n /** Function names, matched without case against a call's last name part. */\n readonly names?: readonly string[];\n /** Name prefixes, matched without case against a call's last name part. */\n readonly prefixes?: readonly string[];\n /** Deny every call whose name has more than one part, such as `dataset.fn`. */\n readonly qualified?: true;\n}\n\n/** The SQL calls none of the denied functions. */\nexport class DeniedCalls implements Rule<Calls> {\n readonly #names: ReadonlySet<string>;\n readonly #prefixes: readonly string[];\n readonly #qualified: boolean;\n\n constructor(denials: CallDenials) {\n this.#names = new Set(denials.names?.map((name) => name.toLowerCase()));\n this.#prefixes =\n denials.prefixes?.map((prefix) => prefix.toLowerCase()) ?? [];\n this.#qualified = denials.qualified === true;\n }\n\n readonly check = async (facts: Calls) => {\n const calls = await facts.calls();\n return calls.some((parts) => this.#denies(parts)) ? readOnly : null;\n };\n\n #denies(parts: readonly string[]): boolean {\n if (this.#qualified && parts.length > 1) return true;\n const name = parts.at(-1)?.toLowerCase();\n if (name === undefined) return false;\n return (\n this.#names.has(name) ||\n this.#prefixes.some((prefix) => name.startsWith(prefix))\n );\n }\n}\n", "import { readOnly } from './read-only.ts';\nimport type { Rule } from './source-policy.ts';\nimport type { Construct, Constructs } from './sql-text.ts';\n\n/** The SQL holds none of the forbidden constructs. */\nexport class Forbid implements Rule<Constructs> {\n readonly #forbidden: readonly Construct[];\n\n constructor(forbidden: readonly [Construct, ...Construct[]]) {\n this.#forbidden = forbidden;\n }\n\n readonly check = async (facts: Constructs) => {\n const found = await facts.constructs();\n return this.#forbidden.some((construct) => found.has(construct))\n ? readOnly\n : null;\n };\n}\n", "import type { SQLScopeErrorPayload } from './agents/exceptions.ts';\n\nexport function buildScopeParseErrorPayload(\n sql: string,\n parserDialect: string,\n error: unknown,\n): SQLScopeErrorPayload {\n const parserError = Error.isError(error)\n ? error.message\n : String(error ?? 'Unknown error');\n\n return {\n error: `SQL scope analysis failed before validation/execution: ${parserError}`,\n error_type: 'SQL_SCOPE_PARSE_ERROR',\n suggestion:\n 'Rewrite the query into simpler SQL that can be analyzed safely, or extend parser coverage for this dialect feature.',\n sql_attempted: sql,\n parser_dialect: parserDialect,\n parser_error: parserError,\n };\n}\n\nexport function buildOutOfScopePayload(\n sql: string,\n referencedEntities: string[],\n allowedEntities: string[],\n): SQLScopeErrorPayload {\n return {\n error: `Query references entities outside grounded scope: ${referencedEntities.join(', ')}`,\n error_type: 'OUT_OF_SCOPE',\n suggestion:\n 'Restrict the query to grounded tables/views or expand grounding to include the referenced entities.',\n sql_attempted: sql,\n referenced_entities: referencedEntities,\n allowed_entities: allowedEntities,\n };\n}\n", "import { buildOutOfScopePayload } from '../../sql-scope-error.ts';\nimport type { SqlPolicyViolation } from '../sql-policy.ts';\nimport type { Relations } from './facts.ts';\nimport type { PolicyCheck, Rule } from './source-policy.ts';\n\n/** Decides which relations, as the SQL writes them, the allowed entities cover. */\nexport interface NameMatcher {\n allowing(allowed: readonly string[]): Promise<(relation: string) => boolean>;\n}\n\n/**\n * The SQL reads only relations of its grounded scope. SQL that reads no\n * relation never resolves the scope.\n */\nexport class InScope implements Rule<Relations> {\n readonly #names: NameMatcher;\n\n constructor(names: NameMatcher) {\n this.#names = names;\n }\n\n readonly check = async (\n facts: Relations,\n check: PolicyCheck,\n ): Promise<SqlPolicyViolation | null> => {\n const relations = await facts.relations();\n if (relations.length === 0) return null;\n\n const allowed = await check.resolveAllowedEntities();\n const isAllowed = await this.#names.allowing(allowed);\n const outOfScope = relations.filter((relation) => !isAllowed(relation));\n return outOfScope.length === 0\n ? null\n : {\n kind: 'scope',\n payload: buildOutOfScopePayload(check.sql, outOfScope, [...allowed]),\n };\n };\n}\n\n/**\n * Matches names without case. A one-part name matches an allowed entity by\n * its full name or by its last part; a longer name matches by its full name,\n * and a name of three or more parts also by its last two parts.\n */\nexport class GroundedNames implements NameMatcher {\n async allowing(allowed: readonly string[]) {\n const qualified = new Set(allowed.map((entity) => entity.toLowerCase()));\n const unqualified = new Set(\n allowed.map((entity) =>\n entity.slice(entity.lastIndexOf('.') + 1).toLowerCase(),\n ),\n );\n\n return (relation: string) => {\n const name = relation.toLowerCase();\n if (qualified.has(name)) return true;\n if (!name.includes('.')) return unqualified.has(name);\n const parts = name.split('.');\n return parts.length >= 3 && qualified.has(parts.slice(-2).join('.'));\n };\n }\n}\n", "import type { Statements } from './facts.ts';\nimport { readOnly } from './read-only.ts';\nimport type { Rule } from './source-policy.ts';\n\n/** The SQL is exactly one SELECT, which writes nowhere. */\nexport class OneSelect implements Rule<Statements> {\n readonly check = async (facts: Statements) => {\n const statements = await facts.statements();\n return statements.length === 1 && statements[0]?.kind === 'select'\n ? null\n : readOnly;\n };\n}\n", "import { buildScopeParseErrorPayload } from '../../sql-scope-error.ts';\nimport type {\n SqlPolicyAnalyzer,\n SqlPolicyContext,\n SqlPolicyViolation,\n} from '../sql-policy.ts';\n\n/** What a rule reads besides the facts: the SQL and its grounded scope. */\nexport interface PolicyCheck extends SqlPolicyContext {\n readonly sql: string;\n}\n\n/**\n * Reads SQL into facts. A fact is computed when a rule first asks for it and\n * is kept for that read, so a rule that is never reached costs nothing.\n */\nexport interface FactSource<F> {\n /** The dialect that a parse error names. */\n readonly dialect: string;\n read(sql: string): F;\n}\n\n/**\n * One check over the facts of a source. `check` is a property, not a method,\n * so TypeScript compares its parameter strictly: a rule over facts that the\n * source does not give does not compile.\n */\nexport interface Rule<in F> {\n readonly check: (\n facts: F,\n check: PolicyCheck,\n ) => Promise<SqlPolicyViolation | null>;\n}\n\n/**\n * A source could not read the SQL. A policy turns this error, and only this\n * error, into an SQL_SCOPE_PARSE_ERROR; every other error rejects the check.\n */\nexport class UnreadableSql extends Error {\n override readonly name = 'UnreadableSql';\n}\n\n/**\n * One fact source and its rules, in order. The first violation wins, so the\n * rules after it never ask for their facts.\n */\nexport class SourcePolicy<F> implements SqlPolicyAnalyzer {\n readonly #source: FactSource<F>;\n readonly #rules: readonly Rule<F>[];\n\n constructor(\n source: FactSource<F>,\n rules: readonly [Rule<NoInfer<F>>, ...Rule<NoInfer<F>>[]],\n ) {\n this.#source = source;\n this.#rules = rules;\n }\n\n async analyze(\n sql: string,\n context: SqlPolicyContext,\n ): Promise<SqlPolicyViolation | null> {\n const check: PolicyCheck = {\n sql,\n resolveAllowedEntities: () => context.resolveAllowedEntities(),\n };\n try {\n const facts = this.#source.read(sql);\n for (const rule of this.#rules) {\n const violation = await rule.check(facts, check);\n if (violation) return violation;\n }\n return null;\n } catch (error) {\n if (!(error instanceof UnreadableSql)) throw error;\n return {\n kind: 'scope',\n payload: buildScopeParseErrorPayload(sql, this.#source.dialect, error),\n };\n }\n }\n}\n\n/** Policies in order. The first violation wins. */\nexport class FirstViolation implements SqlPolicyAnalyzer {\n readonly #policies: readonly SqlPolicyAnalyzer[];\n\n constructor(\n ...policies: [SqlPolicyAnalyzer, SqlPolicyAnalyzer, ...SqlPolicyAnalyzer[]]\n ) {\n this.#policies = policies;\n }\n\n async analyze(\n sql: string,\n context: SqlPolicyContext,\n ): Promise<SqlPolicyViolation | null> {\n for (const policy of this.#policies) {\n const violation = await policy.analyze(sql, context);\n if (violation) return violation;\n }\n return null;\n }\n}\n", "import nodeSqlParser from 'node-sql-parser';\n\nimport type { Calls, Relations, Statement, Statements } from './facts.ts';\nimport { type FactSource, UnreadableSql } from './source-policy.ts';\n\nexport type ParserDialect =\n 'bigquery' | 'mysql' | 'postgresql' | 'sqlite' | 'transactsql';\n\n/**\n * A construct of SQL text that a SELECT can hold:\n * - `table-hint`: a table hint such as SQL Server's `WITH (UPDLOCK)`\n * - `server-relation`: a relation on a linked server, `server.db.schema.table`\n * - `locking-read`: `FOR UPDATE` or `LOCK IN SHARE MODE`\n * - `assignment`: a variable assignment such as MySQL's `@x := 1`\n */\nexport type Construct =\n 'assignment' | 'locking-read' | 'server-relation' | 'table-hint';\n\nexport interface Constructs {\n constructs(): Promise<ReadonlySet<Construct>>;\n}\n\nexport type TextFacts = Statements & Relations & Calls & Constructs;\n\nexport interface SqlTextOptions {\n /**\n * The grammars of node-sql-parser, tried in order. The first grammar that\n * parses the SQL gives every fact; a parse error names the last grammar\n * and reports its error.\n */\n readonly dialects: readonly [ParserDialect, ...ParserDialect[]];\n /**\n * Rewrites SQL that a grammar rejects into equivalent SQL that it parses,\n * or gives null. It runs again after each failure, until it gives null or\n * SQL that it gave before.\n */\n readonly recover?: (sql: string, error: unknown) => string | null;\n}\n\ntype AstLike = Record<string, unknown>;\n\ntype ScopeVisitState = {\n cteNames: Set<string>;\n references: Set<string>;\n};\n\nconst { Parser } = nodeSqlParser;\nconst parser = new Parser();\n\n/**\n * Reads SQL text with node-sql-parser. It parses the SQL once per read, when\n * a rule first asks for a fact. SQL that no grammar parses gives no fact but\n * its statements: SQL that starts with a keyword other than SELECT or WITH\n * is one statement of that name, and SQL with no keyword has no statement.\n * Every other fact of such SQL throws UnreadableSql.\n */\nexport class SqlText implements FactSource<TextFacts> {\n readonly dialect: ParserDialect;\n readonly #dialects: readonly ParserDialect[];\n readonly #recover: SqlTextOptions['recover'];\n\n constructor(options: SqlTextOptions) {\n this.#dialects = options.dialects;\n this.#recover = options.recover;\n [this.dialect] = options.dialects.slice(-1);\n }\n\n read(sql: string): TextFacts {\n let parsed: { ast: unknown } | { error: UnreadableSql } | undefined;\n const parse = () => (parsed ??= this.#parse(sql));\n const ast = () => {\n const result = parse();\n if ('error' in result) throw result.error;\n return result.ast;\n };\n\n return {\n statements: async () => {\n const result = parse();\n if ('ast' in result) return statementNodes(result.ast).map(toStatement);\n const keyword = firstStatementKeyword(sql);\n if (keyword === 'SELECT' || keyword === 'WITH') throw result.error;\n return keyword === null ? [] : [{ kind: 'other', name: keyword }];\n },\n relations: async () => baseRelations(ast()),\n calls: async () => calls(ast()),\n constructs: async () => constructs(ast()),\n };\n }\n\n #parse(sql: string): { ast: unknown } | { error: UnreadableSql } {\n let lastError: unknown;\n for (const dialect of this.#dialects) {\n try {\n return { ast: this.#astify(sql, dialect) };\n } catch (error) {\n lastError = error;\n }\n }\n return {\n error: new UnreadableSql(\n Error.isError(lastError) ? lastError.message : String(lastError),\n { cause: lastError },\n ),\n };\n }\n\n #astify(sql: string, dialect: ParserDialect): unknown {\n let parserSql = sql;\n const attempted = new Set([sql]);\n\n while (true) {\n try {\n return parser.astify(parserSql, { database: dialect });\n } catch (error) {\n const recovered = this.#recover?.(parserSql, error);\n if (!recovered || attempted.has(recovered)) throw error;\n attempted.add(recovered);\n parserSql = recovered;\n }\n }\n }\n}\n\nfunction statementNodes(ast: unknown): AstLike[] {\n const statements: unknown[] = Array.isArray(ast) ? ast : [ast];\n return statements.filter(isAstLike);\n}\n\nfunction toStatement(node: AstLike): Statement {\n if (node.type !== 'select') return { kind: 'other', name: String(node.type) };\n return nodes(node).some(\n (child) =>\n child.type === 'select' &&\n isAstLike(child.into) &&\n child.into.type === 'into',\n )\n ? { kind: 'select-into' }\n : { kind: 'select' };\n}\n\nfunction calls(ast: unknown): string[][] {\n return nodes(ast)\n .filter((node) => node.type === 'function')\n .map(functionNameParts)\n .filter((parts) => parts.length > 0)\n .toArray();\n}\n\nfunction constructs(ast: unknown): ReadonlySet<Construct> {\n const found = new Set<Construct>();\n for (const node of nodes(ast)) {\n if (node.table_hint != null) found.add('table-hint');\n if (node.locking_read != null) found.add('locking-read');\n if (node.type === 'assign') found.add('assignment');\n if (isTableReferenceNode(node) && typeof node.server === 'string') {\n found.add('server-relation');\n }\n }\n return found;\n}\n\n/** Every object node of the AST, depth first. */\nfunction* nodes(node: unknown): Generator<AstLike, void, undefined> {\n if (Array.isArray(node)) {\n for (const item of node) yield* nodes(item);\n return;\n }\n if (!isAstLike(node)) return;\n yield node;\n for (const value of Object.values(node)) yield* nodes(value);\n}\n\nfunction functionNameParts(node: AstLike): string[] {\n if (!isAstLike(node.name)) return [];\n const parts: string[] = [];\n\n if (\n isAstLike(node.name.schema) &&\n typeof node.name.schema.value === 'string'\n ) {\n parts.push(...identifierParts(node.name.schema.value));\n }\n\n const names = Array.isArray(node.name.name) ? node.name.name : [];\n for (const name of names) {\n if (isAstLike(name) && typeof name.value === 'string') {\n parts.push(...identifierParts(name.value));\n }\n }\n\n return parts;\n}\n\nfunction identifierParts(value: string): string[] {\n return value.split('.').filter((part) => part.length > 0);\n}\n\nfunction firstStatementKeyword(sql: string): string | null {\n let offset = 0;\n\n while (offset < sql.length) {\n if (/\\s/.test(sql[offset])) {\n offset++;\n continue;\n }\n\n if (sql.startsWith('--', offset)) {\n offset += 2;\n while (\n offset < sql.length &&\n sql[offset] !== '\\n' &&\n sql[offset] !== '\\r'\n ) {\n offset++;\n }\n continue;\n }\n\n if (sql.startsWith('/*', offset)) {\n const commentEnd = sql.indexOf('*/', offset + 2);\n if (commentEnd === -1) return null;\n offset = commentEnd + 2;\n continue;\n }\n\n const keyword = /^[A-Za-z]+/.exec(sql.slice(offset));\n return keyword ? keyword[0].toUpperCase() : null;\n }\n\n return null;\n}\n\nfunction baseRelations(ast: unknown): string[] {\n const state: ScopeVisitState = {\n cteNames: new Set<string>(),\n references: new Set<string>(),\n };\n\n visitNode(ast, state);\n return [...state.references];\n}\n\nfunction visitNode(node: unknown, state: ScopeVisitState): void {\n if (Array.isArray(node)) {\n for (const item of node) visitNode(item, state);\n return;\n }\n if (!isAstLike(node)) return;\n\n if (isStatementNode(node)) {\n visitStatement(node, state);\n return;\n }\n\n if (isTableReferenceNode(node)) addReference(node, state);\n for (const value of Object.values(node)) visitNode(value, state);\n}\n\nfunction visitStatement(node: AstLike, parentState: ScopeVisitState): void {\n const localState: ScopeVisitState = {\n cteNames: new Set(parentState.cteNames),\n references: parentState.references,\n };\n const withItems = Array.isArray(node.with) ? node.with : [];\n\n for (const item of withItems) {\n if (!isAstLike(item)) continue;\n const cteName = readCteName(item);\n if (cteName) localState.cteNames.add(cteName.toLowerCase());\n }\n\n for (const item of withItems) {\n if (isAstLike(item)) visitNode(item.stmt, localState);\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (key !== 'with') visitNode(value, localState);\n }\n}\n\nfunction addReference(node: AstLike, state: ScopeVisitState): void {\n const table = typeof node.table === 'string' ? node.table : null;\n if (!table || state.cteNames.has(table.toLowerCase())) return;\n\n const db = typeof node.db === 'string' ? node.db : null;\n state.references.add(db ? `${db}.${table}` : table);\n}\n\nfunction readCteName(node: AstLike): string | undefined {\n const name = node.name;\n if (typeof name === 'string') return name;\n if (!isAstLike(name)) return undefined;\n return typeof name.value === 'string' ? name.value : undefined;\n}\n\nfunction isStatementNode(node: AstLike): boolean {\n return (\n typeof node.type === 'string' &&\n ['delete', 'insert', 'replace', 'select', 'update'].includes(node.type)\n );\n}\n\nfunction isTableReferenceNode(node: AstLike): boolean {\n if (node.type === 'column_ref' || typeof node.table !== 'string')\n return false;\n\n return (\n 'addition' in node ||\n 'as' in node ||\n 'db' in node ||\n 'join' in node ||\n 'operator' in node ||\n 'surround' in node ||\n 'table_hint' in node ||\n 'temporal_table' in node\n );\n}\n\nfunction isAstLike(value: unknown): value is AstLike {\n return typeof value === 'object' && value !== null;\n}\n"],
5
- "mappings": ";AAGO,IAAM,WAA+B,OAAO,OAAO;AAAA,EACxD,MAAM;AAAA,EACN,SAAS;AACX,CAAC;;;ACQM,IAAM,cAAN,MAAyC;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAsB;AAChC,SAAK,SAAS,IAAI,IAAI,QAAQ,OAAO,IAAI,CAAC,SAAS,KAAK,YAAY,CAAC,CAAC;AACtE,SAAK,YACH,QAAQ,UAAU,IAAI,CAAC,WAAW,OAAO,YAAY,CAAC,KAAK,CAAC;AAC9D,SAAK,aAAa,QAAQ,cAAc;AAAA,EAC1C;AAAA,EAES,QAAQ,OAAO,UAAiB;AACvC,UAAMA,SAAQ,MAAM,MAAM,MAAM;AAChC,WAAOA,OAAM,KAAK,CAAC,UAAU,KAAK,QAAQ,KAAK,CAAC,IAAI,WAAW;AAAA,EACjE;AAAA,EAEA,QAAQ,OAAmC;AACzC,QAAI,KAAK,cAAc,MAAM,SAAS,EAAG,QAAO;AAChD,UAAM,OAAO,MAAM,GAAG,EAAE,GAAG,YAAY;AACvC,QAAI,SAAS,OAAW,QAAO;AAC/B,WACE,KAAK,OAAO,IAAI,IAAI,KACpB,KAAK,UAAU,KAAK,CAAC,WAAW,KAAK,WAAW,MAAM,CAAC;AAAA,EAE3D;AACF;;;ACnCO,IAAM,SAAN,MAAyC;AAAA,EACrC;AAAA,EAET,YAAY,WAAiD;AAC3D,SAAK,aAAa;AAAA,EACpB;AAAA,EAES,QAAQ,OAAO,UAAsB;AAC5C,UAAM,QAAQ,MAAM,MAAM,WAAW;AACrC,WAAO,KAAK,WAAW,KAAK,CAAC,cAAc,MAAM,IAAI,SAAS,CAAC,IAC3D,WACA;AAAA,EACN;AACF;;;AChBO,SAAS,4BACd,KACA,eACA,OACsB;AACt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,QACd,gBAAgB,QAChB,oBAAoB;AAExB;AAEA,SAAS,UAAU,OAAkC;AACnD,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;",
4
+ "sourcesContent": ["import type { SqlPolicyViolation } from '../sql-policy.ts';\n\n/** The violation of SQL that could write, lock or leave the database. */\nexport const readOnly: SqlPolicyViolation = Object.freeze({\n kind: 'read-only',\n message: 'only SELECT or WITH queries allowed',\n});\n", "import type { Calls } from './facts.ts';\nimport { readOnly } from './read-only.ts';\nimport type { Rule } from './source-policy.ts';\n\nexport interface CallDenials {\n /** Function names, matched without case against a call's last name part. */\n readonly names?: readonly string[];\n /** Name prefixes, matched without case against a call's last name part. */\n readonly prefixes?: readonly string[];\n /** Deny every call whose name has more than one part, such as `dataset.fn`. */\n readonly qualified?: true;\n}\n\n/** The SQL calls none of the denied functions. */\nexport class DeniedCalls implements Rule<Calls> {\n readonly #names: ReadonlySet<string>;\n readonly #prefixes: readonly string[];\n readonly #qualified: boolean;\n\n constructor(denials: CallDenials) {\n this.#names = new Set(denials.names?.map((name) => name.toLowerCase()));\n this.#prefixes =\n denials.prefixes?.map((prefix) => prefix.toLowerCase()) ?? [];\n this.#qualified = denials.qualified === true;\n }\n\n readonly check = async (facts: Calls) => {\n const calls = await facts.calls();\n return calls.some((parts) => this.#denies(parts)) ? readOnly : null;\n };\n\n #denies(parts: readonly string[]): boolean {\n if (this.#qualified && parts.length > 1) return true;\n const name = parts.at(-1)?.toLowerCase();\n if (name === undefined) return false;\n return (\n this.#names.has(name) ||\n this.#prefixes.some((prefix) => name.startsWith(prefix))\n );\n }\n}\n", "import { readOnly } from './read-only.ts';\nimport type { Rule } from './source-policy.ts';\nimport type { Construct, Constructs } from './sql-text.ts';\n\n/** The SQL holds none of the forbidden constructs. */\nexport class Forbid implements Rule<Constructs> {\n readonly #forbidden: readonly Construct[];\n\n constructor(forbidden: readonly [Construct, ...Construct[]]) {\n this.#forbidden = forbidden;\n }\n\n readonly check = async (facts: Constructs) => {\n const found = await facts.constructs();\n return this.#forbidden.some((construct) => found.has(construct))\n ? readOnly\n : null;\n };\n}\n", "import type { SQLScopeErrorPayload } from './agents/exceptions.ts';\n\nexport function buildScopeParseErrorPayload(\n sql: string,\n parserDialect: string,\n error: unknown,\n): SQLScopeErrorPayload {\n const parserError = Error.isError(error)\n ? error.message\n : String(error ?? 'Unknown error');\n\n return {\n error: `SQL scope analysis failed before validation/execution: ${parserError}`,\n error_type: 'SQL_SCOPE_PARSE_ERROR',\n suggestion:\n 'Rewrite the query into simpler SQL that can be analyzed safely, or extend parser coverage for this dialect feature.',\n sql_attempted: sql,\n parser_dialect: parserDialect,\n parser_error: parserError,\n };\n}\n\n/**\n * Why SQL is out of scope: it reads entities outside the grounded scope, or\n * the database refused it for the principal that compiled it, in the\n * database's own words.\n */\nexport type OutOfScope =\n | { readonly referenced: string[]; readonly allowed: string[] }\n | { readonly denial: string };\n\nexport function buildOutOfScopePayload(\n sql: string,\n scope: OutOfScope,\n): SQLScopeErrorPayload {\n if ('denial' in scope) {\n return {\n error: scope.denial,\n error_type: 'OUT_OF_SCOPE',\n suggestion:\n 'Read only the tables and views that the database grants, in one SELECT that writes nothing.',\n sql_attempted: sql,\n };\n }\n return {\n error: `Query references entities outside grounded scope: ${scope.referenced.join(', ')}`,\n error_type: 'OUT_OF_SCOPE',\n suggestion:\n 'Restrict the query to grounded tables/views or expand grounding to include the referenced entities.',\n sql_attempted: sql,\n referenced_entities: scope.referenced,\n allowed_entities: scope.allowed,\n };\n}\n", "import { buildOutOfScopePayload } from '../../sql-scope-error.ts';\nimport type { SqlPolicyViolation } from '../sql-policy.ts';\nimport type { Relations } from './facts.ts';\nimport type { PolicyCheck, Rule } from './source-policy.ts';\n\n/** Decides which relations, as the SQL writes them, the allowed entities cover. */\nexport interface NameMatcher {\n allowing(allowed: readonly string[]): Promise<(relation: string) => boolean>;\n}\n\n/**\n * The SQL reads only relations of its grounded scope. SQL that reads no\n * relation never resolves the scope.\n */\nexport class InScope implements Rule<Relations> {\n readonly #names: NameMatcher;\n\n constructor(names: NameMatcher) {\n this.#names = names;\n }\n\n readonly check = async (\n facts: Relations,\n check: PolicyCheck,\n ): Promise<SqlPolicyViolation | null> => {\n const relations = await facts.relations();\n if (relations.length === 0) return null;\n\n const allowed = await check.resolveAllowedEntities();\n const isAllowed = await this.#names.allowing(allowed);\n const outOfScope = relations.filter((relation) => !isAllowed(relation));\n return outOfScope.length === 0\n ? null\n : {\n kind: 'scope',\n payload: buildOutOfScopePayload(check.sql, {\n referenced: outOfScope,\n allowed: [...allowed],\n }),\n };\n };\n}\n\n/**\n * Matches names without case. A one-part name matches an allowed entity by\n * its full name or by its last part; a longer name matches by its full name,\n * and a name of three or more parts also by its last two parts.\n */\nexport class GroundedNames implements NameMatcher {\n async allowing(allowed: readonly string[]) {\n const qualified = new Set(allowed.map((entity) => entity.toLowerCase()));\n const unqualified = new Set(\n allowed.map((entity) =>\n entity.slice(entity.lastIndexOf('.') + 1).toLowerCase(),\n ),\n );\n\n return (relation: string) => {\n const name = relation.toLowerCase();\n if (qualified.has(name)) return true;\n if (!name.includes('.')) return unqualified.has(name);\n const parts = name.split('.');\n return parts.length >= 3 && qualified.has(parts.slice(-2).join('.'));\n };\n }\n}\n", "import type { Statements } from './facts.ts';\nimport { readOnly } from './read-only.ts';\nimport type { Rule } from './source-policy.ts';\n\n/** The SQL is exactly one SELECT, which writes nowhere. */\nexport class OneSelect implements Rule<Statements> {\n readonly check = async (facts: Statements) => {\n const statements = await facts.statements();\n return statements.length === 1 && statements[0]?.kind === 'select'\n ? null\n : readOnly;\n };\n}\n", "import { buildScopeParseErrorPayload } from '../../sql-scope-error.ts';\nimport type {\n SqlPolicyAnalyzer,\n SqlPolicyContext,\n SqlPolicyViolation,\n} from '../sql-policy.ts';\n\n/** What a rule reads besides the facts: the SQL and its grounded scope. */\nexport interface PolicyCheck extends SqlPolicyContext {\n readonly sql: string;\n}\n\n/**\n * Reads SQL into facts. A fact is computed when a rule first asks for it and\n * is kept for that read, so a rule that is never reached costs nothing.\n */\nexport interface FactSource<F> {\n /** The dialect that a parse error names. */\n readonly dialect: string;\n read(sql: string): F;\n}\n\n/**\n * One check over the facts of a source. `check` is a property, not a method,\n * so TypeScript compares its parameter strictly: a rule over facts that the\n * source does not give does not compile.\n */\nexport interface Rule<in F> {\n readonly check: (\n facts: F,\n check: PolicyCheck,\n ) => Promise<SqlPolicyViolation | null>;\n}\n\nconst unreadable = Symbol.for('@deepagents/text2sql/UnreadableSql');\n\n/**\n * A source could not read the SQL. A policy turns this error, and only this\n * error, into an SQL_SCOPE_PARSE_ERROR; every other error rejects the check.\n *\n * Each entry point of the package bundles its own copy of this class, so\n * `instanceof` reads a mark in the global symbol registry: a source of\n * `./sqlserver` and a `SourcePolicy` of `./policy` agree on the error.\n */\nexport class UnreadableSql extends Error {\n override readonly name = 'UnreadableSql';\n\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n Object.defineProperty(this, unreadable, { value: true });\n }\n\n static override [Symbol.hasInstance](value: unknown): value is UnreadableSql {\n return Error.isError(value) && Object.hasOwn(value, unreadable);\n }\n}\n\n/**\n * One fact source and its rules, in order. The first violation wins, so the\n * rules after it never ask for their facts.\n */\nexport class SourcePolicy<F> implements SqlPolicyAnalyzer {\n readonly #source: FactSource<F>;\n readonly #rules: readonly Rule<F>[];\n\n constructor(\n source: FactSource<F>,\n rules: readonly [Rule<NoInfer<F>>, ...Rule<NoInfer<F>>[]],\n ) {\n this.#source = source;\n this.#rules = rules;\n }\n\n async analyze(\n sql: string,\n context: SqlPolicyContext,\n ): Promise<SqlPolicyViolation | null> {\n const check: PolicyCheck = {\n sql,\n resolveAllowedEntities: () => context.resolveAllowedEntities(),\n };\n try {\n const facts = this.#source.read(sql);\n for (const rule of this.#rules) {\n const violation = await rule.check(facts, check);\n if (violation) return violation;\n }\n return null;\n } catch (error) {\n if (!(error instanceof UnreadableSql)) throw error;\n return {\n kind: 'scope',\n payload: buildScopeParseErrorPayload(sql, this.#source.dialect, error),\n };\n }\n }\n}\n\n/** Policies in order. The first violation wins. */\nexport class FirstViolation implements SqlPolicyAnalyzer {\n readonly #policies: readonly SqlPolicyAnalyzer[];\n\n constructor(\n ...policies: [SqlPolicyAnalyzer, SqlPolicyAnalyzer, ...SqlPolicyAnalyzer[]]\n ) {\n this.#policies = policies;\n }\n\n async analyze(\n sql: string,\n context: SqlPolicyContext,\n ): Promise<SqlPolicyViolation | null> {\n for (const policy of this.#policies) {\n const violation = await policy.analyze(sql, context);\n if (violation) return violation;\n }\n return null;\n }\n}\n", "import nodeSqlParser from 'node-sql-parser';\n\nimport type { Calls, Relations, Statement, Statements } from './facts.ts';\nimport { type FactSource, UnreadableSql } from './source-policy.ts';\n\nexport type ParserDialect =\n 'bigquery' | 'mysql' | 'postgresql' | 'sqlite' | 'transactsql';\n\n/**\n * A construct of SQL text that a SELECT can hold:\n * - `table-hint`: a table hint such as SQL Server's `WITH (UPDLOCK)`\n * - `server-relation`: a relation on a linked server, `server.db.schema.table`\n * - `locking-read`: `FOR UPDATE` or `LOCK IN SHARE MODE`\n * - `assignment`: a variable assignment such as MySQL's `@x := 1`\n */\nexport type Construct =\n 'assignment' | 'locking-read' | 'server-relation' | 'table-hint';\n\nexport interface Constructs {\n constructs(): Promise<ReadonlySet<Construct>>;\n}\n\nexport type TextFacts = Statements & Relations & Calls & Constructs;\n\nexport interface SqlTextOptions {\n /**\n * The grammars of node-sql-parser, tried in order. The first grammar that\n * parses the SQL gives every fact; a parse error names the last grammar\n * and reports its error.\n */\n readonly dialects: readonly [ParserDialect, ...ParserDialect[]];\n /**\n * Rewrites SQL that a grammar rejects into equivalent SQL that it parses,\n * or gives null. It runs again after each failure, until it gives null or\n * SQL that it gave before.\n */\n readonly recover?: (sql: string, error: unknown) => string | null;\n}\n\ntype AstLike = Record<string, unknown>;\n\ntype ScopeVisitState = {\n cteNames: Set<string>;\n references: Set<string>;\n};\n\nconst { Parser } = nodeSqlParser;\nconst parser = new Parser();\n\n/**\n * Reads SQL text with node-sql-parser. It parses the SQL once per read, when\n * a rule first asks for a fact. SQL that no grammar parses gives no fact but\n * its statements: SQL that starts with a keyword other than SELECT or WITH\n * is one statement of that name, and SQL with no keyword has no statement.\n * Every other fact of such SQL throws UnreadableSql.\n */\nexport class SqlText implements FactSource<TextFacts> {\n readonly dialect: ParserDialect;\n readonly #dialects: readonly ParserDialect[];\n readonly #recover: SqlTextOptions['recover'];\n\n constructor(options: SqlTextOptions) {\n this.#dialects = options.dialects;\n this.#recover = options.recover;\n [this.dialect] = options.dialects.slice(-1);\n }\n\n read(sql: string): TextFacts {\n let parsed: { ast: unknown } | { error: UnreadableSql } | undefined;\n const parse = () => (parsed ??= this.#parse(sql));\n const ast = () => {\n const result = parse();\n if ('error' in result) throw result.error;\n return result.ast;\n };\n\n return {\n statements: async () => {\n const result = parse();\n if ('ast' in result) return statementNodes(result.ast).map(toStatement);\n const keyword = firstStatementKeyword(sql);\n if (keyword === 'SELECT' || keyword === 'WITH') throw result.error;\n return keyword === null ? [] : [{ kind: 'other', name: keyword }];\n },\n relations: async () => baseRelations(ast()),\n calls: async () => calls(ast()),\n constructs: async () => constructs(ast()),\n };\n }\n\n #parse(sql: string): { ast: unknown } | { error: UnreadableSql } {\n let lastError: unknown;\n for (const dialect of this.#dialects) {\n try {\n return { ast: this.#astify(sql, dialect) };\n } catch (error) {\n lastError = error;\n }\n }\n return {\n error: new UnreadableSql(\n Error.isError(lastError) ? lastError.message : String(lastError),\n { cause: lastError },\n ),\n };\n }\n\n #astify(sql: string, dialect: ParserDialect): unknown {\n let parserSql = sql;\n const attempted = new Set([sql]);\n\n while (true) {\n try {\n return parser.astify(parserSql, { database: dialect });\n } catch (error) {\n const recovered = this.#recover?.(parserSql, error);\n if (!recovered || attempted.has(recovered)) throw error;\n attempted.add(recovered);\n parserSql = recovered;\n }\n }\n }\n}\n\nfunction statementNodes(ast: unknown): AstLike[] {\n const statements: unknown[] = Array.isArray(ast) ? ast : [ast];\n return statements.filter(isAstLike);\n}\n\nfunction toStatement(node: AstLike): Statement {\n if (node.type !== 'select') return { kind: 'other', name: String(node.type) };\n return nodes(node).some(\n (child) =>\n child.type === 'select' &&\n isAstLike(child.into) &&\n child.into.type === 'into',\n )\n ? { kind: 'select-into' }\n : { kind: 'select' };\n}\n\nfunction calls(ast: unknown): string[][] {\n return nodes(ast)\n .filter((node) => node.type === 'function')\n .map(functionNameParts)\n .filter((parts) => parts.length > 0)\n .toArray();\n}\n\nfunction constructs(ast: unknown): ReadonlySet<Construct> {\n const found = new Set<Construct>();\n for (const node of nodes(ast)) {\n if (node.table_hint != null) found.add('table-hint');\n if (node.locking_read != null) found.add('locking-read');\n if (node.type === 'assign') found.add('assignment');\n if (isTableReferenceNode(node) && typeof node.server === 'string') {\n found.add('server-relation');\n }\n }\n return found;\n}\n\n/** Every object node of the AST, depth first. */\nfunction* nodes(node: unknown): Generator<AstLike, void, undefined> {\n if (Array.isArray(node)) {\n for (const item of node) yield* nodes(item);\n return;\n }\n if (!isAstLike(node)) return;\n yield node;\n for (const value of Object.values(node)) yield* nodes(value);\n}\n\nfunction functionNameParts(node: AstLike): string[] {\n if (!isAstLike(node.name)) return [];\n const parts: string[] = [];\n\n if (\n isAstLike(node.name.schema) &&\n typeof node.name.schema.value === 'string'\n ) {\n parts.push(...identifierParts(node.name.schema.value));\n }\n\n const names = Array.isArray(node.name.name) ? node.name.name : [];\n for (const name of names) {\n if (isAstLike(name) && typeof name.value === 'string') {\n parts.push(...identifierParts(name.value));\n }\n }\n\n return parts;\n}\n\nfunction identifierParts(value: string): string[] {\n return value.split('.').filter((part) => part.length > 0);\n}\n\nfunction firstStatementKeyword(sql: string): string | null {\n let offset = 0;\n\n while (offset < sql.length) {\n if (/\\s/.test(sql[offset])) {\n offset++;\n continue;\n }\n\n if (sql.startsWith('--', offset)) {\n offset += 2;\n while (\n offset < sql.length &&\n sql[offset] !== '\\n' &&\n sql[offset] !== '\\r'\n ) {\n offset++;\n }\n continue;\n }\n\n if (sql.startsWith('/*', offset)) {\n const commentEnd = sql.indexOf('*/', offset + 2);\n if (commentEnd === -1) return null;\n offset = commentEnd + 2;\n continue;\n }\n\n const keyword = /^[A-Za-z]+/.exec(sql.slice(offset));\n return keyword ? keyword[0].toUpperCase() : null;\n }\n\n return null;\n}\n\nfunction baseRelations(ast: unknown): string[] {\n const state: ScopeVisitState = {\n cteNames: new Set<string>(),\n references: new Set<string>(),\n };\n\n visitNode(ast, state);\n return [...state.references];\n}\n\nfunction visitNode(node: unknown, state: ScopeVisitState): void {\n if (Array.isArray(node)) {\n for (const item of node) visitNode(item, state);\n return;\n }\n if (!isAstLike(node)) return;\n\n if (isStatementNode(node)) {\n visitStatement(node, state);\n return;\n }\n\n if (isTableReferenceNode(node)) addReference(node, state);\n for (const value of Object.values(node)) visitNode(value, state);\n}\n\nfunction visitStatement(node: AstLike, parentState: ScopeVisitState): void {\n const localState: ScopeVisitState = {\n cteNames: new Set(parentState.cteNames),\n references: parentState.references,\n };\n const withItems = Array.isArray(node.with) ? node.with : [];\n\n for (const item of withItems) {\n if (!isAstLike(item)) continue;\n const cteName = readCteName(item);\n if (cteName) localState.cteNames.add(cteName.toLowerCase());\n }\n\n for (const item of withItems) {\n if (isAstLike(item)) visitNode(item.stmt, localState);\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (key !== 'with') visitNode(value, localState);\n }\n}\n\nfunction addReference(node: AstLike, state: ScopeVisitState): void {\n const table = typeof node.table === 'string' ? node.table : null;\n if (!table || state.cteNames.has(table.toLowerCase())) return;\n\n const db = typeof node.db === 'string' ? node.db : null;\n state.references.add(db ? `${db}.${table}` : table);\n}\n\nfunction readCteName(node: AstLike): string | undefined {\n const name = node.name;\n if (typeof name === 'string') return name;\n if (!isAstLike(name)) return undefined;\n return typeof name.value === 'string' ? name.value : undefined;\n}\n\nfunction isStatementNode(node: AstLike): boolean {\n return (\n typeof node.type === 'string' &&\n ['delete', 'insert', 'replace', 'select', 'update'].includes(node.type)\n );\n}\n\nfunction isTableReferenceNode(node: AstLike): boolean {\n if (node.type === 'column_ref' || typeof node.table !== 'string')\n return false;\n\n return (\n 'addition' in node ||\n 'as' in node ||\n 'db' in node ||\n 'join' in node ||\n 'operator' in node ||\n 'surround' in node ||\n 'table_hint' in node ||\n 'temporal_table' in node\n );\n}\n\nfunction isAstLike(value: unknown): value is AstLike {\n return typeof value === 'object' && value !== null;\n}\n"],
5
+ "mappings": ";AAGO,IAAM,WAA+B,OAAO,OAAO;AAAA,EACxD,MAAM;AAAA,EACN,SAAS;AACX,CAAC;;;ACQM,IAAM,cAAN,MAAyC;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAAsB;AAChC,SAAK,SAAS,IAAI,IAAI,QAAQ,OAAO,IAAI,CAAC,SAAS,KAAK,YAAY,CAAC,CAAC;AACtE,SAAK,YACH,QAAQ,UAAU,IAAI,CAAC,WAAW,OAAO,YAAY,CAAC,KAAK,CAAC;AAC9D,SAAK,aAAa,QAAQ,cAAc;AAAA,EAC1C;AAAA,EAES,QAAQ,OAAO,UAAiB;AACvC,UAAMA,SAAQ,MAAM,MAAM,MAAM;AAChC,WAAOA,OAAM,KAAK,CAAC,UAAU,KAAK,QAAQ,KAAK,CAAC,IAAI,WAAW;AAAA,EACjE;AAAA,EAEA,QAAQ,OAAmC;AACzC,QAAI,KAAK,cAAc,MAAM,SAAS,EAAG,QAAO;AAChD,UAAM,OAAO,MAAM,GAAG,EAAE,GAAG,YAAY;AACvC,QAAI,SAAS,OAAW,QAAO;AAC/B,WACE,KAAK,OAAO,IAAI,IAAI,KACpB,KAAK,UAAU,KAAK,CAAC,WAAW,KAAK,WAAW,MAAM,CAAC;AAAA,EAE3D;AACF;;;ACnCO,IAAM,SAAN,MAAyC;AAAA,EACrC;AAAA,EAET,YAAY,WAAiD;AAC3D,SAAK,aAAa;AAAA,EACpB;AAAA,EAES,QAAQ,OAAO,UAAsB;AAC5C,UAAM,QAAQ,MAAM,MAAM,WAAW;AACrC,WAAO,KAAK,W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AAK,OAAO,WAAW,KAAK,KAAK;AACnD,QAAM,WAAW,IAAI,KAAK,GAAG,EAAE,IAAI,KAAK,KAAK,KAAK;AACpD;AAEA,SAAS,YAAY,MAAmC;AACtD,QAAM,OAAO,KAAK;AAClB,MAAI,OAAO,SAAS,SAAU,QAAO;AACrC,MAAI,CAAC,UAAU,IAAI,EAAG,QAAO;AAC7B,SAAO,OAAO,KAAK,UAAU,WAAW,KAAK,QAAQ;AACvD;AAEA,SAAS,gBAAgB,MAAwB;AAC/C,SACE,OAAO,KAAK,SAAS,YACrB,CAAC,UAAU,UAAU,WAAW,UAAU,QAAQ,EAAE,SAAS,KAAK,IAAI;AAE1E;AAEA,SAAS,qBAAqB,MAAwB;AACpD,MAAI,KAAK,SAAS,gBAAgB,OAAO,KAAK,UAAU;AACtD,WAAO;AAET,SACE,cAAc,QACd,QAAQ,QACR,QAAQ,QACR,UAAU,QACV,cAAc,QACd,cAAc,QACd,gBAAgB,QAChB,oBAAoB;AAExB;AAEA,SAAS,UAAU,OAAkC;AACnD,SAAO,OAAO,UAAU,YAAY,UAAU;AAChD;",
6
6
  "names": ["calls"]
7
7
  }
@@ -23,9 +23,15 @@ export interface Rule<in F> {
23
23
  /**
24
24
  * A source could not read the SQL. A policy turns this error, and only this
25
25
  * error, into an SQL_SCOPE_PARSE_ERROR; every other error rejects the check.
26
+ *
27
+ * Each entry point of the package bundles its own copy of this class, so
28
+ * `instanceof` reads a mark in the global symbol registry: a source of
29
+ * `./sqlserver` and a `SourcePolicy` of `./policy` agree on the error.
26
30
  */
27
31
  export declare class UnreadableSql extends Error {
28
32
  readonly name = "UnreadableSql";
33
+ constructor(message: string, options?: ErrorOptions);
34
+ static [Symbol.hasInstance](value: unknown): value is UnreadableSql;
29
35
  }
30
36
  /**
31
37
  * One fact source and its rules, in order. The first violation wins, so the
@@ -1 +1 @@
1
- {"version":3,"file":"source-policy.d.ts","sources":["../../../../src/lib/adapters/policy/source-policy.ts"],"names":[],"mappings":"AACA,OAA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,GACxB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAmBpC;CACF;AAED,mDAAmD;AACnD,qBAAa,cAAe,YAAW,iBAAiB;;IAGtD,YACE,GAAG,QAAQ,EAAE,CAAC,iBAAiB,EAAE,iBAAiB,EAAE,GAAG,iBAAiB,EAAE,CAAC,EAG5E;IAEK,OAAO,CACX,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAMpC;CACF"}
@@ -1600,14 +1600,22 @@ function buildScopeParseErrorPayload(sql, parserDialect, error) {
1600
1600
  parser_error: parserError
1601
1601
  };
1602
1602
  }
1603
- function buildOutOfScopePayload(sql, referencedEntities, allowedEntities) {
1603
+ function buildOutOfScopePayload(sql, scope) {
1604
+ if ("denial" in scope) {
1605
+ return {
1606
+ error: scope.denial,
1607
+ error_type: "OUT_OF_SCOPE",
1608
+ suggestion: "Read only the tables and views that the database grants, in one SELECT that writes nothing.",
1609
+ sql_attempted: sql
1610
+ };
1611
+ }
1604
1612
  return {
1605
- error: `Query references entities outside grounded scope: ${referencedEntities.join(", ")}`,
1613
+ error: `Query references entities outside grounded scope: ${scope.referenced.join(", ")}`,
1606
1614
  error_type: "OUT_OF_SCOPE",
1607
1615
  suggestion: "Restrict the query to grounded tables/views or expand grounding to include the referenced entities.",
1608
1616
  sql_attempted: sql,
1609
- referenced_entities: referencedEntities,
1610
- allowed_entities: allowedEntities
1617
+ referenced_entities: scope.referenced,
1618
+ allowed_entities: scope.allowed
1611
1619
  };
1612
1620
  }
1613
1621
 
@@ -1625,7 +1633,10 @@ var InScope = class {
1625
1633
  const outOfScope = relations.filter((relation) => !isAllowed(relation));
1626
1634
  return outOfScope.length === 0 ? null : {
1627
1635
  kind: "scope",
1628
- payload: buildOutOfScopePayload(check.sql, outOfScope, [...allowed])
1636
+ payload: buildOutOfScopePayload(check.sql, {
1637
+ referenced: outOfScope,
1638
+ allowed: [...allowed]
1639
+ })
1629
1640
  };
1630
1641
  };
1631
1642
  };
@@ -1656,8 +1667,16 @@ var OneSelect = class {
1656
1667
  };
1657
1668
 
1658
1669
  // packages/text2sql/src/lib/adapters/policy/source-policy.ts
1670
+ var unreadable = /* @__PURE__ */ Symbol.for("@deepagents/text2sql/UnreadableSql");
1659
1671
  var UnreadableSql = class extends Error {
1660
1672
  name = "UnreadableSql";
1673
+ constructor(message, options) {
1674
+ super(message, options);
1675
+ Object.defineProperty(this, unreadable, { value: true });
1676
+ }
1677
+ static [Symbol.hasInstance](value) {
1678
+ return Error.isError(value) && Object.hasOwn(value, unreadable);
1679
+ }
1661
1680
  };
1662
1681
  var SourcePolicy = class {
1663
1682
  #source;