@niscorp/vex 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +881 -0
- package/DOCS.md +1295 -0
- package/LICENSE +202 -0
- package/README.md +97 -0
- package/dist/adapters/express/index.cjs +1406 -0
- package/dist/adapters/express/index.cjs.map +1 -0
- package/dist/adapters/express/index.d.cts +25 -0
- package/dist/adapters/express/index.d.ts +25 -0
- package/dist/adapters/express/index.js +60 -0
- package/dist/adapters/express/index.js.map +1 -0
- package/dist/adapters/hono/index.cjs +1426 -0
- package/dist/adapters/hono/index.cjs.map +1 -0
- package/dist/adapters/hono/index.d.cts +25 -0
- package/dist/adapters/hono/index.d.ts +25 -0
- package/dist/adapters/hono/index.js +78 -0
- package/dist/adapters/hono/index.js.map +1 -0
- package/dist/adapters/pglite/index.cjs +17 -0
- package/dist/adapters/pglite/index.cjs.map +1 -0
- package/dist/adapters/pglite/index.d.cts +21 -0
- package/dist/adapters/pglite/index.d.ts +21 -0
- package/dist/adapters/pglite/index.js +14 -0
- package/dist/adapters/pglite/index.js.map +1 -0
- package/dist/agent/index.cjs +478 -0
- package/dist/agent/index.cjs.map +1 -0
- package/dist/agent/index.d.cts +29 -0
- package/dist/agent/index.d.ts +29 -0
- package/dist/agent/index.js +313 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/chunk-FPKW4TRX.js +1528 -0
- package/dist/chunk-FPKW4TRX.js.map +1 -0
- package/dist/chunk-HF25Q53I.js +165 -0
- package/dist/chunk-HF25Q53I.js.map +1 -0
- package/dist/handler-Cql8SJ3F.d.cts +133 -0
- package/dist/handler-mICf9ins.d.ts +133 -0
- package/dist/index.cjs +4078 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +199 -0
- package/dist/index.d.ts +199 -0
- package/dist/index.js +2340 -0
- package/dist/index.js.map +1 -0
- package/dist/introspect-D3OaXHBc.d.cts +16 -0
- package/dist/introspect-D3OaXHBc.d.ts +16 -0
- package/dist/types-BRvMB6IM.d.cts +1491 -0
- package/dist/types-BRvMB6IM.d.ts +1491 -0
- package/package.json +125 -0
|
@@ -0,0 +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,EAAO,CAAE,SAAS,aAAa,CAAA;AAAA,EACzC,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,8BAA8B;AA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AA;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"]}
|