@niscorp/vex 0.2.3 → 0.3.1

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 (40) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/DESIGN.md +26 -11
  3. package/DOCS.md +39 -9
  4. package/dist/adapters/express/index.cjs +6 -24
  5. package/dist/adapters/express/index.cjs.map +1 -1
  6. package/dist/adapters/express/index.d.cts +2 -2
  7. package/dist/adapters/express/index.d.ts +2 -2
  8. package/dist/adapters/express/index.js +2 -2
  9. package/dist/adapters/express/index.js.map +1 -1
  10. package/dist/adapters/hono/index.cjs +6 -24
  11. package/dist/adapters/hono/index.cjs.map +1 -1
  12. package/dist/adapters/hono/index.d.cts +2 -2
  13. package/dist/adapters/hono/index.d.ts +2 -2
  14. package/dist/adapters/hono/index.js +2 -2
  15. package/dist/adapters/hono/index.js.map +1 -1
  16. package/dist/adapters/pglite/index.cjs.map +1 -1
  17. package/dist/adapters/pglite/index.js.map +1 -1
  18. package/dist/agent/index.cjs +5 -11
  19. package/dist/agent/index.cjs.map +1 -1
  20. package/dist/agent/index.d.cts +1 -1
  21. package/dist/agent/index.d.ts +1 -1
  22. package/dist/agent/index.js +3 -6
  23. package/dist/agent/index.js.map +1 -1
  24. package/dist/{chunk-IQM4SQE2.js → chunk-3HORTMZ7.js} +6 -21
  25. package/dist/chunk-3HORTMZ7.js.map +1 -0
  26. package/dist/{chunk-H4BHW76Q.js → chunk-J7JYKCUA.js} +5 -8
  27. package/dist/chunk-J7JYKCUA.js.map +1 -0
  28. package/dist/{handler-CMrjTXNx.d.cts → handler-B4NAi4k_.d.cts} +1 -1
  29. package/dist/{handler-BGCL6_Si.d.ts → handler-BRVhWuNk.d.ts} +1 -1
  30. package/dist/index.cjs +23 -79
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +14 -62
  33. package/dist/index.d.ts +14 -62
  34. package/dist/index.js +21 -59
  35. package/dist/index.js.map +1 -1
  36. package/dist/{types-Bi-Lg86b.d.cts → types-DUJp5B3o.d.cts} +9 -124
  37. package/dist/{types-Bi-Lg86b.d.ts → types-DUJp5B3o.d.ts} +9 -124
  38. package/package.json +7 -7
  39. package/dist/chunk-H4BHW76Q.js.map +0 -1
  40. package/dist/chunk-IQM4SQE2.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/agent/tools.ts","../../src/agent/query.agent.ts","../../src/agent/index.ts"],"names":["ir"],"mappings":";;;;;;;AA4BA,IAAM,oBAAA,GAAuB,EAAE,MAAA,CAAO;AAAA,EACpC,QAAA,EAAU,CAAA,CAAE,KAAA,CAAM,CAAA,CAAE,MAAA,EAAQ,CAAA,CAAE,QAAA,EAAS,CAAE,QAAA,CAAS,iCAAiC;AACrF,CAAC,CAAA;AAGD,IAAM,wBAAA,GAA2B,EAAE,MAAA,CAAO;AAAA,EACxC,MAAA,EAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,iCAAiC,CAAA;AAAA,EAC7D,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,EAAS,CAAE,GAAA,CAAI,EAAE,CAAA,CAAE,QAAA,EAAS,CAAE,SAAS,iCAAiC;AAClG,CAAC,CAAA;AAGD,IAAM,4BAAA,GAA+B,EAAE,MAAA,CAAO;AAAA,EAC5C,MAAA,EAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,aAAa,CAAA;AAAA,EACzC,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,8BAA8B,CAAA;AAAA,EACzD,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,EAAS,CAAE,GAAA,CAAI,GAAG,CAAA,CAAE,QAAA,EAAS,CAAE,SAAS,6CAA6C;AAC/G,CAAC,CAAA;AAGD,IAAM,wBAAA,GAA2B,EAAE,MAAA,CAAO;AAAA,EACxC,MAAA,EAAQ,CAAA,CAAE,MAAA,EAA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AAa,IAAA,EAAM,KAAK,CAAA,EAAG;AAC7B,MAAA,MAAMA,GAAAA,GAAK,MAAM,OAAA,CAAQ,QAAQ,CAAA;AACjC,MAAA,OAAO,EAAE,EAAA,EAAAA,GAAAA,EAAI,aAAa,OAAA,CAAQA,GAAAA,EAAI,QAAQ,CAAA,EAAE;AAAA,IAClD;AAEA,IAAA,MAAM,MAAA,GAAS,MAAM,YAAA,CAAa,GAAA;AAAA,MAChC,EAAE,WAAA,EAAa,QAAA,EAAU,WAAA,EAAa,KAAA,EAAM;AAAA,MAC5C,EAAE,GAAA;AAAI,KACR,CAAE,MAAA;AAEF,IAAA,IAAI,CAAC,MAAA,CAAO,EAAA,EAAI,MAAM,IAAI,QAAA,CAAS,cAAA,EAAgB,CAAA,EAAG,MAAA,CAAO,MAAM,IAAI,CAAA,EAAA,EAAK,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAElG,IAAA,MAAM,EAAA,GAAK,MAAM,OAAA,CAAQ,MAAA,CAAO,OAAO,IAAI,CAAA;AAC3C,IAAA,MAAM,WAAA,GAAc,OAAA,CAAQ,EAAA,EAAI,QAAQ,CAAA;AACxC,IAAA,OAAO,EAAE,IAAI,WAAA,EAAY;AAAA,EAC3B,CAAA;AACF","file":"index.js","sourcesContent":["import { z } from 'zod';\nimport { depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport { defineTool } from '@niscorp/cortex';\nimport { QuerySchema } from '../schemas/query.schema.js';\nimport type { Query } from '../schemas/query.schema.js';\nimport type { Row } from '../adapters/adapter.types.js';\nimport type { DatabaseSchema, EntitySchema, FieldSchema } from '../schemas/database.schema.js';\nimport type { GenerationCaller } from '../types.js';\n\n// ═══════════════════════════════════════════════════════════════\n// Dependencies\n//\n// The tools hold no adapter and no policy. Everything they learn about the\n// data they learn through `read` — the engine's own pipeline, run as the\n// caller the generation is for — so a sample row, a distinct value and a\n// null count are all things that person could have read, and nothing else.\n// There is no SQL in this file.\n// ═══════════════════════════════════════════════════════════════\n\nexport type QueryToolDeps = {\n getSchema: () => DatabaseSchema | undefined;\n read: GenerationCaller['read'];\n};\n\n// ═══════════════════════════════════════════════════════════════\n// Tool input schemas + types\n// ═══════════════════════════════════════════════════════════════\n\nconst GetSchemaInputSchema = z.object({\n entities: z.array(z.string()).optional().describe('Filter to specific entity names'),\n});\nexport type GetSchemaInput = z.infer<typeof GetSchemaInputSchema>;\n\nconst GetSampleRowsInputSchema = z.object({\n entity: z.string().describe('Entity name to sample rows from'),\n limit: z.number().int().positive().max(50).optional().describe('Max rows to return (default: 5)'),\n});\nexport type GetSampleRowsInput = z.infer<typeof GetSampleRowsInputSchema>;\n\nconst GetDistinctValuesInputSchema = z.object({\n entity: z.string().describe('Entity name'),\n field: z.string().describe('Field name within the entity'),\n limit: z.number().int().positive().max(200).optional().describe('Max distinct values to return (default: 20)'),\n});\nexport type GetDistinctValuesInput = z.infer<typeof GetDistinctValuesInputSchema>;\n\nconst DescribeFieldInputSchema = z.object({\n entity: z.string().describe('Entity name'),\n field: z.string().describe('Field name within the entity'),\n});\nexport type DescribeFieldInput = z.infer<typeof DescribeFieldInputSchema>;\n\n// The draft query ITSELF at the root — no `dsl` wrapper. Models\n// naturally pass the query object directly, and a wrapper mismatch is\n// fatal on providers (Groq) that validate tool args SERVER-SIDE.\n//\n// SHALLOW: every top-level key of the query, and nothing below it. A model\n// takes a tool's parameter schema as the whole contract for its arguments —\n// qwen 3.8 27b does, and does not look the argument's shape up in the prompt\n// (measured 2026-09-27: given an empty object it sent `{}` until its step\n// limit; given `from` and `fields` it wrote only `from` and `fields`, never an\n// aggregate; given these nine keys it wrote correct aggregate + groupBy\n// queries at once). So the schema names every key a query can have. What\n// goes INSIDE each is the DSL spec's, in the prompt: the full recursive\n// schema cannot be the parameters — Groq refuses it (400, measured) — and the\n// real validation is this tool's QuerySchema safeParse, whose errors the model\n// reads and fixes. `test/agent/tools.test.ts` holds these keys to QuerySchema's.\nconst inSpec = (what: string): string => `${what} — written as the DSL spec (OUTPUT SCHEMA) says.`;\nconst TestQueryInputSchema = z\n .object({\n from: z.array(z.unknown()).describe(inSpec('The data sources: entity names (or subqueries); every entity the query uses is listed here')),\n fields: z.array(z.unknown()).optional().describe(inSpec('Raw columns to select, `entity.field` or `{ field, as }`; omit for an aggregate-only query')),\n filter: z.record(z.string(), z.unknown()).optional().describe(inSpec('Filter conditions')),\n compute: z.record(z.string(), z.unknown()).optional().describe(inSpec('Computed fields: output alias → expression')),\n aggregate: z.record(z.string(), z.unknown()).optional().describe(inSpec('Aggregates (count, sum, avg, …): output alias → function')),\n groupBy: z.array(z.unknown()).optional().describe(inSpec('Fields to group by, for aggregates')),\n sort: z.array(z.unknown()).optional().describe(inSpec('Sort order')),\n limit: z.number().optional().describe('Maximum rows to return.'),\n distinct: z.boolean().optional().describe('Eliminate duplicate rows.'),\n })\n .catchall(z.unknown())\n .describe('Your draft DSL query — the query object itself, NOT wrapped in any field.');\nexport type TestQueryInput = z.infer<typeof TestQueryInputSchema>;\n\nconst CannotSatisfyInputSchema = z.object({\n reason: z.string().describe('Why the request cannot be satisfied'),\n});\nexport type CannotSatisfyInput = z.infer<typeof CannotSatisfyInputSchema>;\n\n// ═══════════════════════════════════════════════════════════════\n// Result types\n// ═══════════════════════════════════════════════════════════════\n\ntype FieldStats = {\n type: string;\n nullable: boolean;\n cardinality: number;\n nullCount: number;\n min?: unknown;\n max?: unknown;\n};\n\ntype TestQueryResult = {\n rows: Row[];\n sql: string;\n warnings: string[];\n errors: string[];\n // On success only: what the model does now. A passing test is the moment\n // the run can end, and a model that is not told so tests the same query\n // again (measured: qwen 3.8 27b, until its stop).\n next?: string;\n};\n\nconst NEXT_AFTER_PASS =\n 'This query runs. If its rows answer the request, you are done: do not test it again — finish now with the envelope, its `data` being exactly this query. If not, change the query and test again.';\n\n// ═══════════════════════════════════════════════════════════════\n// Helpers\n// ═══════════════════════════════════════════════════════════════\n\ntype Located = { entity: EntitySchema } | { error: string };\ntype LocatedField = { entity: EntitySchema; field: FieldSchema } | { error: string };\n\n// The schema the tools are handed is already the caller's — tables their\n// policy cannot read are not in it — so \"not found\" and \"not yours\" are the\n// same answer, which is the point.\nconst locate = (deps: QueryToolDeps, entityName: string): Located => {\n const schema = deps.getSchema();\n if (schema === undefined) return { error: 'Schema not available' };\n const entity = schema.entities.find((e) => e.name === entityName);\n return entity === undefined ? { error: `Entity \"${entityName}\" not found` } : { entity };\n};\n\nconst locateField = (deps: QueryToolDeps, entityName: string, fieldName: string): LocatedField => {\n const located = locate(deps, entityName);\n if ('error' in located) return located;\n const field = located.entity.fields.find((f) => f.name === fieldName);\n return field === undefined\n ? { error: `Field \"${fieldName}\" not found on entity \"${entityName}\"` }\n : { entity: located.entity, field };\n};\n\nconst messageOf = (err: unknown): string => (err instanceof Error ? err.message : String(err));\n\n// A read that fails (a refused table, a column the grammar cannot name) is an\n// answer the model can use, not a crash of the run.\nconst attempt = async <T>(run: () => Promise<T>): Promise<T | { error: string }> => {\n try {\n return await run();\n } catch (err) {\n return { error: messageOf(err) };\n }\n};\n\nconst firstRow = (rows: Row[]): Row => rows[0] ?? {};\n\n// ═══════════════════════════════════════════════════════════════\n// Factory\n// ═══════════════════════════════════════════════════════════════\n\nexport const createQueryTools = (deps: QueryToolDeps): ReturnType<typeof defineTool>[] => {\n const getSchemaTool = defineTool({\n id: 'getSchema',\n name: 'getSchema',\n description: 'Returns the introspected database schema, optionally filtered to specific entities.',\n input: GetSchemaInputSchema,\n execute: (input: GetSchemaInput) => {\n const schema = deps.getSchema();\n if (!schema) return { error: 'Schema not available' };\n\n if (input.entities && input.entities.length > 0) {\n const filtered = {\n ...schema,\n entities: schema.entities.filter(e => input.entities?.includes(e.name)),\n };\n return JSON.stringify(filtered);\n }\n\n return JSON.stringify(schema);\n },\n });\n\n const getSampleRowsTool = defineTool({\n id: 'getSampleRows',\n name: 'getSampleRows',\n description: 'Returns sample rows from an entity table.',\n input: GetSampleRowsInputSchema,\n execute: async (input: GetSampleRowsInput) => {\n const located = locate(deps, input.entity);\n if ('error' in located) return located;\n const { entity } = located;\n // Vector columns are left out: hundreds of floats per row teach the\n // model nothing and cost the context window everything.\n const fields = entity.fields.filter((f) => f.normalizedType !== 'vector').map((f) => `${entity.name}.${f.name}`);\n const query: Query = { from: [entity.name], fields, limit: input.limit ?? 5 };\n return attempt(async () => (await deps.read(query)).rows);\n },\n });\n\n const getDistinctValuesTool = defineTool({\n id: 'getDistinctValues',\n name: 'getDistinctValues',\n description: 'Returns distinct values for a specific field in an entity.',\n input: GetDistinctValuesInputSchema,\n execute: async (input: GetDistinctValuesInput) => {\n const located = locateField(deps, input.entity, input.field);\n if ('error' in located) return located;\n const { entity, field } = located;\n const query: Query = { from: [entity.name], fields: [`${entity.name}.${field.name}`], distinct: true, limit: input.limit ?? 20 };\n return attempt(async () => (await deps.read(query)).rows.map((row) => row[field.name]));\n },\n });\n\n const describeFieldTool = defineTool({\n id: 'describeField',\n name: 'describeField',\n description: 'Returns statistics about a field: type, nullable, cardinality, null count, min/max for numeric/date types.',\n input: DescribeFieldInputSchema,\n execute: async (input: DescribeFieldInput) => {\n const located = locateField(deps, input.entity, input.field);\n if ('error' in located) return located;\n const { entity, field } = located;\n const path = `${entity.name}.${field.name}`;\n const isNumericOrDate = ['number', 'date', 'timestamp'].includes(field.normalizedType);\n\n return attempt(async (): Promise<FieldStats> => {\n const [counted, nulls, range] = await Promise.all([\n deps.read({ from: [entity.name], aggregate: { cardinality: { countDistinct: path } } }),\n deps.read({ from: [entity.name], aggregate: { null_count: { count: '*' } }, filter: { isNull: path } }),\n isNumericOrDate\n ? deps.read({ from: [entity.name], aggregate: { min_val: { min: path }, max_val: { max: path } } })\n : Promise.resolve(undefined),\n ]);\n\n const stats: FieldStats = {\n type: field.normalizedType,\n nullable: field.nullable,\n cardinality: Number(firstRow(counted.rows)['cardinality'] ?? 0),\n nullCount: Number(firstRow(nulls.rows)['null_count'] ?? 0),\n };\n if (range !== undefined) {\n stats.min = firstRow(range.rows)['min_val'];\n stats.max = firstRow(range.rows)['max_val'];\n }\n return stats;\n });\n },\n });\n\n const testQueryTool = defineTool({\n id: 'testQuery',\n name: 'testQuery',\n description:\n 'Validates a DSL query, compiles it to SQL, and executes it with synthetic parameters (LIMIT 5). ' +\n 'Pass the query object DIRECTLY as the arguments. Returns rows, SQL, warnings, and errors.',\n input: TestQueryInputSchema,\n execute: async (input: TestQueryInput): Promise<TestQueryResult> => {\n if (exceedsDepth(input)) return { rows: [], sql: '', warnings: [], errors: [depthRefusal()] };\n const parseResult = QuerySchema.safeParse(input);\n if (!parseResult.success) {\n const validationErrors = parseResult.error.issues.map(\n issue => `${issue.path.join('.')}: ${issue.message}`,\n );\n return { rows: [], sql: '', warnings: [], errors: validationErrors };\n }\n\n try {\n const { rows, sql, warnings } = await deps.read({ ...parseResult.data, limit: 5 });\n return { rows, sql, warnings, errors: [], next: NEXT_AFTER_PASS };\n } catch (err: unknown) {\n return { rows: [], sql: '', warnings: [], errors: [messageOf(err)] };\n }\n },\n });\n\n // The caller (createQueryDsl) watches for this tool's observation on\n // the run's event stream and aborts the run with the reason — the\n // v2 replacement for the v1 bus-emit + abort-rule pair.\n const cannotSatisfyTool = defineTool({\n id: 'cannotSatisfy',\n name: 'cannotSatisfy',\n description: 'Signal that the natural language request cannot be satisfied by the available schema. This ends the run.',\n input: CannotSatisfyInputSchema,\n execute: (input: CannotSatisfyInput) => ({ acknowledged: true, reason: input.reason }),\n });\n\n return [\n getSchemaTool,\n getSampleRowsTool,\n getDistinctValuesTool,\n describeFieldTool,\n testQueryTool,\n cannotSatisfyTool,\n ];\n};\n","import { defineAgent } from '@niscorp/cortex';\nimport type { AgentDefinition } from '@niscorp/cortex';\nimport { stepCount, outputRetries, repeatedCalls } from '@niscorp/cortex';\nimport { QuerySchema } from '../schemas/query.schema.js';\nimport type { Query } from '../schemas/query.schema.js';\nimport type { ScopeBinding } from '../types.js';\n\n// Per-invocation deps: the introspected database schema and the DSL\n// JSON Schema arrive per call (they vary with adapter and scope), so\n// they are context-function inputs — the agent itself is defined once.\nexport type VexQueryDeps = {\n schemaJson: string;\n dslSpecJson: string;\n // Who the caller is, in the schema's terms (describeCaller). Absent — a run\n // built without it — reads as a caller nothing identifies.\n caller?: string;\n};\n\n// WHO THE CALLER IS, for the agent: the columns their scope keys are bound to\n// (GenerationCaller.bindings) — the keys and the columns, never a value. With\n// none, the agent is told plainly that nothing here identifies them, so a\n// question about \"me\" is refused for the right reason rather than guessed at.\nexport const describeCaller = (bindings: readonly ScopeBinding[]): string =>\n bindings.length === 0\n ? '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.'\n : [\n 'The caller — the person or service this query is for — is identified by server-side scope values bound to these columns:',\n ...bindings.map((b) => `- ${b.entity}.${b.field} is the caller's { \"$scope\": \"${b.key}\" }`),\n '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>\" } — the server binds the caller\\'s own value; you never see or write it.',\n ].join('\\n');\n\nconst INSTRUCTIONS = `You are Vex's query agent. You turn a caller's request — a natural-language \\`intent\\` and an example \\`shape\\` of the data they want back — into ONE query in Vex's DSL.\n\nContext gives you two things:\n- the database schema: the entities, fields, relations, and indexes that actually exist;\n- the DSL JSON Schema: the exact structure your query must take. Its field\n descriptions ARE the rules — read them and follow them. They are the single\n source of truth for how every part of a query is written.\n\nYour job is to RETRIEVE the data the request needs: choose the entities, columns,\nfilters, computed values, and aggregates the schema supports. A separate step runs\nafter you and reshapes, nests, combines and formats the rows, so you never nest.\nBut when a key of the shape is exactly ONE column or ONE aggregate, alias it to\nthat key (\\`{ \"field\": …, \"as\": \"<key>\" }\\`, or name the aggregate after the key):\nwhen every row already has exactly the shape's keys, that later step is skipped.\nA key that needs combining or formatting (a full name from two columns, a date\nwritten out) you leave to it — select the underlying columns under their own names.\n\nWork this way, every time:\n1. If you are unsure what exists or what values a field holds, inspect it with\n your tools before drafting.\n2. Draft the query.\n3. Call testQuery on the draft. You may NOT finish until testQuery has succeeded.\n If it returns an error, your query is wrong — read the error, fix the query,\n and call testQuery again. Repeat until it passes.\n4. Finish. Your envelope's \\`data\\` is the EXACT query that passed\n testQuery (optionally a one-line \\`reasoning\\`).\n5. If the request genuinely cannot be answered from the schema, call\n cannotSatisfy with a short reason instead of guessing.\n\nWorked example (illustrative — real entities and rules come from the schema):\nintent: \"each customer's contact line and how much they've spent, biggest first\"\nshape: [{ \"contact\": \"\", \"spent\": 0 }]\ndata: {\"from\":[\"customer\"],\"fields\":[\"customer.name\",\"customer.email\",{\"field\":\"customer.total_spent\",\"as\":\"spent\"}],\"sort\":[{\"field\":\"customer.total_spent\",\"dir\":\"desc\"}]}\n(\\`spent\\` is one column, so it is aliased; \\`contact\\` combines two, so they are selected as they are.)`;\n\nexport const vexQueryDslAgent: AgentDefinition<Query, VexQueryDeps> = defineAgent<Query, VexQueryDeps>({\n id: 'vex.query',\n description: 'Generates DSL queries from natural language intent and target shape.',\n instructions: INSTRUCTIONS,\n context: [\n ({ deps }) => `Database schema:\\n${deps.schemaJson}`,\n ({ deps }) => deps.caller ?? describeCaller([]),\n // Named OUTPUT SCHEMA because that is what the finish protocol refers to:\n // the query this agent returns is the envelope's `data`.\n ({ deps }) => `OUTPUT SCHEMA — the DSL specification (JSON Schema), the single source of truth for your query:\\n${deps.dslSpecJson}`,\n ],\n // The DSL spec above IS the schema documentation; don't inject it twice.\n output: { schema: QuerySchema, doc: 'off' },\n // Three identical testQuery calls with the same error in a row is a model\n // not reading the error; a fourth would cost a full prompt and change nothing.\n stopWhen: [stepCount(20), outputRetries(3), repeatedCalls(2)],\n});\n","import type { RunHandle } from '@niscorp/cortex';\nimport { VexError } from '../errors.js';\nimport { mappingAgent } from '@niscorp/prism/agent';\nimport { compile, execute } from '@niscorp/prism';\nimport type { JsonObject } from '@niscorp/prism';\nimport { createQueryTools } from './tools.js';\nimport { describeCaller, vexQueryDslAgent } from './query.agent.js';\nimport type { Query } from '../schemas/query.schema.js';\nimport type { GenerateDsl, MapToShape } from '../types.js';\nimport type { SignalClient } from '@niscorp/cortex';\n\n// ═══════════════════════════════════════════════════════════════\n// Re-exports\n// ═══════════════════════════════════════════════════════════════\n\nexport { vexQueryDslAgent, describeCaller } from './query.agent.js';\nexport type { VexQueryDeps } from './query.agent.js';\nexport { createQueryTools } from './tools.js';\nexport type { QueryToolDeps } from './tools.js';\n\n// ═══════════════════════════════════════════════════════════════\n// generateDsl hook factory — runs vexQueryDslAgent\n// ═══════════════════════════════════════════════════════════════\n\n// What the agent is built from. Who it runs FOR is not here: the engine hands\n// every generation its caller (a `read` capability under that caller's policy\n// and scope) and the schema that caller may see, so one hook serves every\n// principal and cannot be built with the wrong one baked in.\nexport type QueryDslConfig = {\n llm: SignalClient;\n queryJsonSchema: object;\n};\n\nconst reasonFrom = (args: unknown): string | undefined => {\n if (typeof args !== 'object' || args === null) return undefined;\n const reason = (args as Record<string, unknown>)['reason'];\n return typeof reason === 'string' ? reason : undefined;\n};\n\nexport const createQueryDsl = (config: QueryDslConfig): GenerateDsl => {\n return async (request, schema, caller) => {\n const tools = createQueryTools({ getSchema: () => schema, read: caller.read });\n\n const agentInput = {\n intent: request.intent,\n shape: request.shape,\n contextKeys: Object.keys(request.context),\n };\n\n // The agent signals \"cannot satisfy\" by calling its cannotSatisfy\n // tool. We watch the run's event stream for that observation,\n // capture the reason, and abort — distinguishing a real\n // unsatisfiable result (worth negative-caching) from a transient\n // failure.\n let unsatisfiableReason: string | undefined;\n let run: RunHandle<Query> | undefined;\n run = vexQueryDslAgent.run(agentInput, {\n llm: config.llm,\n deps: {\n schemaJson: JSON.stringify(schema),\n dslSpecJson: JSON.stringify(config.queryJsonSchema),\n caller: describeCaller(caller.bindings),\n },\n tools,\n onEvent: (event) => {\n if (\n event.type === 'tool-end' &&\n event.observation.kind === 'result' &&\n event.observation.toolId === 'cannotSatisfy'\n ) {\n unsatisfiableReason = reasonFrom(event.observation.args) ?? 'request cannot be satisfied';\n run?.abort();\n }\n },\n });\n\n const result = await run.result;\n if (!result.ok) {\n if (unsatisfiableReason !== undefined) {\n throw new VexError('unsatisfiable', unsatisfiableReason);\n }\n throw new VexError('agent_failed', `${result.error.code}: ${result.error.message}`);\n }\n return result.output.data;\n };\n};\n\n// ═══════════════════════════════════════════════════════════════\n// mapToShape hook factory — runs Prism's mappingAgent\n//\n// The mapping runs ONCE over { result }, and its output IS the result (array /\n// object / scalar). An array shape puts the rows in $.result; an object shape\n// puts the single (first) row there. The envelope here must match the\n// runtime's cache-hit path (engine/runtime.ts), which replays the cached IR against the same envelope. Keep them in lockstep.\n//\n// NOTE: for the agent to actually author a whole-set mapping (a `$map` over\n// `$.result` for arrays), its instructions must teach that — tracked as a\n// follow-up. Canned/relay paths use a hand-authored, seeded IR and are correct\n// today; this affects only live generation.\n// ═══════════════════════════════════════════════════════════════\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// ROWS THAT ARE ALREADY THE SHAPE need no mapping. True only when the shape is\n// flat (every value a scalar example) and the first row has EXACTLY the\n// shape's keys — nothing extra, nothing missing — each holding the kind of\n// value the shape shows (or null). The query agent aliases its columns to a\n// flat shape's keys for exactly this reason. Anything else — a nested shape, a\n// renamed or extra column, a count that came back as text — goes to the\n// mapping agent. No rows is not a fit: there is nothing to prove the columns\n// by, and the IR minted here is replayed later against rows that exist.\nexport const rowsFitShape = (rows: readonly Record<string, unknown>[], shape: unknown): boolean => {\n const example = Array.isArray(shape) ? shape[0] : shape;\n const first = rows[0];\n if (!isPlainObject(example) || first === undefined) return false;\n const keys = Object.keys(example);\n if (keys.length !== Object.keys(first).length) return false;\n return keys.every((key) => {\n const sample = example[key];\n if (typeof sample === 'object' && sample !== null) return false;\n if (!(key in first)) return false;\n const value = first[key];\n return value === null || typeof value === typeof sample;\n });\n};\n\n// The identity mapping over the envelope — what a fitting row set replays as.\nconst IDENTITY = { $ref: '$.result' };\n\nexport const createShapeMapper = (llm: SignalClient): MapToShape => {\n return async (rows, shape) => {\n // Array shape → map the whole set; a non-array shape → map the single\n // (first) row. The envelope here must match the runtime's (engine/runtime.ts).\n const single = !Array.isArray(shape);\n const envelope = { result: single ? (rows[0] ?? null) : rows } as unknown as JsonObject;\n\n // Already the shape: the identity, with no model call.\n if (rowsFitShape(rows, shape)) {\n const ir = await compile(IDENTITY);\n return { ir, transformed: execute(ir, envelope) };\n }\n\n const result = await mappingAgent.run(\n { sampleInput: envelope, targetShape: shape },\n { llm },\n ).result;\n\n if (!result.ok) throw new VexError('agent_failed', `${result.error.code}: ${result.error.message}`);\n\n const ir = await compile(result.output.data);\n const transformed = execute(ir, envelope);\n return { ir, transformed };\n };\n};\n"]}
1
+ {"version":3,"sources":["../../src/agent/tools.ts","../../src/agent/query.agent.ts","../../src/agent/index.ts"],"names":["ir"],"mappings":";;;;;;;AAiBA,IAAM,oBAAA,GAAuB,EAAE,MAAA,CAAO;AAAA,EACpC,QAAA,EAAU,CAAA,CAAE,KAAA,CAAM,CAAA,CAAE,MAAA,EAAQ,CAAA,CAAE,QAAA,EAAS,CAAE,QAAA,CAAS,iCAAiC;AACrF,CAAC,CAAA;AAGD,IAAM,wBAAA,GAA2B,EAAE,MAAA,CAAO;AAAA,EACxC,MAAA,EAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,iCAAiC,CAAA;AAAA,EAC7D,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,KAAI,CAAE,QAAA,EAAS,CAAE,GAAA,CAAI,EAAE,CAAA,CAAE,QAAA,EAAS,CAAE,SAAS,iCAAiC;AAClG,CAAC,CAAA;AAGD,IAAM,4BAAA,GAA+B,EAAE,MAAA,CAAO;AAAA,EAC5C,MAAA,EAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,aAAa,CAAA;AAAA,EACzC,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,8BAA8B,CAAA;AAAA,EACz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AO,MAAM,KAAA,KAAU;AAE5B,IAAA,MAAM,MAAA,GAAS,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA;AACnC,IAAA,MAAM,QAAA,GAAW,EAAE,MAAA,EAAQ,MAAA,GAAU,KAAK,CAAC,CAAA,IAAK,OAAQ,IAAA,EAAK;AAE7D,IAAA,IAAI,YAAA,CAAa,IAAA,EAAM,KAAK,CAAA,EAAG;AAC7B,MAAA,MAAMA,GAAAA,GAAK,MAAM,OAAA,CAAQ,QAAQ,CAAA;AACjC,MAAA,OAAO,EAAE,EAAA,EAAAA,GAAAA,EAAI,aAAa,OAAA,CAAQA,GAAAA,EAAI,QAAQ,CAAA,EAAE;AAAA,IAClD;AAEA,IAAA,MAAM,MAAA,GAAS,MAAM,YAAA,CAAa,GAAA;AAAA,MAChC,EAAE,WAAA,EAAa,QAAA,EAAU,WAAA,EAAa,KAAA,EAAM;AAAA,MAC5C,EAAE,GAAA;AAAI,KACR,CAAE,MAAA;AAEF,IAAA,IAAI,CAAC,MAAA,CAAO,EAAA,EAAI,MAAM,IAAI,QAAA,CAAS,cAAA,EAAgB,CAAA,EAAG,MAAA,CAAO,MAAM,IAAI,CAAA,EAAA,EAAK,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAElG,IAAA,MAAM,EAAA,GAAK,MAAM,OAAA,CAAQ,MAAA,CAAO,OAAO,IAAI,CAAA;AAC3C,IAAA,MAAM,WAAA,GAAc,OAAA,CAAQ,EAAA,EAAI,QAAQ,CAAA;AACxC,IAAA,OAAO,EAAE,IAAI,WAAA,EAAY;AAAA,EAC3B,CAAA;AACF","file":"index.js","sourcesContent":["import { z } from 'zod';\nimport { depthRefusal, exceedsDepth } from '@niscorp/strata';\nimport { defineTool } from '@niscorp/cortex';\nimport { QuerySchema } from '../schemas/query.schema.js';\nimport type { Query } from '../schemas/query.schema.js';\nimport type { Row } from '../adapters/adapter.types.js';\nimport type { DatabaseSchema, EntitySchema, FieldSchema } from '../schemas/database.schema.js';\nimport type { GenerationCaller } from '../types.js';\n\n// No adapter and no policy: the tools read data only through `read`, the\n// engine's pipeline run as the caller, so the model sees nothing that caller\n// could not have read.\nexport type QueryToolDeps = {\n getSchema: () => DatabaseSchema | undefined;\n read: GenerationCaller['read'];\n};\n\nconst GetSchemaInputSchema = z.object({\n entities: z.array(z.string()).optional().describe('Filter to specific entity names'),\n});\nexport type GetSchemaInput = z.infer<typeof GetSchemaInputSchema>;\n\nconst GetSampleRowsInputSchema = z.object({\n entity: z.string().describe('Entity name to sample rows from'),\n limit: z.number().int().positive().max(50).optional().describe('Max rows to return (default: 5)'),\n});\nexport type GetSampleRowsInput = z.infer<typeof GetSampleRowsInputSchema>;\n\nconst GetDistinctValuesInputSchema = z.object({\n entity: z.string().describe('Entity name'),\n field: z.string().describe('Field name within the entity'),\n limit: z.number().int().positive().max(200).optional().describe('Max distinct values to return (default: 20)'),\n});\nexport type GetDistinctValuesInput = z.infer<typeof GetDistinctValuesInputSchema>;\n\nconst DescribeFieldInputSchema = z.object({\n entity: z.string().describe('Entity name'),\n field: z.string().describe('Field name within the entity'),\n});\nexport type DescribeFieldInput = z.infer<typeof DescribeFieldInputSchema>;\n\n// The query itself at the root, no wrapper: models pass the query object\n// directly, and Groq validates tool arguments server-side.\n// Every top-level key and nothing below: a model takes the parameter schema as\n// the whole contract and writes only the keys it names, and Groq refuses the\n// full recursive schema (400). QuerySchema's safeParse is the real validation.\nconst inSpec = (what: string): string => `${what} — written as the DSL spec (OUTPUT SCHEMA) says.`;\nconst TestQueryInputSchema = z\n .object({\n from: z.array(z.unknown()).describe(inSpec('The data sources: entity names (or subqueries); every entity the query uses is listed here')),\n fields: z.array(z.unknown()).optional().describe(inSpec('Raw columns to select, `entity.field` or `{ field, as }`; omit for an aggregate-only query')),\n filter: z.record(z.string(), z.unknown()).optional().describe(inSpec('Filter conditions')),\n compute: z.record(z.string(), z.unknown()).optional().describe(inSpec('Computed fields: output alias → expression')),\n aggregate: z.record(z.string(), z.unknown()).optional().describe(inSpec('Aggregates (count, sum, avg, …): output alias → function')),\n groupBy: z.array(z.unknown()).optional().describe(inSpec('Fields to group by, for aggregates')),\n sort: z.array(z.unknown()).optional().describe(inSpec('Sort order')),\n limit: z.number().optional().describe('Maximum rows to return.'),\n distinct: z.boolean().optional().describe('Eliminate duplicate rows.'),\n })\n .catchall(z.unknown())\n .describe('Your draft DSL query — the query object itself, NOT wrapped in any field.');\nexport type TestQueryInput = z.infer<typeof TestQueryInputSchema>;\n\nconst CannotSatisfyInputSchema = z.object({\n reason: z.string().describe('Why the request cannot be satisfied'),\n});\nexport type CannotSatisfyInput = z.infer<typeof CannotSatisfyInputSchema>;\n\ntype FieldStats = {\n type: string;\n nullable: boolean;\n cardinality: number;\n nullCount: number;\n min?: unknown;\n max?: unknown;\n};\n\ntype TestQueryResult = {\n rows: Row[];\n sql: string;\n warnings: string[];\n errors: string[];\n next?: string;\n};\n\nconst NEXT_AFTER_PASS =\n 'This query runs. If its rows answer the request, you are done: do not test it again — finish now with the envelope, its `data` being exactly this query. If not, change the query and test again.';\n\ntype Located = { entity: EntitySchema } | { error: string };\ntype LocatedField = { entity: EntitySchema; field: FieldSchema } | { error: string };\n\nconst locate = (deps: QueryToolDeps, entityName: string): Located => {\n const schema = deps.getSchema();\n if (schema === undefined) return { error: 'Schema not available' };\n const entity = schema.entities.find((e) => e.name === entityName);\n return entity === undefined ? { error: `Entity \"${entityName}\" not found` } : { entity };\n};\n\nconst locateField = (deps: QueryToolDeps, entityName: string, fieldName: string): LocatedField => {\n const located = locate(deps, entityName);\n if ('error' in located) return located;\n const field = located.entity.fields.find((f) => f.name === fieldName);\n return field === undefined\n ? { error: `Field \"${fieldName}\" not found on entity \"${entityName}\"` }\n : { entity: located.entity, field };\n};\n\nconst messageOf = (err: unknown): string => (err instanceof Error ? err.message : String(err));\n\nconst attempt = async <T>(run: () => Promise<T>): Promise<T | { error: string }> => {\n try {\n return await run();\n } catch (err) {\n return { error: messageOf(err) };\n }\n};\n\nconst firstRow = (rows: Row[]): Row => rows[0] ?? {};\n\nexport const createQueryTools = (deps: QueryToolDeps): ReturnType<typeof defineTool>[] => {\n const getSchemaTool = defineTool({\n id: 'getSchema',\n name: 'getSchema',\n description: 'Returns the introspected database schema, optionally filtered to specific entities.',\n input: GetSchemaInputSchema,\n execute: (input: GetSchemaInput) => {\n const schema = deps.getSchema();\n if (!schema) return { error: 'Schema not available' };\n\n if (input.entities && input.entities.length > 0) {\n const filtered = {\n ...schema,\n entities: schema.entities.filter(e => input.entities?.includes(e.name)),\n };\n return JSON.stringify(filtered);\n }\n\n return JSON.stringify(schema);\n },\n });\n\n const getSampleRowsTool = defineTool({\n id: 'getSampleRows',\n name: 'getSampleRows',\n description: 'Returns sample rows from an entity table.',\n input: GetSampleRowsInputSchema,\n execute: async (input: GetSampleRowsInput) => {\n const located = locate(deps, input.entity);\n if ('error' in located) return located;\n const { entity } = located;\n const fields = entity.fields.filter((f) => f.normalizedType !== 'vector').map((f) => `${entity.name}.${f.name}`);\n const query: Query = { from: [entity.name], fields, limit: input.limit ?? 5 };\n return attempt(async () => (await deps.read(query)).rows);\n },\n });\n\n const getDistinctValuesTool = defineTool({\n id: 'getDistinctValues',\n name: 'getDistinctValues',\n description: 'Returns distinct values for a specific field in an entity.',\n input: GetDistinctValuesInputSchema,\n execute: async (input: GetDistinctValuesInput) => {\n const located = locateField(deps, input.entity, input.field);\n if ('error' in located) return located;\n const { entity, field } = located;\n const query: Query = { from: [entity.name], fields: [`${entity.name}.${field.name}`], distinct: true, limit: input.limit ?? 20 };\n return attempt(async () => (await deps.read(query)).rows.map((row) => row[field.name]));\n },\n });\n\n const describeFieldTool = defineTool({\n id: 'describeField',\n name: 'describeField',\n description: 'Returns statistics about a field: type, nullable, cardinality, null count, min/max for numeric/date types.',\n input: DescribeFieldInputSchema,\n execute: async (input: DescribeFieldInput) => {\n const located = locateField(deps, input.entity, input.field);\n if ('error' in located) return located;\n const { entity, field } = located;\n const path = `${entity.name}.${field.name}`;\n const isNumericOrDate = ['number', 'date', 'timestamp'].includes(field.normalizedType);\n\n return attempt(async (): Promise<FieldStats> => {\n const [counted, nulls, range] = await Promise.all([\n deps.read({ from: [entity.name], aggregate: { cardinality: { countDistinct: path } } }),\n deps.read({ from: [entity.name], aggregate: { null_count: { count: '*' } }, filter: { isNull: path } }),\n isNumericOrDate\n ? deps.read({ from: [entity.name], aggregate: { min_val: { min: path }, max_val: { max: path } } })\n : Promise.resolve(undefined),\n ]);\n\n const stats: FieldStats = {\n type: field.normalizedType,\n nullable: field.nullable,\n cardinality: Number(firstRow(counted.rows)['cardinality'] ?? 0),\n nullCount: Number(firstRow(nulls.rows)['null_count'] ?? 0),\n };\n if (range !== undefined) {\n stats.min = firstRow(range.rows)['min_val'];\n stats.max = firstRow(range.rows)['max_val'];\n }\n return stats;\n });\n },\n });\n\n const testQueryTool = defineTool({\n id: 'testQuery',\n name: 'testQuery',\n description:\n 'Validates a DSL query, compiles it to SQL, and executes it with synthetic parameters (LIMIT 5). ' +\n 'Pass the query object DIRECTLY as the arguments. Returns rows, SQL, warnings, and errors.',\n input: TestQueryInputSchema,\n execute: async (input: TestQueryInput): Promise<TestQueryResult> => {\n if (exceedsDepth(input)) return { rows: [], sql: '', warnings: [], errors: [depthRefusal()] };\n const parseResult = QuerySchema.safeParse(input);\n if (!parseResult.success) {\n const validationErrors = parseResult.error.issues.map(\n issue => `${issue.path.join('.')}: ${issue.message}`,\n );\n return { rows: [], sql: '', warnings: [], errors: validationErrors };\n }\n\n try {\n const { rows, sql, warnings } = await deps.read({ ...parseResult.data, limit: 5 });\n return { rows, sql, warnings, errors: [], next: NEXT_AFTER_PASS };\n } catch (err: unknown) {\n return { rows: [], sql: '', warnings: [], errors: [messageOf(err)] };\n }\n },\n });\n\n // createQueryDsl watches the run's event stream for this tool's id and aborts the run.\n const cannotSatisfyTool = defineTool({\n id: 'cannotSatisfy',\n name: 'cannotSatisfy',\n description: 'Signal that the natural language request cannot be satisfied by the available schema. This ends the run.',\n input: CannotSatisfyInputSchema,\n execute: (input: CannotSatisfyInput) => ({ acknowledged: true, reason: input.reason }),\n });\n\n return [\n getSchemaTool,\n getSampleRowsTool,\n getDistinctValuesTool,\n describeFieldTool,\n testQueryTool,\n cannotSatisfyTool,\n ];\n};\n","import { defineAgent } from '@niscorp/cortex';\nimport type { AgentDefinition } from '@niscorp/cortex';\nimport { stepCount, outputRetries, repeatedCalls } from '@niscorp/cortex';\nimport { QuerySchema } from '../schemas/query.schema.js';\nimport type { Query } from '../schemas/query.schema.js';\nimport type { ScopeBinding } from '../types.js';\n\nexport type VexQueryDeps = {\n schemaJson: string;\n dslSpecJson: string;\n caller?: string;\n};\n\nexport const describeCaller = (bindings: readonly ScopeBinding[]): string =>\n bindings.length === 0\n ? '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.'\n : [\n 'The caller — the person or service this query is for — is identified by server-side scope values bound to these columns:',\n ...bindings.map((b) => `- ${b.entity}.${b.field} is the caller's { \"$scope\": \"${b.key}\" }`),\n '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>\" } — the server binds the caller\\'s own value; you never see or write it.',\n ].join('\\n');\n\nconst INSTRUCTIONS = `You are Vex's query agent. You turn a caller's request — a natural-language \\`intent\\` and an example \\`shape\\` of the data they want back — into ONE query in Vex's DSL.\n\nContext gives you two things:\n- the database schema: the entities, fields, relations, and indexes that actually exist;\n- the DSL JSON Schema: the exact structure your query must take. Its field\n descriptions ARE the rules — read them and follow them. They are the single\n source of truth for how every part of a query is written.\n\nYour job is to RETRIEVE the data the request needs: choose the entities, columns,\nfilters, computed values, and aggregates the schema supports. A separate step runs\nafter you and reshapes, nests, combines and formats the rows, so you never nest.\nBut when a key of the shape is exactly ONE column or ONE aggregate, alias it to\nthat key (\\`{ \"field\": …, \"as\": \"<key>\" }\\`, or name the aggregate after the key):\nwhen every row already has exactly the shape's keys, that later step is skipped.\nA key that needs combining or formatting (a full name from two columns, a date\nwritten out) you leave to it — select the underlying columns under their own names.\n\nWork this way, every time:\n1. If you are unsure what exists or what values a field holds, inspect it with\n your tools before drafting.\n2. Draft the query.\n3. Call testQuery on the draft. You may NOT finish until testQuery has succeeded.\n If it returns an error, your query is wrong — read the error, fix the query,\n and call testQuery again. Repeat until it passes.\n4. Finish. Your envelope's \\`data\\` is the EXACT query that passed\n testQuery (optionally a one-line \\`reasoning\\`).\n5. If the request genuinely cannot be answered from the schema, call\n cannotSatisfy with a short reason instead of guessing.\n\nWorked example (illustrative — real entities and rules come from the schema):\nintent: \"each customer's contact line and how much they've spent, biggest first\"\nshape: [{ \"contact\": \"\", \"spent\": 0 }]\ndata: {\"from\":[\"customer\"],\"fields\":[\"customer.name\",\"customer.email\",{\"field\":\"customer.total_spent\",\"as\":\"spent\"}],\"sort\":[{\"field\":\"customer.total_spent\",\"dir\":\"desc\"}]}\n(\\`spent\\` is one column, so it is aliased; \\`contact\\` combines two, so they are selected as they are.)`;\n\nexport const vexQueryDslAgent: AgentDefinition<Query, VexQueryDeps> = defineAgent<Query, VexQueryDeps>({\n id: 'vex.query',\n description: 'Generates DSL queries from natural language intent and target shape.',\n instructions: INSTRUCTIONS,\n context: [\n ({ deps }) => `Database schema:\\n${deps.schemaJson}`,\n ({ deps }) => deps.caller ?? describeCaller([]),\n // Named OUTPUT SCHEMA because cortex's finish protocol refers to it by that name.\n ({ deps }) => `OUTPUT SCHEMA — the DSL specification (JSON Schema), the single source of truth for your query:\\n${deps.dslSpecJson}`,\n ],\n // The DSL spec in the context is the schema documentation; with `doc` on it would be injected twice.\n output: { schema: QuerySchema, doc: 'off' },\n stopWhen: [stepCount(20), outputRetries(3), repeatedCalls(2)],\n});\n","import type { RunHandle } from '@niscorp/cortex';\nimport { VexError } from '../errors.js';\nimport { mappingAgent } from '@niscorp/prism/agent';\nimport { compile, execute } from '@niscorp/prism';\nimport type { JsonObject } from '@niscorp/prism';\nimport { createQueryTools } from './tools.js';\nimport { describeCaller, vexQueryDslAgent } from './query.agent.js';\nimport type { Query } from '../schemas/query.schema.js';\nimport type { GenerateDsl, MapToShape } from '../types.js';\nimport type { SignalClient } from '@niscorp/cortex';\n\nexport { vexQueryDslAgent, describeCaller } from './query.agent.js';\nexport type { VexQueryDeps } from './query.agent.js';\nexport { createQueryTools } from './tools.js';\nexport type { QueryToolDeps } from './tools.js';\n\nexport type QueryDslConfig = {\n llm: SignalClient;\n queryJsonSchema: object;\n};\n\nconst reasonFrom = (args: unknown): string | undefined => {\n if (typeof args !== 'object' || args === null) return undefined;\n const reason = (args as Record<string, unknown>)['reason'];\n return typeof reason === 'string' ? reason : undefined;\n};\n\nexport const createQueryDsl = (config: QueryDslConfig): GenerateDsl => {\n return async (request, schema, caller) => {\n const tools = createQueryTools({ getSchema: () => schema, read: caller.read });\n\n const agentInput = {\n intent: request.intent,\n shape: request.shape,\n contextKeys: Object.keys(request.context),\n };\n\n let unsatisfiableReason: string | undefined;\n let run: RunHandle<Query> | undefined;\n run = vexQueryDslAgent.run(agentInput, {\n llm: config.llm,\n deps: {\n schemaJson: JSON.stringify(schema),\n dslSpecJson: JSON.stringify(config.queryJsonSchema),\n caller: describeCaller(caller.bindings),\n },\n tools,\n onEvent: (event) => {\n if (\n event.type === 'tool-end' &&\n event.observation.kind === 'result' &&\n event.observation.toolId === 'cannotSatisfy'\n ) {\n unsatisfiableReason = reasonFrom(event.observation.args) ?? 'request cannot be satisfied';\n run?.abort();\n }\n },\n });\n\n const result = await run.result;\n if (!result.ok) {\n if (unsatisfiableReason !== undefined) {\n throw new VexError('unsatisfiable', unsatisfiableReason);\n }\n throw new VexError('agent_failed', `${result.error.code}: ${result.error.message}`);\n }\n return result.output.data;\n };\n};\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// No rows is not a fit: nothing proves the columns, and the identity IR is\n// replayed later against rows that exist.\nexport const rowsFitShape = (rows: readonly Record<string, unknown>[], shape: unknown): boolean => {\n const example = Array.isArray(shape) ? shape[0] : shape;\n const first = rows[0];\n if (!isPlainObject(example) || first === undefined) return false;\n const keys = Object.keys(example);\n if (keys.length !== Object.keys(first).length) return false;\n return keys.every((key) => {\n const sample = example[key];\n if (typeof sample === 'object' && sample !== null) return false;\n if (!(key in first)) return false;\n const value = first[key];\n return value === null || typeof value === typeof sample;\n });\n};\n\nconst IDENTITY = { $ref: '$.result' };\n\nexport const createShapeMapper = (llm: SignalClient): MapToShape => {\n return async (rows, shape) => {\n // `result` must match the envelope engine/runtime.ts replays the IR against.\n const single = !Array.isArray(shape);\n const envelope = { result: single ? (rows[0] ?? null) : rows } as unknown as JsonObject;\n\n if (rowsFitShape(rows, shape)) {\n const ir = await compile(IDENTITY);\n return { ir, transformed: execute(ir, envelope) };\n }\n\n const result = await mappingAgent.run(\n { sampleInput: envelope, targetShape: shape },\n { llm },\n ).result;\n\n if (!result.ok) throw new VexError('agent_failed', `${result.error.code}: ${result.error.message}`);\n\n const ir = await compile(result.output.data);\n const transformed = execute(ir, envelope);\n return { ir, transformed };\n };\n};\n"]}
@@ -1,4 +1,4 @@
1
- import { FilterSchema, FieldPathSchema, VexError, QuerySchema, isVexError, isFieldPathShape } from './chunk-H4BHW76Q.js';
1
+ import { FilterSchema, FieldPathSchema, VexError, QuerySchema, isVexError, isFieldPathShape } from './chunk-J7JYKCUA.js';
2
2
  import { z } from 'zod';
3
3
  import { exceedsDepth, depthRefusal } from '@niscorp/strata';
4
4
 
@@ -10,11 +10,6 @@ var ContextSchema = z.object({
10
10
  'Caller runtime values. Keys referenced from the DSL via { $context: "key" } are bound as SQL parameters. `sortBy` (an entity.field, schema-validated) and `sortDir` ("asc"|"desc") are reserved keys that drive ORDER BY directly and are never bound as parameters.'
11
11
  );
12
12
  var QueryRequestSchema = z.object({
13
- // The ONE cache identity. Server-minted (`fp_…`) when absent — returned in
14
- // meta.cache.fingerprint, an immutable pin. Caller-chosen strings are
15
- // mutable named slots: the name is yours, its content follows your request.
16
- // Alone → replay-or-error. With intent/shape → hit when the stored request
17
- // matches, regenerate-and-replace when it differs (409 when protected).
18
13
  fingerprint: z.string().min(1).optional(),
19
14
  intent: z.string().optional(),
20
15
  shape: z.unknown().optional(),
@@ -482,13 +477,9 @@ var computeSchemaFingerprint = (schema) => {
482
477
  primaryKey: f.primaryKey,
483
478
  ...f.vectorDimensions !== void 0 ? { vectorDimensions: f.vectorDimensions } : {}
484
479
  })),
485
- // Column order within a relation is the key's own order, so it is
486
- // preserved; relations are sorted by target and columns. This shape
487
- // changed when keys became composite, so every entry cached before
488
- // revalidates once on the next boot — the drift eviction, by design.
480
+ // Column order within a relation is the key's own order, so it is not sorted.
489
481
  relations: [...e.relations].sort((a, b) => `${a.entity}.${a.localFields.join(",")}`.localeCompare(`${b.entity}.${b.localFields.join(",")}`)).map((r) => ({ type: r.type, entity: r.entity, localFields: r.localFields, foreignFields: r.foreignFields })),
490
- // Index field order is significant (composite indexes) and stable
491
- // from introspection, so it is preserved; indexes are sorted by name.
482
+ // Index field order is significant (composite indexes) and stable from introspection.
492
483
  indexes: [...e.indexes].sort(byName).map((i) => ({
493
484
  name: i.name,
494
485
  fields: i.fields,
@@ -615,8 +606,7 @@ var compileFilter = (filter, ctx) => {
615
606
  const inner = {
616
607
  ...ctx,
617
608
  resolvedPaths: resolved.filter?.resolvedPaths ?? ctx.resolvedPaths,
618
- // The inner map LAYERS OVER the outer one, so an inner path resolves to
619
- // the inner alias and an outer path — the correlation — still resolves.
609
+ // Inner over outer: an outer path, the correlation, still resolves.
620
610
  aliasMap: new Map([...ctx.aliasMap, ...resolved.aliasMap])
621
611
  };
622
612
  const parts = ["SELECT 1"];
@@ -843,9 +833,7 @@ var UpsertSchema = z.object({
843
833
  op: z.literal("upsert"),
844
834
  table: z.string(),
845
835
  columns: Columns,
846
- // set on BOTH branches (update SET, and part of the insert)
847
836
  insert: Columns.optional(),
848
- // extra columns set ONLY on insert — immutable-on-create (e.g. a FK)
849
837
  key: z.string()
850
838
  }).strict().describe('Sugar: insert-or-update by `key` (e.g. "id"). Desugars to update (SET columns WHERE key) when the key is present, else insert (columns + `insert`-only).');
851
839
  var MutationSchema = z.discriminatedUnion("op", [InsertSchema, InsertEachSchema, UpdateSchema, DeleteSchema, UpsertSchema]);
@@ -1505,7 +1493,6 @@ var listFingerprints = async (engine, policy) => {
1505
1493
  ...entry.intent !== void 0 ? { intent: entry.intent } : {},
1506
1494
  createdAt: entry.createdAt,
1507
1495
  ...entry.lastUsedAt !== void 0 ? { lastUsedAt: entry.lastUsedAt } : {},
1508
- // The derived contract — what to pass, straight from the stored def.
1509
1496
  ...entry.kind === "ok" ? {
1510
1497
  context: collectQueryContext(entry.dsl, schema),
1511
1498
  ...entry.shape !== void 0 ? { shape: entry.shape } : {}
@@ -1581,8 +1568,6 @@ var handleQuery = async (config, body, scope, live) => {
1581
1568
  const result = await runQuery(config, body, scope, probe, live);
1582
1569
  const record = {
1583
1570
  kind: probe.kind,
1584
- // 200 succeeded; 403 is a policy/reach refusal (a normal outcome, not a
1585
- // fault); everything else is an error.
1586
1571
  status: result.status === 200 ? "ok" : result.status === 403 ? "refused" : "error",
1587
1572
  startUnixNano,
1588
1573
  endUnixNano: startUnixNano + (elapsedClock() - t0) * 1e6,
@@ -1774,5 +1759,5 @@ var handleFingerprintDelete = async (config, fingerprint) => {
1774
1759
  };
1775
1760
 
1776
1761
  export { MutationDefinitionSchema, MutationSchema, QueryRequestSchema, VexScopeError, applyScope, buildContextContract, buildValidationContext, canReadTable, canonicalHash, canonicalText, checkScope, collectMutationContext, collectQueryContext, compileAggregate, compileCompute, compileFieldOrValue, compileFilter, compileJoinPairs, computePolicyKey, computeRequestHash, computeSchemaFingerprint, executeMutation, executeQuery, executeWrites, findMissingContext, fireAndForget, handleDiscovery, handleFingerprintDelete, handleFingerprintPatch, handleQuery, hashText, isEntryFresh, isSetMatch, isTouchDue, lintMutation, mintFingerprint, mutationEffect, mutationMisfits, normalizeShape, optionalKeysOf, presenceOf, presenceSignature, pruneOptional, quoteIdent, refuseOptional, requireScope, requiredContextKeys, resolveParams, scopeResolved, sweepCache, tablesChangedBy };
1777
- //# sourceMappingURL=chunk-IQM4SQE2.js.map
1778
- //# sourceMappingURL=chunk-IQM4SQE2.js.map
1762
+ //# sourceMappingURL=chunk-3HORTMZ7.js.map
1763
+ //# sourceMappingURL=chunk-3HORTMZ7.js.map