@niscorp/vex 0.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 (45) hide show
  1. package/DESIGN.md +881 -0
  2. package/DOCS.md +1295 -0
  3. package/LICENSE +202 -0
  4. package/README.md +97 -0
  5. package/dist/adapters/express/index.cjs +1406 -0
  6. package/dist/adapters/express/index.cjs.map +1 -0
  7. package/dist/adapters/express/index.d.cts +25 -0
  8. package/dist/adapters/express/index.d.ts +25 -0
  9. package/dist/adapters/express/index.js +60 -0
  10. package/dist/adapters/express/index.js.map +1 -0
  11. package/dist/adapters/hono/index.cjs +1426 -0
  12. package/dist/adapters/hono/index.cjs.map +1 -0
  13. package/dist/adapters/hono/index.d.cts +25 -0
  14. package/dist/adapters/hono/index.d.ts +25 -0
  15. package/dist/adapters/hono/index.js +78 -0
  16. package/dist/adapters/hono/index.js.map +1 -0
  17. package/dist/adapters/pglite/index.cjs +17 -0
  18. package/dist/adapters/pglite/index.cjs.map +1 -0
  19. package/dist/adapters/pglite/index.d.cts +21 -0
  20. package/dist/adapters/pglite/index.d.ts +21 -0
  21. package/dist/adapters/pglite/index.js +14 -0
  22. package/dist/adapters/pglite/index.js.map +1 -0
  23. package/dist/agent/index.cjs +478 -0
  24. package/dist/agent/index.cjs.map +1 -0
  25. package/dist/agent/index.d.cts +29 -0
  26. package/dist/agent/index.d.ts +29 -0
  27. package/dist/agent/index.js +313 -0
  28. package/dist/agent/index.js.map +1 -0
  29. package/dist/chunk-FPKW4TRX.js +1528 -0
  30. package/dist/chunk-FPKW4TRX.js.map +1 -0
  31. package/dist/chunk-HF25Q53I.js +165 -0
  32. package/dist/chunk-HF25Q53I.js.map +1 -0
  33. package/dist/handler-Cql8SJ3F.d.cts +133 -0
  34. package/dist/handler-mICf9ins.d.ts +133 -0
  35. package/dist/index.cjs +4078 -0
  36. package/dist/index.cjs.map +1 -0
  37. package/dist/index.d.cts +199 -0
  38. package/dist/index.d.ts +199 -0
  39. package/dist/index.js +2340 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/introspect-D3OaXHBc.d.cts +16 -0
  42. package/dist/introspect-D3OaXHBc.d.ts +16 -0
  43. package/dist/types-BRvMB6IM.d.cts +1491 -0
  44. package/dist/types-BRvMB6IM.d.ts +1491 -0
  45. package/package.json +125 -0
