@niscorp/vex 0.3.1 → 0.4.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 (50) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/DESIGN.md +11 -7
  3. package/DOCS.md +52 -9
  4. package/dist/adapters/express/index.cjs +1 -1
  5. package/dist/adapters/express/index.cjs.map +1 -1
  6. package/dist/adapters/express/index.d.cts +3 -2
  7. package/dist/adapters/express/index.d.ts +3 -2
  8. package/dist/adapters/express/index.js +3 -2
  9. package/dist/adapters/express/index.js.map +1 -1
  10. package/dist/adapters/hono/index.cjs +1 -1
  11. package/dist/adapters/hono/index.cjs.map +1 -1
  12. package/dist/adapters/hono/index.d.cts +3 -2
  13. package/dist/adapters/hono/index.d.ts +3 -2
  14. package/dist/adapters/hono/index.js +3 -2
  15. package/dist/adapters/hono/index.js.map +1 -1
  16. package/dist/agent/index.cjs +144 -21
  17. package/dist/agent/index.cjs.map +1 -1
  18. package/dist/agent/index.d.cts +3 -2
  19. package/dist/agent/index.d.ts +3 -2
  20. package/dist/agent/index.js +146 -22
  21. package/dist/agent/index.js.map +1 -1
  22. package/dist/{chunk-3HORTMZ7.js → chunk-AKR6HU34.js} +9 -5
  23. package/dist/chunk-AKR6HU34.js.map +1 -0
  24. package/dist/chunk-F7RDSWYF.js +7 -0
  25. package/dist/chunk-F7RDSWYF.js.map +1 -0
  26. package/dist/{chunk-J7JYKCUA.js → chunk-UPQMKAAX.js} +3 -18
  27. package/dist/chunk-UPQMKAAX.js.map +1 -0
  28. package/dist/chunk-XTOK7YOR.js +18 -0
  29. package/dist/chunk-XTOK7YOR.js.map +1 -0
  30. package/dist/{handler-B4NAi4k_.d.cts → handler-CoJxInw-.d.ts} +2 -1
  31. package/dist/{handler-BRVhWuNk.d.ts → handler-CsFbanZA.d.cts} +2 -1
  32. package/dist/index.cjs +26 -13
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +6 -4
  35. package/dist/index.d.ts +6 -4
  36. package/dist/index.js +30 -20
  37. package/dist/index.js.map +1 -1
  38. package/dist/migrations/index.cjs +173 -0
  39. package/dist/migrations/index.cjs.map +1 -0
  40. package/dist/migrations/index.d.cts +20 -0
  41. package/dist/migrations/index.d.ts +20 -0
  42. package/dist/migrations/index.js +23 -0
  43. package/dist/migrations/index.js.map +1 -0
  44. package/dist/query.schema-B-LVNfyX.d.cts +461 -0
  45. package/dist/query.schema-B-LVNfyX.d.ts +461 -0
  46. package/dist/{types-DUJp5B3o.d.cts → types-B2HEmyNq.d.cts} +11 -463
  47. package/dist/{types-DUJp5B3o.d.ts → types-DC68ZUuq.d.ts} +11 -463
  48. package/package.json +12 -1
  49. package/dist/chunk-3HORTMZ7.js.map +0 -1
  50. package/dist/chunk-J7JYKCUA.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":";;;;;;;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,EAA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B,IAAM,iBAAA,GAAoB,CAAC,GAAA,KAAkC;AAClE,EAAA,OAAO,OAAO,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
