@niscorp/vex 0.3.1 → 0.4.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/CHANGELOG.md +12 -0
- package/DESIGN.md +4 -3
- package/DOCS.md +26 -4
- package/dist/adapters/express/index.cjs +1 -1
- package/dist/adapters/express/index.cjs.map +1 -1
- package/dist/adapters/express/index.d.cts +3 -2
- package/dist/adapters/express/index.d.ts +3 -2
- package/dist/adapters/express/index.js +3 -2
- package/dist/adapters/express/index.js.map +1 -1
- package/dist/adapters/hono/index.cjs +1 -1
- package/dist/adapters/hono/index.cjs.map +1 -1
- package/dist/adapters/hono/index.d.cts +3 -2
- package/dist/adapters/hono/index.d.ts +3 -2
- package/dist/adapters/hono/index.js +3 -2
- package/dist/adapters/hono/index.js.map +1 -1
- package/dist/agent/index.cjs +4 -3
- package/dist/agent/index.cjs.map +1 -1
- package/dist/agent/index.d.cts +3 -2
- package/dist/agent/index.d.ts +3 -2
- package/dist/agent/index.js +6 -4
- package/dist/agent/index.js.map +1 -1
- package/dist/{chunk-3HORTMZ7.js → chunk-7F2OH4IP.js} +5 -4
- package/dist/chunk-7F2OH4IP.js.map +1 -0
- package/dist/chunk-F7RDSWYF.js +7 -0
- package/dist/chunk-F7RDSWYF.js.map +1 -0
- package/dist/{chunk-J7JYKCUA.js → chunk-UPQMKAAX.js} +3 -18
- package/dist/chunk-UPQMKAAX.js.map +1 -0
- package/dist/chunk-XTOK7YOR.js +18 -0
- package/dist/chunk-XTOK7YOR.js.map +1 -0
- package/dist/{handler-B4NAi4k_.d.cts → handler-Bw7xVmBM.d.ts} +2 -1
- package/dist/{handler-BRVhWuNk.d.ts → handler-Cy0gNM6K.d.cts} +2 -1
- package/dist/index.cjs +21 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -4
- package/dist/index.d.ts +6 -4
- package/dist/index.js +29 -19
- package/dist/index.js.map +1 -1
- package/dist/migrations/index.cjs +173 -0
- package/dist/migrations/index.cjs.map +1 -0
- package/dist/migrations/index.d.cts +20 -0
- package/dist/migrations/index.d.ts +20 -0
- package/dist/migrations/index.js +23 -0
- package/dist/migrations/index.js.map +1 -0
- package/dist/query.schema-B-LVNfyX.d.cts +461 -0
- package/dist/query.schema-B-LVNfyX.d.ts +461 -0
- package/dist/{types-DUJp5B3o.d.cts → types-Bs_9VM9p.d.ts} +10 -462
- package/dist/{types-DUJp5B3o.d.ts → types-DO-rYZci.d.cts} +10 -462
- package/package.json +11 -1
- package/dist/chunk-3HORTMZ7.js.map +0 -1
- package/dist/chunk-J7JYKCUA.js.map +0 -1
package/dist/agent/index.js.map
CHANGED
|
@@ -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,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,8BAA8B,CAAA;AAAA,EACzD,KAAA,EAAO,CAAA,CAAE,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B,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/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,C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QAAQ,CAAA;AACxC,IAAA,OAAO,EAAE,EAAA,EAAI,MAAA,EAAQ,WAAA,EAAY;AAAA,EACnC,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, config: IDENTITY, 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 config = result.output.data;\n const ir = await compile(config);\n const transformed = execute(ir, envelope);\n return { ir, config, transformed };\n };\n};\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
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
|
|
|
@@ -1612,7 +1613,7 @@ var runQuery = async (config, body, scope, probe, live) => {
|
|
|
1612
1613
|
try {
|
|
1613
1614
|
let entryReach;
|
|
1614
1615
|
if (parsed.data.fingerprint !== void 0) {
|
|
1615
|
-
const entry = await engine.cache.get(parsed.data.fingerprint);
|
|
1616
|
+
const entry = await engine.cache.get(parsed.data.fingerprint, scope);
|
|
1616
1617
|
if (entry !== void 0 && entry.kind === "ok") entryReach = entry.reach;
|
|
1617
1618
|
if (probe !== void 0 && entryReach !== void 0) probe.reach = entryReach;
|
|
1618
1619
|
if (entry !== void 0 && entry.kind === "mutation") {
|
|
@@ -1759,5 +1760,5 @@ var handleFingerprintDelete = async (config, fingerprint) => {
|
|
|
1759
1760
|
};
|
|
1760
1761
|
|
|
1761
1762
|
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-
|
|
1763
|
-
//# sourceMappingURL=chunk-
|
|
1763
|
+
//# sourceMappingURL=chunk-7F2OH4IP.js.map
|
|
1764
|
+
//# sourceMappingURL=chunk-7F2OH4IP.js.map
|