@@ -0,0 +1,478 @@
1
+ 'use strict';
2
+
3
+ var agent = require('@niscorp/prism/agent');
4
+ var prism = require('@niscorp/prism');
5
+ var zod = require('zod');
6
+ var strata = require('@niscorp/strata');
7
+ var cortex = require('@niscorp/cortex');
8
+
9
+ // src/errors.ts
10
+ var VexError = class extends Error {
11
+ code;
12
+ details;
13
+ constructor(code, message, details) {
14
+ super(message);
15
+ this.name = "VexError";
16
+ this.code = code;
17
+ this.details = details;
18
+ }
19
+ };
20
+ var ContextRefSchema = zod.z.object({
21
+ $context: zod.z.string().describe("Key to look up in the request context object")
22
+ }).strict().describe("Reference to a caller-provided context value");
23
+ var ScopeRefSchema = zod.z.object({
24
+ $scope: zod.z.string().describe("Key to look up in the server-side scope values")
25
+ }).strict().describe("Reference to a server-injected scope value (access control)");
26
+ var FieldOrValueSchema = zod.z.union([
27
+ zod.z.string().describe("A field path (entity.field format) or a literal string"),
28
+ zod.z.number().describe("A literal number"),
29
+ zod.z.boolean().describe("A literal boolean"),
30
+ zod.z.null().describe("A literal null"),
31
+ ContextRefSchema,
32
+ ScopeRefSchema
33
+ ]).describe("A field path, literal value, or dynamic reference");
34
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
35
+ var FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]*\.[A-Za-z_][A-Za-z0-9_]*$/;
36
+ var IdentifierSchema = zod.z.string().regex(IDENTIFIER, "A name is letters, digits and underscores, not starting with a digit");
37
+ var FieldPathSchema = zod.z.string().regex(FIELD_PATH, "A field path is entity.field \u2014 each part letters, digits and underscores, not starting with a digit");
38
+
39
+ // src/schemas/filter.schema.ts
40
+ var comparisonPair = zod.z.tuple([FieldOrValueSchema, FieldOrValueSchema]).describe("[left, right] \u2014 both can be field paths, literals, or references");
41
+ var fieldString = FieldPathSchema.describe("Field path in entity.field format");
42
+ var collectionTarget = zod.z.union([
43
+ zod.z.array(FieldOrValueSchema).min(1).describe("Array of literal values or references"),
44
+ ContextRefSchema,
45
+ ScopeRefSchema
46
+ ]).describe("A set of values or a reference that resolves to an array");
47
+ var ExistsSchema = zod.z.lazy(
48
+ () => zod.z.object({
49
+ from: zod.z.array(zod.z.string()).min(1).describe("Entities the subquery reads. Joined by foreign key like any other from."),
50
+ filter: FilterSchema.optional().describe('The correlation, and any extra condition. Reference the outer query by its own entity path: { eq: ["<inner>.<fk>", "<outer>.id"] }.')
51
+ }).strict()
52
+ );
53
+ var FilterSchema = zod.z.lazy(
54
+ () => zod.z.union([
55
+ zod.z.object({ exists: ExistsSchema }).strict().describe("EXISTS: true when the subquery matches at least one row. Wrap in `not` for NOT EXISTS."),
56
+ zod.z.object({ eq: comparisonPair }).strict().describe("Equals: tests equality between two values"),
57
+ zod.z.object({ neq: comparisonPair }).strict().describe("Not equals"),
58
+ zod.z.object({ gt: comparisonPair }).strict().describe("Greater than"),
59
+ zod.z.object({ gte: comparisonPair }).strict().describe("Greater than or equal"),
60
+ zod.z.object({ lt: comparisonPair }).strict().describe("Less than"),
61
+ zod.z.object({ lte: comparisonPair }).strict().describe("Less than or equal"),
62
+ zod.z.object({ in: zod.z.tuple([fieldString, collectionTarget]) }).strict().describe("Field value is in a set"),
63
+ zod.z.object({ notIn: zod.z.tuple([fieldString, collectionTarget]) }).strict().describe("Field value is not in a set"),
64
+ zod.z.object({ like: zod.z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe("Case-sensitive LIKE pattern match (use % as wildcard)"),
65
+ zod.z.object({ ilike: zod.z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe("Case-insensitive ILIKE pattern match (use % as wildcard)"),
66
+ zod.z.object({ isNull: fieldString }).strict().describe("Field value is NULL"),
67
+ zod.z.object({ isNotNull: fieldString }).strict().describe("Field value is NOT NULL"),
68
+ zod.z.object({ and: zod.z.array(FilterSchema).min(2) }).strict().describe("Logical AND: all conditions must be true"),
69
+ zod.z.object({ or: zod.z.array(FilterSchema).min(2) }).strict().describe("Logical OR: at least one condition must be true"),
70
+ zod.z.object({ not: FilterSchema }).strict().describe("Logical NOT: negates the condition"),
71
+ zod.z.object({
72
+ semantic: zod.z.object({
73
+ field: FieldPathSchema.describe("Vector column field path (entity.field)"),
74
+ query: zod.z.union([ContextRefSchema, ScopeRefSchema]).describe("Text to embed and compare"),
75
+ minScore: zod.z.number().min(0).max(1).optional().describe("Minimum cosine similarity (0\u20131)")
76
+ }).strict()
77
+ }).strict().describe("Semantic vector similarity search"),
78
+ zod.z.object({
79
+ fuzzy: zod.z.object({
80
+ field: FieldPathSchema.describe("String field path"),
81
+ query: zod.z.union([ContextRefSchema, ScopeRefSchema]).describe("Text to fuzzy-match"),
82
+ maxDistance: zod.z.number().int().nonnegative().optional().describe("Maximum Levenshtein edit distance")
83
+ }).strict()
84
+ }).strict().describe("Fuzzy string match"),
85
+ zod.z.object({
86
+ optional: zod.z.object({
87
+ key: zod.z.union([zod.z.string().min(1), zod.z.array(zod.z.string().min(1)).min(1)]).describe("The context key this condition depends on, or EVERY key it depends on. A condition referencing two keys must name both \u2014 gating on one leaves the other conditionally required, which surfaces as an empty result rather than as a condition that did not apply."),
88
+ // BARE, never `.describe()`d. That call CLONES the schema, and zod
89
+ // detects a recursive reference by instance identity — a clone is a
90
+ // different instance, so `to-json-schema` stops seeing the cycle and
91
+ // expands the filter union into itself until the stack goes. Every
92
+ // other recursive slot here (`not`, `and`, `or`) uses it bare for the
93
+ // same reason; the description belongs on the wrapper below.
94
+ then: FilterSchema
95
+ }).strict()
96
+ }).strict().describe(
97
+ 'A condition the caller turns on by supplying context keys. When any named key is absent the condition is REMOVED from the query before it compiles \u2014 it does not match everything, it is not there. Absent means missing, undefined or null; "" is a value and keeps the condition. Direction follows position: under `and` supplying the key NARROWS, under `or` it WIDENS. Either way an absent key reads exactly as if the condition had never been written, and scope is injected afterwards regardless. Reads only: a mutation may not contain one, and neither may the inside of an `exists` (its correlation must be unconditional).'
98
+ )
99
+ ])
100
+ );
101
+ var CaseWhenSchema = zod.z.object({
102
+ condition: FilterSchema,
103
+ then: FieldOrValueSchema.describe("Value when condition is true")
104
+ }).strict();
105
+ var ComputeExpressionSchema = zod.z.union([
106
+ zod.z.object({ add: zod.z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe("Addition: a + b"),
107
+ zod.z.object({ subtract: zod.z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe("Subtraction: a - b"),
108
+ zod.z.object({ multiply: zod.z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe("Multiplication: a * b"),
109
+ zod.z.object({ divide: zod.z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe("Division: a / b"),
110
+ zod.z.object({ concat: zod.z.array(FieldOrValueSchema).min(2) }).strict().describe("String concatenation"),
111
+ zod.z.object({ coalesce: zod.z.array(FieldOrValueSchema).min(2) }).strict().describe("Returns first non-null value"),
112
+ zod.z.object({
113
+ case: zod.z.object({
114
+ when: zod.z.array(CaseWhenSchema).min(1).describe("Condition/result pairs evaluated in order"),
115
+ else: FieldOrValueSchema.describe("Default value when no condition matches")
116
+ }).strict()
117
+ }).strict().describe("CASE WHEN conditional expression")
118
+ ]).describe("Computed expression: arithmetic, string, or conditional");
119
+ var fieldPath = FieldPathSchema.describe("Field path in entity.field format");
120
+ var fieldOrExpr = zod.z.union([fieldPath, ComputeExpressionSchema]).describe("A field path or a compute expression");
121
+ var AggregateExpressionSchema = zod.z.union([
122
+ zod.z.object({ count: zod.z.union([FieldPathSchema, zod.z.literal("*")]).describe('Field path or "*" for COUNT(*)') }).strict().describe("COUNT"),
123
+ zod.z.object({ countDistinct: FieldPathSchema.describe("Field path whose distinct non-null values are counted") }).strict().describe("COUNT(DISTINCT field)"),
124
+ zod.z.object({ sum: fieldOrExpr }).strict().describe("SUM"),
125
+ zod.z.object({ avg: fieldOrExpr }).strict().describe("AVG"),
126
+ zod.z.object({ min: fieldOrExpr }).strict().describe("MIN"),
127
+ zod.z.object({ max: fieldOrExpr }).strict().describe("MAX")
128
+ ]).describe("Aggregate function applied to a field or expression");
129
+
130
+ // src/schemas/query.schema.ts
131
+ var SortEntrySchema = zod.z.object({
132
+ field: zod.z.union([FieldPathSchema, IdentifierSchema]).describe("Field path (entity.field), computed field name, or aggregate alias"),
133
+ dir: zod.z.enum(["asc", "desc"]).default("asc").describe("Sort direction")
134
+ }).strict().describe("Sort specification");
135
+ var SubquerySourceSchema = zod.z.object({
136
+ as: IdentifierSchema.describe("Alias for subquery results \u2014 use as prefix in field paths"),
137
+ query: zod.z.lazy(() => QuerySchema).describe("A nested query")
138
+ }).strict().describe("Subquery data source: a nested query read as a table under `as`, its columns referenced as `<as>.<field>` anywhere in the outer query. Joined by foreign key like an entity when one links them; otherwise every outer row is paired with every subquery row (a cross join), so a one-row subquery puts its values beside each outer row.");
139
+ var SourceSchema = zod.z.union([
140
+ zod.z.string().describe("Entity name from the database schema"),
141
+ SubquerySourceSchema
142
+ ]).describe("Data source: entity name or subquery");
143
+ var FieldRefSchema = zod.z.union([
144
+ FieldPathSchema.describe("A column in entity.field format"),
145
+ zod.z.object({
146
+ field: FieldPathSchema.describe("A column in entity.field format"),
147
+ as: IdentifierSchema.describe("Output key for this column")
148
+ }).strict().describe("An aliased column: output under `as` instead of the column name")
149
+ ]).describe("A selected field \u2014 a bare `entity.field`, or `{ field, as }` to alias the output key");
150
+ var QuerySchema = zod.z.lazy(
151
+ () => zod.z.object({
152
+ from: zod.z.array(SourceSchema).min(1).describe("Data sources \u2014 entity names or subqueries. Every entity used anywhere in the query must be listed here. Listed entities are JOINED FOR YOU along their foreign keys \u2014 a nullable key as a LEFT JOIN, so a row whose key is empty is kept, with the joined columns null. Never restate a join as a filter comparing the two keys: that throws those rows away."),
153
+ fields: zod.z.array(FieldRefSchema).optional().describe("Raw columns to select \u2014 each `entity.field`, or `{ field, as }` to alias the output key (no SELECT *). Optional: omit it for an aggregate-only query (e.g. a bare COUNT). Do not list compute or aggregate aliases here \u2014 those are added automatically."),
154
+ filter: FilterSchema.optional().describe("Filter conditions"),
155
+ compute: zod.z.record(IdentifierSchema, ComputeExpressionSchema).optional().describe("Computed fields \u2014 key is output alias, value is the expression"),
156
+ aggregate: zod.z.record(IdentifierSchema, AggregateExpressionSchema).optional().describe("Aggregate functions \u2014 key is output alias, value is the function"),
157
+ groupBy: zod.z.array(FieldPathSchema).optional().describe("Fields to group by for aggregation"),
158
+ sort: zod.z.array(SortEntrySchema).optional().describe("Sort order"),
159
+ limit: zod.z.number().int().positive().optional().describe("Maximum rows to return"),
160
+ distinct: zod.z.boolean().optional().describe("Eliminate duplicate rows")
161
+ }).strict().refine(
162
+ (q) => (q.fields?.length ?? 0) > 0 || Object.keys(q.aggregate ?? {}).length > 0,
163
+ { message: "A query must select at least one of `fields` or `aggregate`." }
164
+ )
165
+ );
166
+
167
+ // src/agent/tools.ts
168
+ var GetSchemaInputSchema = zod.z.object({
169
+ entities: zod.z.array(zod.z.string()).optional().describe("Filter to specific entity names")
170
+ });
171
+ var GetSampleRowsInputSchema = zod.z.object({
172
+ entity: zod.z.string().describe("Entity name to sample rows from"),
173
+ limit: zod.z.number().int().positive().max(50).optional().describe("Max rows to return (default: 5)")
174
+ });
175
+ var GetDistinctValuesInputSchema = zod.z.object({
176
+ entity: zod.z.string().describe("Entity name"),
177
+ field: zod.z.string().describe("Field name within the entity"),
178
+ limit: zod.z.number().int().positive().max(200).optional().describe("Max distinct values to return (default: 20)")
179
+ });
180
+ var DescribeFieldInputSchema = zod.z.object({
181
+ entity: zod.z.string().describe("Entity name"),
182
+ field: zod.z.string().describe("Field name within the entity")
183
+ });
184
+ var inSpec = (what) => `${what} \u2014 written as the DSL spec (OUTPUT SCHEMA) says.`;
185
+ var TestQueryInputSchema = zod.z.object({
186
+ from: zod.z.array(zod.z.unknown()).describe(inSpec("The data sources: entity names (or subqueries); every entity the query uses is listed here")),
187
+ fields: zod.z.array(zod.z.unknown()).optional().describe(inSpec("Raw columns to select, `entity.field` or `{ field, as }`; omit for an aggregate-only query")),
188
+ filter: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe(inSpec("Filter conditions")),
189
+ compute: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe(inSpec("Computed fields: output alias \u2192 expression")),
190
+ aggregate: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe(inSpec("Aggregates (count, sum, avg, \u2026): output alias \u2192 function")),
191
+ groupBy: zod.z.array(zod.z.unknown()).optional().describe(inSpec("Fields to group by, for aggregates")),
192
+ sort: zod.z.array(zod.z.unknown()).optional().describe(inSpec("Sort order")),
193
+ limit: zod.z.number().optional().describe("Maximum rows to return."),
194
+ distinct: zod.z.boolean().optional().describe("Eliminate duplicate rows.")
195
+ }).catchall(zod.z.unknown()).describe("Your draft DSL query \u2014 the query object itself, NOT wrapped in any field.");
196
+ var CannotSatisfyInputSchema = zod.z.object({
197
+ reason: zod.z.string().describe("Why the request cannot be satisfied")
198
+ });
199
+ var NEXT_AFTER_PASS = "This query runs. If its rows answer the request, you are done: do not test it again \u2014 finish now with the envelope, its `data` being exactly this query. If not, change the query and test again.";
200
+ var locate = (deps, entityName) => {
201
+ const schema = deps.getSchema();
202
+ if (schema === void 0) return { error: "Schema not available" };
203
+ const entity = schema.entities.find((e) => e.name === entityName);
204
+ return entity === void 0 ? { error: `Entity "${entityName}" not found` } : { entity };
205
+ };
206
+ var locateField = (deps, entityName, fieldName) => {
207
+ const located = locate(deps, entityName);
208
+ if ("error" in located) return located;
209
+ const field = located.entity.fields.find((f) => f.name === fieldName);
210
+ return field === void 0 ? { error: `Field "${fieldName}" not found on entity "${entityName}"` } : { entity: located.entity, field };
211
+ };
212
+ var messageOf = (err) => err instanceof Error ? err.message : String(err);
213
+ var attempt = async (run) => {
214
+ try {
215
+ return await run();
216
+ } catch (err) {
217
+ return { error: messageOf(err) };
218
+ }
219
+ };
220
+ var firstRow = (rows) => rows[0] ?? {};
221
+ var createQueryTools = (deps) => {
222
+ const getSchemaTool = cortex.defineTool({
223
+ id: "getSchema",
224
+ name: "getSchema",
225
+ description: "Returns the introspected database schema, optionally filtered to specific entities.",
226
+ input: GetSchemaInputSchema,
227
+ execute: (input) => {
228
+ const schema = deps.getSchema();
229
+ if (!schema) return { error: "Schema not available" };
230
+ if (input.entities && input.entities.length > 0) {
231
+ const filtered = {
232
+ ...schema,
233
+ entities: schema.entities.filter((e) => input.entities?.includes(e.name))
234
+ };
235
+ return JSON.stringify(filtered);
236
+ }
237
+ return JSON.stringify(schema);
238
+ }
239
+ });
240
+ const getSampleRowsTool = cortex.defineTool({
241
+ id: "getSampleRows",
242
+ name: "getSampleRows",
243
+ description: "Returns sample rows from an entity table.",
244
+ input: GetSampleRowsInputSchema,
245
+ execute: async (input) => {
246
+ const located = locate(deps, input.entity);
247
+ if ("error" in located) return located;
248
+ const { entity } = located;
249
+ const fields = entity.fields.filter((f) => f.normalizedType !== "vector").map((f) => `${entity.name}.${f.name}`);
250
+ const query = { from: [entity.name], fields, limit: input.limit ?? 5 };
251
+ return attempt(async () => (await deps.read(query)).rows);
252
+ }
253
+ });
254
+ const getDistinctValuesTool = cortex.defineTool({
255
+ id: "getDistinctValues",
256
+ name: "getDistinctValues",
257
+ description: "Returns distinct values for a specific field in an entity.",
258
+ input: GetDistinctValuesInputSchema,
259
+ execute: async (input) => {
260
+ const located = locateField(deps, input.entity, input.field);
261
+ if ("error" in located) return located;
262
+ const { entity, field } = located;
263
+ const query = { from: [entity.name], fields: [`${entity.name}.${field.name}`], distinct: true, limit: input.limit ?? 20 };
264
+ return attempt(async () => (await deps.read(query)).rows.map((row) => row[field.name]));
265
+ }
266
+ });
267
+ const describeFieldTool = cortex.defineTool({
268
+ id: "describeField",
269
+ name: "describeField",
270
+ description: "Returns statistics about a field: type, nullable, cardinality, null count, min/max for numeric/date types.",
271
+ input: DescribeFieldInputSchema,
272
+ execute: async (input) => {
273
+ const located = locateField(deps, input.entity, input.field);
274
+ if ("error" in located) return located;
275
+ const { entity, field } = located;
276
+ const path = `${entity.name}.${field.name}`;
277
+ const isNumericOrDate = ["number", "date", "timestamp"].includes(field.normalizedType);
278
+ return attempt(async () => {
279
+ const [counted, nulls, range] = await Promise.all([
280
+ deps.read({ from: [entity.name], aggregate: { cardinality: { countDistinct: path } } }),
281
+ deps.read({ from: [entity.name], aggregate: { null_count: { count: "*" } }, filter: { isNull: path } }),
282
+ isNumericOrDate ? deps.read({ from: [entity.name], aggregate: { min_val: { min: path }, max_val: { max: path } } }) : Promise.resolve(void 0)
283
+ ]);
284
+ const stats = {
285
+ type: field.normalizedType,
286
+ nullable: field.nullable,
287
+ cardinality: Number(firstRow(counted.rows)["cardinality"] ?? 0),
288
+ nullCount: Number(firstRow(nulls.rows)["null_count"] ?? 0)
289
+ };
290
+ if (range !== void 0) {
291
+ stats.min = firstRow(range.rows)["min_val"];
292
+ stats.max = firstRow(range.rows)["max_val"];
293
+ }
294
+ return stats;
295
+ });
296
+ }
297
+ });
298
+ const testQueryTool = cortex.defineTool({
299
+ id: "testQuery",
300
+ name: "testQuery",
301
+ description: "Validates a DSL query, compiles it to SQL, and executes it with synthetic parameters (LIMIT 5). Pass the query object DIRECTLY as the arguments. Returns rows, SQL, warnings, and errors.",
302
+ input: TestQueryInputSchema,
303
+ execute: async (input) => {
304
+ if (strata.exceedsDepth(input)) return { rows: [], sql: "", warnings: [], errors: [strata.depthRefusal()] };
305
+ const parseResult = QuerySchema.safeParse(input);
306
+ if (!parseResult.success) {
307
+ const validationErrors = parseResult.error.issues.map(
308
+ (issue) => `${issue.path.join(".")}: ${issue.message}`
309
+ );
310
+ return { rows: [], sql: "", warnings: [], errors: validationErrors };
311
+ }
312
+ try {
313
+ const { rows, sql, warnings } = await deps.read({ ...parseResult.data, limit: 5 });
314
+ return { rows, sql, warnings, errors: [], next: NEXT_AFTER_PASS };
315
+ } catch (err) {
316
+ return { rows: [], sql: "", warnings: [], errors: [messageOf(err)] };
317
+ }
318
+ }
319
+ });
320
+ const cannotSatisfyTool = cortex.defineTool({
321
+ id: "cannotSatisfy",
322
+ name: "cannotSatisfy",
323
+ description: "Signal that the natural language request cannot be satisfied by the available schema. This ends the run.",
324
+ input: CannotSatisfyInputSchema,
325
+ execute: (input) => ({ acknowledged: true, reason: input.reason })
326
+ });
327
+ return [
328
+ getSchemaTool,
329
+ getSampleRowsTool,
330
+ getDistinctValuesTool,
331
+ describeFieldTool,
332
+ testQueryTool,
333
+ cannotSatisfyTool
334
+ ];
335
+ };
336
+ var describeCaller = (bindings) => bindings.length === 0 ? 'The caller: no column in this schema is bound to anything that identifies the caller, so a request about "me", "my" or "mine" cannot be answered.' : [
337
+ "The caller \u2014 the person or service this query is for \u2014 is identified by server-side scope values bound to these columns:",
338
+ ...bindings.map((b) => `- ${b.entity}.${b.field} is the caller's { "$scope": "${b.key}" }`),
339
+ `Such a column holds that value on the caller's own rows. To mean the caller or what is theirs ("me", "my", "mine", "our"), filter the column with { "$scope": "<key>" } \u2014 the server binds the caller's own value; you never see or write it.`
340
+ ].join("\n");
341
+ var INSTRUCTIONS = `You are Vex's query agent. You turn a caller's request \u2014 a natural-language \`intent\` and an example \`shape\` of the data they want back \u2014 into ONE query in Vex's DSL.
342
+
343
+ Context gives you two things:
344
+ - the database schema: the entities, fields, relations, and indexes that actually exist;
345
+ - the DSL JSON Schema: the exact structure your query must take. Its field
346
+ descriptions ARE the rules \u2014 read them and follow them. They are the single
347
+ source of truth for how every part of a query is written.
348
+
349
+ Your job is to RETRIEVE the data the request needs: choose the entities, columns,
350
+ filters, computed values, and aggregates the schema supports. A separate step runs
351
+ after you and reshapes, nests, combines and formats the rows, so you never nest.
352
+ But when a key of the shape is exactly ONE column or ONE aggregate, alias it to
353
+ that key (\`{ "field": \u2026, "as": "<key>" }\`, or name the aggregate after the key):
354
+ when every row already has exactly the shape's keys, that later step is skipped.
355
+ A key that needs combining or formatting (a full name from two columns, a date
356
+ written out) you leave to it \u2014 select the underlying columns under their own names.
357
+
358
+ Work this way, every time:
359
+ 1. If you are unsure what exists or what values a field holds, inspect it with
360
+ your tools before drafting.
361
+ 2. Draft the query.
362
+ 3. Call testQuery on the draft. You may NOT finish until testQuery has succeeded.
363
+ If it returns an error, your query is wrong \u2014 read the error, fix the query,
364
+ and call testQuery again. Repeat until it passes.
365
+ 4. Finish. Your envelope's \`data\` is the EXACT query that passed
366
+ testQuery (optionally a one-line \`reasoning\`).
367
+ 5. If the request genuinely cannot be answered from the schema, call
368
+ cannotSatisfy with a short reason instead of guessing.
369
+
370
+ Worked example (illustrative \u2014 real entities and rules come from the schema):
371
+ intent: "each customer's contact line and how much they've spent, biggest first"
372
+ shape: [{ "contact": "", "spent": 0 }]
373
+ data: {"from":["customer"],"fields":["customer.name","customer.email",{"field":"customer.total_spent","as":"spent"}],"sort":[{"field":"customer.total_spent","dir":"desc"}]}
374
+ (\`spent\` is one column, so it is aliased; \`contact\` combines two, so they are selected as they are.)`;
375
+ var vexQueryDslAgent = cortex.defineAgent({
376
+ id: "vex.query",
377
+ description: "Generates DSL queries from natural language intent and target shape.",
378
+ instructions: INSTRUCTIONS,
379
+ context: [
380
+ ({ deps }) => `Database schema:
381
+ ${deps.schemaJson}`,
382
+ ({ deps }) => deps.caller ?? describeCaller([]),
383
+ // Named OUTPUT SCHEMA because that is what the finish protocol refers to:
384
+ // the query this agent returns is the envelope's `data`.
385
+ ({ deps }) => `OUTPUT SCHEMA \u2014 the DSL specification (JSON Schema), the single source of truth for your query:
386
+ ${deps.dslSpecJson}`
387
+ ],
388
+ // The DSL spec above IS the schema documentation; don't inject it twice.
389
+ output: { schema: QuerySchema, doc: "off" },
390
+ // Three identical testQuery calls with the same error in a row is a model
391
+ // not reading the error; a fourth would cost a full prompt and change nothing.
392
+ stopWhen: [cortex.stepCount(20), cortex.outputRetries(3), cortex.repeatedCalls(2)]
393
+ });
394
+
395
+ // src/agent/index.ts
396
+ var reasonFrom = (args) => {
397
+ if (typeof args !== "object" || args === null) return void 0;
398
+ const reason = args["reason"];
399
+ return typeof reason === "string" ? reason : void 0;
400
+ };
401
+ var createQueryDsl = (config) => {
402
+ return async (request, schema, caller) => {
403
+ const tools = createQueryTools({ getSchema: () => schema, read: caller.read });
404
+ const agentInput = {
405
+ intent: request.intent,
406
+ shape: request.shape,
407
+ contextKeys: Object.keys(request.context)
408
+ };
409
+ let unsatisfiableReason;
410
+ let run;
411
+ run = vexQueryDslAgent.run(agentInput, {
412
+ llm: config.llm,
413
+ deps: {
414
+ schemaJson: JSON.stringify(schema),
415
+ dslSpecJson: JSON.stringify(config.queryJsonSchema),
416
+ caller: describeCaller(caller.bindings)
417
+ },
418
+ tools,
419
+ onEvent: (event) => {
420
+ if (event.type === "tool-end" && event.observation.kind === "result" && event.observation.toolId === "cannotSatisfy") {
421
+ unsatisfiableReason = reasonFrom(event.observation.args) ?? "request cannot be satisfied";
422
+ run?.abort();
423
+ }
424
+ }
425
+ });
426
+ const result = await run.result;
427
+ if (!result.ok) {
428
+ if (unsatisfiableReason !== void 0) {
429
+ throw new VexError("unsatisfiable", unsatisfiableReason);
430
+ }
431
+ throw new VexError("agent_failed", `${result.error.code}: ${result.error.message}`);
432
+ }
433
+ return result.output.data;
434
+ };
435
+ };
436
+ var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
437
+ var rowsFitShape = (rows, shape) => {
438
+ const example = Array.isArray(shape) ? shape[0] : shape;
439
+ const first = rows[0];
440
+ if (!isPlainObject(example) || first === void 0) return false;
441
+ const keys = Object.keys(example);
442
+ if (keys.length !== Object.keys(first).length) return false;
443
+ return keys.every((key) => {
444
+ const sample = example[key];
445
+ if (typeof sample === "object" && sample !== null) return false;
446
+ if (!(key in first)) return false;
447
+ const value = first[key];
448
+ return value === null || typeof value === typeof sample;
449
+ });
450
+ };
451
+ var IDENTITY = { $ref: "$.result" };
452
+ var createShapeMapper = (llm) => {
453
+ return async (rows, shape) => {
454
+ const single = !Array.isArray(shape);
455
+ const envelope = { result: single ? rows[0] ?? null : rows };
456
+ if (rowsFitShape(rows, shape)) {
457
+ const ir2 = await prism.compile(IDENTITY);
458
+ return { ir: ir2, transformed: prism.execute(ir2, envelope) };
459
+ }
460
+ const result = await agent.mappingAgent.run(
461
+ { sampleInput: envelope, targetShape: shape },
462
+ { llm }
463
+ ).result;
464
+ if (!result.ok) throw new VexError("agent_failed", `${result.error.code}: ${result.error.message}`);
465
+ const ir = await prism.compile(result.output.data);
466
+ const transformed = prism.execute(ir, envelope);
467
+ return { ir, transformed };
468
+ };
469
+ };
470
+
471
+ exports.createQueryDsl = createQueryDsl;
472
+ exports.createQueryTools = createQueryTools;
473
+ exports.createShapeMapper = createShapeMapper;
474
+ exports.describeCaller = describeCaller;
475
+ exports.rowsFitShape = rowsFitShape;
476
+ exports.vexQueryDslAgent = vexQueryDslAgent;
477
+ //# sourceMappingURL=index.cjs.map
478
+ //# sourceMappingURL=index.cjs.map