+ {"version":3,"sources":["../../src/agent/tools.ts","../../src/agent/compact.ts","../../src/agent/declared.ts","../../src/agent/query.agent.ts","../../src/agent/index.ts"],"names":["isRecord","attempt"],"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,EA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AAM,YAAA,CAAa,GAAA,CAAI,EAAE,WAAA,EAAa,QAAA,EAAU,aAAa,KAAA,EAAO,GAAI,UAAU,EAAA,GAAK,EAAE,OAAM,GAAI,IAAI,EAAG,EAAE,GAAA,EAAK,CAAA,CAAE,MAAA;AAClI,MAAA,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;AAClG,MAAA,MAAM,MAAA,GAAS,OAAO,MAAA,CAAO,IAAA;AAC7B,MAAA,IAAI;AACF,QAAA,MAAM,EAAA,GAAK,MAAM,OAAA,CAAQ,MAAM,CAAA;AAC/B,QAAA,OAAO,EAAE,EAAA,EAAI,MAAA,EAAQ,aAAa,OAAA,CAAQ,EAAA,EAAI,QAAQ,CAAA,EAAE;AAAA,MAC1D,SAAS,KAAA,EAAO;AACd,QAAA,MAAA,GAAS,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AAAA,MAChE;AAAA,IACF;AACA,IAAA,MAAM,IAAI,QAAA,CAAS,cAAA,EAAgB,CAAA,wDAAA,EAA2D,MAAA,IAAU,iBAAiB,CAAA,CAAE,CAAA;AAAA,EAC7H,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 type { DatabaseSchema } from '../schemas/database.schema.js';\n\n// What the query agent reads, written as text rather than JSON: the same entities, fields, keys and rules in\n// fewer tokens. The query it writes is still validated against the full DSL schema.\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);\n\nexport const compactSchema = (schema: DatabaseSchema): string =>\n schema.entities\n .map((entity) => {\n const fields = entity.fields.map((field) => `${field.name} ${field.type}${field.primaryKey ? ' key' : ''}${field.nullable ? ' null' : ''}`);\n const relations = entity.relations.map((relation) => `${relation.type} ${relation.entity} (${relation.localFields.join(', ')} = ${relation.entity}.${relation.foreignFields.join(', ')})`);\n const indexed = entity.indexes.filter((index) => !(index.unique && index.fields.length === 1 && entity.fields.some((field) => field.primaryKey && field.name === index.fields[0])));\n return [\n `${entity.name}${entity.table === entity.name ? '' : ` (table ${entity.table})`}: ${fields.join(', ')}`,\n ...(relations.length > 0 ? [` relations: ${relations.join('; ')}`] : []),\n ...(indexed.length > 0 ? [` indexed: ${indexed.map((index) => `${index.fields.join('+')}${index.unique ? ' unique' : ''}`).join(', ')}`] : []),\n ].join('\\n');\n })\n .join('\\n');\n\n// \"#/definitions/__schema14\" → \"D14\".\nconst nameOf = (ref: string): string => ref.replace(/^#\\/definitions\\/(?:__schema)?/, 'D');\n\nconst noteOf = (node: Record<string, unknown>): string => {\n const limits = ['minItems', 'maxItems', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'minLength', 'maxLength', 'pattern', 'format', 'default']\n .filter((key) => key in node)\n .map((key) => `${key} ${JSON.stringify(node[key])}`);\n return limits.length > 0 ? ` (${limits.join(', ')})` : '';\n};\n\nconst describedOf = (node: unknown): string => (isRecord(node) && typeof node['description'] === 'string' ? ` /* ${node['description']} */` : '');\n\nconst SPELLED = new Set(['$ref', 'anyOf', 'oneOf', 'allOf', 'enum', 'const', 'type', 'items', 'properties', 'required', 'additionalProperties', 'description', 'minItems', 'maxItems', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'minLength', 'maxLength', 'pattern', 'format', 'default', '$schema']);\n\n// A node as text, its own description beside it wherever it sits. A keyword this writer does not spell out keeps\n// its JSON, so nothing the schema says is dropped.\nconst typeOf = (node: unknown, indent: string): string =>\n isRecord(node) && !Object.keys(node).some((key) => !SPELLED.has(key)) ? `${shapeOf(node, indent)}${describedOf(node)}` : JSON.stringify(node);\n\nconst shapeOf = (node: Record<string, unknown>, indent: string): string => {\n if (typeof node['$ref'] === 'string') return nameOf(node['$ref']);\n const alternatives = node['anyOf'] ?? node['oneOf'];\n if (Array.isArray(alternatives)) {\n if (!alternatives.some((alternative) => describedOf(alternative) !== '')) return alternatives.map((alternative) => typeOf(alternative, indent)).join(' | ');\n return alternatives.map((alternative) => `\\n${indent} | ${typeOf(alternative, `${indent} `)}`).join('');\n }\n if (Array.isArray(node['allOf'])) return node['allOf'].map((part) => typeOf(part, indent)).join(' & ');\n if (Array.isArray(node['enum'])) return node['enum'].map((value) => JSON.stringify(value)).join(' | ');\n if ('const' in node) return JSON.stringify(node['const']);\n const kind = node['type'];\n if (kind === 'array') {\n const item = typeOf(node['items'], indent);\n return `${/[ |&]/.test(item) ? `(${item})` : item}[]${noteOf(node)}`;\n }\n if (kind === 'object' || isRecord(node['properties'])) {\n const required = new Set(Array.isArray(node['required']) ? node['required'] : []);\n const properties = Object.entries(isRecord(node['properties']) ? node['properties'] : {}).map(\n ([key, value]) => `${key}${required.has(key) ? '' : '?'}: ${typeOf(value, indent)}`,\n );\n const rest = isRecord(node['additionalProperties']) ? [`[key: string]: ${typeOf(node['additionalProperties'], indent)}`] : [];\n return `{ ${[...properties, ...rest].join(', ')} }`;\n }\n if (Array.isArray(kind)) return kind.join(' | ');\n if (typeof kind === 'string') return `${kind}${noteOf(node)}`;\n return JSON.stringify(node);\n};\n\nexport const compactSpec = (jsonSchema: object): string => {\n const root = jsonSchema as Record<string, unknown>;\n const definitions = isRecord(root['definitions']) ? root['definitions'] : {};\n const number = (name: string): number => Number(name.replace(/\\D/g, '')) || 0;\n return [\n 'The query is one JSON object of type Query; every Dn is defined below. \"a?: T\" is optional, \"A | B\" is either.',\n `Query = ${typeOf({ type: 'object', properties: root['properties'], required: root['required'] }, '')}`,\n ...Object.entries(definitions)\n .sort(([a], [b]) => number(a) - number(b))\n .map(([name, node]) => `${nameOf(`#/definitions/${name}`)} = ${typeOf(node, '')}`),\n ].join('\\n');\n};\n","// A field a request declares as a prism expression over the row's own stored fields, beside the plain ones:\n// [{ \"close_date\": \"\", \"close_date_display\": { \"$date\": { \"value\": { \"$ref\": \"$.close_date\" }, \"format\": \"MMM D\" } } }].\n// The query returns the stored fields; the declared ones are computed from them by prism, never by a model.\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);\n\nconst isExpression = (value: unknown): value is Record<string, unknown> => isRecord(value) && Object.keys(value).length === 1 && Object.keys(value)[0]?.startsWith('$') === true;\n\nconst templateOf = (shape: unknown): unknown => (Array.isArray(shape) ? shape[0] : shape);\n\n// The stored fields an expression reads: \"$.close_date\" → close_date.\nconst readsOf = (value: unknown): string[] => {\n if (Array.isArray(value)) return value.flatMap(readsOf);\n if (!isRecord(value)) return [];\n const ref = value['$ref'];\n const own = typeof ref === 'string' && ref.startsWith('$.') ? [ref.slice(2).split('.')[0] ?? ''] : [];\n return [...own, ...Object.values(value).flatMap(readsOf)].filter((field) => field !== '');\n};\n\n// The fields of a flat row template: each plain field, and each declared one with what it reads. A nested shape is\n// no flat template, and is mapped as before.\nconst fieldsOf = (shape: unknown): { plain: string[]; declared: [string, Record<string, unknown>][] } | undefined => {\n const template = templateOf(shape);\n if (!isRecord(template)) return undefined;\n const entries = Object.entries(template);\n if (entries.some(([, value]) => (isRecord(value) || Array.isArray(value)) && !isExpression(value))) return undefined;\n return {\n plain: entries.filter(([, value]) => !isExpression(value)).map(([key]) => key),\n declared: entries.filter((entry): entry is [string, Record<string, unknown>] => isExpression(entry[1])),\n };\n};\n\n// The shape the query is written for: the declared fields replaced by the stored fields they read.\nexport const storedShape = (shape: unknown): { shape: unknown; declared: boolean } => {\n const fields = fieldsOf(shape);\n if (fields === undefined || fields.declared.length === 0) return { shape, declared: false };\n const template = templateOf(shape) as Record<string, unknown>;\n const kept = Object.fromEntries(fields.plain.map((key) => [key, template[key]]));\n for (const [, expression] of fields.declared) for (const field of readsOf(expression)) if (!(field in kept)) kept[field] = '';\n return { shape: Array.isArray(shape) ? [kept] : kept, declared: true };\n};\n\n// A row's own field, read inside the mapping: \"$.close_date\" → the field of the row being mapped.\nconst onRow = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(onRow);\n if (!isRecord(value)) return value;\n const ref = value['$ref'];\n if (typeof ref === 'string' && ref.startsWith('$.') && Object.keys(value).length === 1) return { $get: { from: { $var: 'row' }, path: ref.slice(2).split('.'), fallback: null } };\n return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, onRow(inner)]));\n};\n\n// The mapping as a prism config over vex's envelope ({ result: rows }, or the first row for a single shape): plain\n// fields copied, declared ones computed. Undefined for a shape that is not a flat row template.\nexport const declaredMapping = (shape: unknown): { config: object; reads: string[]; examples: Record<string, unknown> } | undefined => {\n const fields = fieldsOf(shape);\n if (fields === undefined) return undefined;\n const template = templateOf(shape) as Record<string, unknown>;\n const body = Object.fromEntries([\n ...fields.plain.map((key) => [key, { $get: { from: { $var: 'row' }, path: [key], fallback: null } }]),\n ...fields.declared.map(([key, expression]) => [key, onRow(expression)]),\n ]);\n const reads = [...new Set([...fields.plain, ...fields.declared.flatMap(([, expression]) => readsOf(expression))])];\n const config = Array.isArray(shape) ? { $map: { over: { $ref: '$.result' }, as: 'row', body } } : { $with: { let: { row: { $ref: '$.result' } }, value: body } };\n return { config, reads, examples: Object.fromEntries(fields.plain.map((key) => [key, template[key]])) };\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 specification, written as types: the exact structure your query must\n take. Its descriptions ARE the rules — read them and follow them. They are the\n single 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, written as types, 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 { compactSchema, compactSpec } from './compact.js';\nimport { declaredMapping, storedShape } from './declared.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 const dslSpec = compactSpec(config.queryJsonSchema);\n return async (request, schema, caller) => {\n const tools = createQueryTools({ getSchema: () => schema, read: caller.read });\n\n // A shape with declared fields asks only for the stored fields they read: they are computed after the query.\n const stored = storedShape(request.shape);\n const agentInput = {\n intent: stored.declared ? `${request.intent ?? ''}\\nReturn the stored fields the shape names; how a field is shown is worked out from them after the query.` : request.intent,\n shape: stored.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: compactSchema(schema),\n dslSpecJson: dslSpec,\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 MAPPING_ATTEMPTS = 3;\n\nexport const createShapeMapper = (llm: SignalClient): MapToShape => {\n return async (rows, shape, intent) => {\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 // A flat shape whose fields the rows carry, each plain one of the kind its example shows, is mapped by prism from\n // the shape itself, declared fields computed from the stored ones; the agent writes the mapping for any other.\n const declared = declaredMapping(shape);\n const first = rows[0];\n const carried =\n first === undefined ||\n (declared !== undefined &&\n declared.reads.every((field) => field in first) &&\n Object.entries(declared.examples).every(([field, example]) => first[field] === null || typeof first[field] === typeof example));\n if (declared !== undefined && carried) {\n const ir = await compile(declared.config);\n return { ir, config: declared.config, transformed: execute(ir, envelope) };\n }\n\n let failed: string | undefined;\n for (let attempt = 1; attempt <= MAPPING_ATTEMPTS; attempt += 1) {\n const notes = [\n ...(intent !== undefined\n ? [`The request these rows answer: ${intent}. The rows already answer it: they are filtered, sorted and limited. Give each value the form the request names, and keep every row, in order.`]\n : []),\n ...(failed !== undefined ? [`Your last config failed on these rows: ${failed}. Write one that runs on them.`] : []),\n ].join('\\n');\n const result = await mappingAgent.run({ sampleInput: envelope, targetShape: shape, ...(notes !== '' ? { notes } : {}) }, { llm }).result;\n if (!result.ok) throw new VexError('agent_failed', `${result.error.code}: ${result.error.message}`);\n const config = result.output.data;\n try {\n const ir = await compile(config);\n return { ir, config, transformed: execute(ir, envelope) };\n } catch (error) {\n failed = error instanceof Error ? error.message : String(error);\n }\n }\n throw new VexError('agent_failed', `the mapping did not run on the rows it was written for: ${failed ?? 'no reason given'}`);\n };\n};\n"]}
@@ -1,4 +1,5 @@
1
- import { FilterSchema, FieldPathSchema, VexError, QuerySchema, isVexError, isFieldPathShape } from './chunk-J7JYKCUA.js';
1
+ import { VexError, isVexError } from './chunk-XTOK7YOR.js';
2
+ import { FilterSchema, FieldPathSchema, QuerySchema, isFieldPathShape } from './chunk-UPQMKAAX.js';
2
3
  import { z } from 'zod';
3
4
  import { exceedsDepth, depthRefusal } from '@niscorp/strata';
4
5
 
@@ -424,6 +425,7 @@ var canonicalHash = (value) => hashText(canonicalText(value));
424
425
 
425
426
  // src/cache/hash.ts
426
427
  var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
428
+ var sortedDeep = (value) => Array.isArray(value) ? value.map(sortedDeep) : isRecord(value) ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, sortedDeep(value[key])])) : value;
427
429
  var normalizeShape = (shape) => {
428
430
  if (shape === null) return "null";
429
431
  if (shape === void 0) return "unknown";
@@ -432,7 +434,9 @@ var normalizeShape = (shape) => {
432
434
  return first !== void 0 ? [normalizeShape(first)] : [];
433
435
  }
434
436
  if (isRecord(shape)) {
435
- const sortedKeys = Object.keys(shape).sort();
437
+ const keys = Object.keys(shape);
438
+ if (keys.length === 1 && keys[0]?.startsWith("$") === true) return sortedDeep(shape);
439
+ const sortedKeys = keys.sort();
436
440
  const normalized = {};
437
441
  for (const key of sortedKeys) {
438
442
  normalized[key] = normalizeShape(shape[key]);
@@ -1612,7 +1616,7 @@ var runQuery = async (config, body, scope, probe, live) => {
1612
1616
  try {
1613
1617
  let entryReach;
1614
1618
  if (parsed.data.fingerprint !== void 0) {
1615
- const entry = await engine.cache.get(parsed.data.fingerprint);
1619
+ const entry = await engine.cache.get(parsed.data.fingerprint, scope);
1616
1620
  if (entry !== void 0 && entry.kind === "ok") entryReach = entry.reach;
1617
1621
  if (probe !== void 0 && entryReach !== void 0) probe.reach = entryReach;
1618
1622
  if (entry !== void 0 && entry.kind === "mutation") {
@@ -1759,5 +1763,5 @@ var handleFingerprintDelete = async (config, fingerprint) => {
1759
1763
  };
1760
1764
 
1761
1765
  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 };
1762
- //# sourceMappingURL=chunk-3HORTMZ7.js.map
1763
- //# sourceMappingURL=chunk-3HORTMZ7.js.map
1766
+ //# sourceMappingURL=chunk-AKR6HU34.js.map
1767
+ //# sourceMappingURL=chunk-AKR6HU34.js.map