@niscorp/vex 0.4.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/DESIGN.md +72 -45
  3. package/DOCS.md +219 -21
  4. package/README.md +18 -0
  5. package/dist/adapters/express/index.cjs +606 -173
  6. package/dist/adapters/express/index.cjs.map +1 -1
  7. package/dist/adapters/express/index.d.cts +6 -2
  8. package/dist/adapters/express/index.d.ts +6 -2
  9. package/dist/adapters/express/index.js +16 -3
  10. package/dist/adapters/express/index.js.map +1 -1
  11. package/dist/adapters/hono/index.cjs +597 -173
  12. package/dist/adapters/hono/index.cjs.map +1 -1
  13. package/dist/adapters/hono/index.d.cts +5 -2
  14. package/dist/adapters/hono/index.d.ts +5 -2
  15. package/dist/adapters/hono/index.js +7 -3
  16. package/dist/adapters/hono/index.js.map +1 -1
  17. package/dist/agent/index.cjs +12 -12
  18. package/dist/agent/index.cjs.map +1 -1
  19. package/dist/agent/index.d.cts +1 -1
  20. package/dist/agent/index.d.ts +1 -1
  21. package/dist/agent/index.js +12 -12
  22. package/dist/agent/index.js.map +1 -1
  23. package/dist/{chunk-W5MYFJKT.js → chunk-F7OXXJIH.js} +562 -192
  24. package/dist/chunk-F7OXXJIH.js.map +1 -0
  25. package/dist/{chunk-F7RDSWYF.js → chunk-VHNCSQPO.js} +2 -2
  26. package/dist/{chunk-F7RDSWYF.js.map → chunk-VHNCSQPO.js.map} +1 -1
  27. package/dist/{handler-CoJxInw-.d.ts → handler-DdfaWN_J.d.ts} +7 -1
  28. package/dist/{handler-CsFbanZA.d.cts → handler-kvZkxwaN.d.cts} +7 -1
  29. package/dist/index.cjs +667 -259
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +5 -3
  32. package/dist/index.d.ts +5 -3
  33. package/dist/index.js +290 -248
  34. package/dist/index.js.map +1 -1
  35. package/dist/migrations/index.cjs.map +1 -1
  36. package/dist/migrations/index.js +1 -1
  37. package/dist/{types-B2HEmyNq.d.cts → types-BxkRxTTx.d.cts} +38 -2
  38. package/dist/{types-DC68ZUuq.d.ts → types-DgUZNKii.d.ts} +38 -2
  39. package/package.json +8 -8
  40. package/dist/chunk-W5MYFJKT.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { Env, Context, Hono } from 'hono';
2
- import { a as QueryEngine, aa as ScopeValues, S as ScopePolicy } from '../../types-B2HEmyNq.cjs';
3
- import { M as MutationClient, W as WriteEvent, E as ExecuteRecord } from '../../handler-CsFbanZA.cjs';
2
+ import { a as QueryEngine, ab as ScopeValues, S as ScopePolicy } from '../../types-BxkRxTTx.cjs';
3
+ import { M as MutationClient, W as WriteEvent, E as ExecuteRecord } from '../../handler-kvZkxwaN.cjs';
4
4
  import '../../query.schema-B-LVNfyX.cjs';
5
5
  import 'zod';
6
6
  import '@niscorp/prism';
@@ -11,6 +11,7 @@ type VexHonoConfig<E extends Env = Env> = {
11
11
  engine: QueryEngine;
12
12
  entities?: string[];
13
13
  locked?: boolean;
14
+ manageFingerprints?: boolean;
14
15
  getScope?: (c: Context<E>) => Promise<ScopeValues> | ScopeValues;
15
16
  getPolicy?: (c: Context<E>) => Promise<ScopePolicy | undefined> | ScopePolicy | undefined;
16
17
  getPolicyForReach?: (c: Context<E>, reach: string) => Promise<ScopePolicy | undefined> | ScopePolicy | undefined;
@@ -18,6 +19,8 @@ type VexHonoConfig<E extends Env = Env> = {
18
19
  client: MutationClient;
19
20
  policy?: ScopePolicy;
20
21
  onWrite?: (event: WriteEvent) => void;
22
+ checkMovedRows?: boolean;
23
+ answerReadableRows?: boolean;
21
24
  };
22
25
  onExecute?: (record: ExecuteRecord) => void;
23
26
  };
@@ -1,6 +1,6 @@
1
1
  import { Env, Context, Hono } from 'hono';
2
- import { a as QueryEngine, aa as ScopeValues, S as ScopePolicy } from '../../types-DC68ZUuq.js';
3
- import { M as MutationClient, W as WriteEvent, E as ExecuteRecord } from '../../handler-CoJxInw-.js';
2
+ import { a as QueryEngine, ab as ScopeValues, S as ScopePolicy } from '../../types-DgUZNKii.js';
3
+ import { M as MutationClient, W as WriteEvent, E as ExecuteRecord } from '../../handler-DdfaWN_J.js';
4
4
  import '../../query.schema-B-LVNfyX.js';
5
5
  import 'zod';
6
6
  import '@niscorp/prism';
@@ -11,6 +11,7 @@ type VexHonoConfig<E extends Env = Env> = {
11
11
  engine: QueryEngine;
12
12
  entities?: string[];
13
13
  locked?: boolean;
14
+ manageFingerprints?: boolean;
14
15
  getScope?: (c: Context<E>) => Promise<ScopeValues> | ScopeValues;
15
16
  getPolicy?: (c: Context<E>) => Promise<ScopePolicy | undefined> | ScopePolicy | undefined;
16
17
  getPolicyForReach?: (c: Context<E>, reach: string) => Promise<ScopePolicy | undefined> | ScopePolicy | undefined;
@@ -18,6 +19,8 @@ type VexHonoConfig<E extends Env = Env> = {
18
19
  client: MutationClient;
19
20
  policy?: ScopePolicy;
20
21
  onWrite?: (event: WriteEvent) => void;
22
+ checkMovedRows?: boolean;
23
+ answerReadableRows?: boolean;
21
24
  };
22
25
  onExecute?: (record: ExecuteRecord) => void;
23
26
  };
@@ -1,4 +1,4 @@
1
- import { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../chunk-W5MYFJKT.js';
1
+ import { warnOfOpenManagement, handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../chunk-F7OXXJIH.js';
2
2
  import '../../chunk-XTOK7YOR.js';
3
3
  import '../../chunk-UPQMKAAX.js';
4
4
  import { Hono } from 'hono';
@@ -20,6 +20,7 @@ var fingerprintFromBody = (body) => {
20
20
  var NOT_JSON = { error: "invalid_request", message: "Body must be JSON" };
21
21
  var vex = (config) => {
22
22
  const app = new Hono();
23
+ warnOfOpenManagement(config);
23
24
  const jsonBodyOf = async (c) => {
24
25
  try {
25
26
  const body = await c.req.json();
@@ -43,7 +44,9 @@ var vex = (config) => {
43
44
  mutations: {
44
45
  client: config.mutations.client,
45
46
  policy: mutationPolicy,
46
- ...config.mutations.onWrite !== void 0 ? { onWrite: config.mutations.onWrite } : {}
47
+ ...config.mutations.onWrite !== void 0 ? { onWrite: config.mutations.onWrite } : {},
48
+ ...config.mutations.checkMovedRows !== void 0 ? { checkMovedRows: config.mutations.checkMovedRows } : {},
49
+ ...config.mutations.answerReadableRows === true ? { answerReadableRows: true } : {}
47
50
  }
48
51
  } : {}
49
52
  };
@@ -51,7 +54,8 @@ var vex = (config) => {
51
54
  const handlerConfig = {
52
55
  engine: config.engine,
53
56
  entities: config.entities,
54
- ...config.locked === true ? { locked: true } : {}
57
+ ...config.locked === true ? { locked: true } : {},
58
+ ...config.manageFingerprints === false ? { manageFingerprints: false } : {}
55
59
  };
56
60
  app.get("/", async (c) => c.json(await handleDiscovery(await requestConfig(c))));
57
61
  app.post("/", async (c) => {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/adapters/hono/index.ts"],"names":[],"mappings":";;;;;AAYO,IAAM,YAAA,GAAe;AAE5B,IAAM,MAAA,GAAS,CAAC,GAAA,KAAsC;AACpD,EAAA,IAAI,GAAA,KAAQ,QAAQ,OAAO,GAAA,KAAQ,YAAY,EAAE,YAAA,IAAgB,MAAM,OAAO,MAAA;AAC9E,EAAA,MAAM,IAAA,GAAgB,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,YAAY,CAAA;AACnD,EAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,OAAO,IAAA,KAAS,QAAA,IAAY,EAAE,QAAA,IAAY,IAAA,CAAA,IAAS,EAAE,UAAA,IAAc,IAAA,CAAA,EAAO,OAAO,MAAA;AACtG,EAAA,MAAM,EAAE,MAAA,EAAQ,QAAA,EAAS,GAAI,IAAA;AAC7B,EAAA,IAAI,EAAE,MAAA,YAAkB,WAAA,CAAA,IAAgB,OAAO,QAAA,KAAa,YAAY,OAAO,MAAA;AAC/E,EAAA,OAAO,EAAE,MAAA,EAAQ,QAAA,EAAU,CAAC,QAAA,KA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AM,OAAO,MAAa,CAAA;AAAA,EACjD,CAAC,CAAA;AAED,EAAA,GAAA,CAAI,MAAA,CAAO,GAAA,EAAK,OAAO,CAAA,KAAM;AAC3B,IAAA,MAAM,IAAA,GAAO,MAAM,UAAA,CAAW,CAAC,CAAA;AAC/B,IAAA,IAAI,CAAC,IAAA,CAAK,MAAA,SAAe,CAAA,CAAE,IAAA,CAAK,UAAU,GAAG,CAAA;AAC7C,IAAA,MAAM,WAAA,GAAc,mBAAA,CAAoB,IAAA,CAAK,IAAI,CAAA;AACjD,IAAA,IAAI,gBAAgB,MAAA,EAAW;AAC7B,MAAA,OAAO,CAAA,CAAE,KAAK,EAAE,KAAA,EAAO,mBAAmB,OAAA,EAAS,mCAAA,IAAuC,GAAG,CAAA;AAAA,IAC/F;AACA,IAAA,MAAM,MAAA,GAAS,MAAM,uBAAA,CAAwB,aAAA,EAAe,WAAW,CAAA;AACvE,IAAA,OAAO,CAAA,CAAE,IAAA,CAAK,MAAA,CAAO,IAAA,EAAM,OAAO,MAAa,CAAA;AAAA,EACjD,CAAC,CAAA;AAED,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["import { Hono } from 'hono';\nimport type { Context, Env } from 'hono';\nimport type { QueryEngine } from '../../types.js';\nimport type { ScopePolicy, ScopeValues } from '../../scope/scope.types.js';\nimport type { MutationClient } from '../../mutations/engine.js';\nimport { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../handler.js';\nimport type { WriteEvent, ExecuteRecord, VexLive } from '../../handler.js';\nimport type { QueryResponse } from '../../schemas/request.schema.js';\n\n// A request made in-process may carry a follower under this key in hono's env\n// (`app.request(url, init, env)`). One off the network cannot: its env is the\n// runtime's, which nothing a client sends reaches.\nexport const VEX_LIVE_ENV = 'vexLive';\n\nconst liveOf = (env: unknown): VexLive | undefined => {\n if (env === null || typeof env !== 'object' || !(VEX_LIVE_ENV in env)) return undefined;\n const live: unknown = Reflect.get(env, VEX_LIVE_ENV);\n if (live === null || typeof live !== 'object' || !('signal' in live) || !('onChange' in live)) return undefined;\n const { signal, onChange } = live;\n if (!(signal instanceof AbortSignal) || typeof onChange !== 'function') return undefined;\n return { signal, onChange: (response: QueryResponse) => void Reflect.apply(onChange, undefined, [response]) };\n};\n\nexport type VexHonoConfig<E extends Env = Env> = {\n engine: QueryEngine;\n entities?: string[];\n locked?: boolean;\n getScope?: (c: Context<E>) => Promise<ScopeValues> | ScopeValues;\n getPolicy?: (c: Context<E>) => Promise<ScopePolicy | undefined> | ScopePolicy | undefined;\n getPolicyForReach?: (c: Context<E>, reach: string) => Promise<ScopePolicy | undefined> | ScopePolicy | undefined;\n mutations?: {\n client: MutationClient;\n policy?: ScopePolicy;\n onWrite?: (event: WriteEvent) => void;\n };\n onExecute?: (record: ExecuteRecord) => void;\n};\n\n// A fingerprint may contain '/' (a named slot such as \"deals/table\"), so it\n// travels in the request body, not the path.\nconst fingerprintFromBody = (body: unknown): string | undefined => {\n if (body === null || typeof body !== 'object') return undefined;\n const fp = (body as Record<string, unknown>)['fingerprint'];\n return typeof fp === 'string' && fp.length > 0 ? fp : undefined;\n};\n\nconst NOT_JSON = { error: 'invalid_request', message: 'Body must be JSON' };\n\nexport const vex = <E extends Env = Env>(config: VexHonoConfig<E>): Hono<E> => {\n const app = new Hono<E>();\n // Read through hono's own `c.req.json()`, which shares hono's body cache with\n // a host middleware that read the body first.\n const jsonBodyOf = async (c: Context<E>): Promise<{ parsed: true; body: unknown } | { parsed: false }> => {\n try {\n const body: unknown = await c.req.json();\n return { parsed: true, body };\n } catch (err) {\n if (err instanceof SyntaxError) return { parsed: false };\n throw err;\n }\n };\n const requestConfig = async (c: Context<E>) => {\n const policy = config.getPolicy ? await config.getPolicy(c) : undefined;\n const mutationPolicy = policy ?? config.mutations?.policy;\n return {\n engine: config.engine,\n entities: config.entities,\n ...(config.locked === true ? { locked: true } : {}),\n ...(policy !== undefined ? { scopePolicy: policy } : {}),\n ...(config.getPolicyForReach !== undefined\n ? { policyForReach: (reach: string) => config.getPolicyForReach?.(c, reach) }\n : {}),\n ...(config.onExecute !== undefined ? { onExecute: config.onExecute } : {}),\n ...(config.mutations !== undefined && mutationPolicy !== undefined\n ? {\n mutations: {\n client: config.mutations.client,\n policy: mutationPolicy,\n ...(config.mutations.onWrite !== undefined ? { onWrite: config.mutations.onWrite } : {}),\n },\n }\n : {}),\n };\n };\n // Fingerprint management is an operator's surface, not a principal's: it\n // carries no per-request policy.\n const handlerConfig = {\n engine: config.engine,\n entities: config.entities,\n ...(config.locked === true ? { locked: true } : {}),\n };\n\n app.get('/', async (c) => c.json(await handleDiscovery(await requestConfig(c))));\n\n app.post('/', async (c) => {\n const scope = config.getScope ? await config.getScope(c) : {};\n const read = await jsonBodyOf(c);\n if (!read.parsed) return c.json(NOT_JSON, 400);\n const result = await handleQuery(await requestConfig(c), read.body, scope, liveOf(c.env));\n return c.json(result.body, result.status as 200);\n });\n\n app.patch('/', async (c) => {\n const read = await jsonBodyOf(c);\n if (!read.parsed) return c.json(NOT_JSON, 400);\n const body = read.body;\n const fingerprint = fingerprintFromBody(body);\n if (fingerprint === undefined) {\n return c.json({ error: 'invalid_request', message: 'Body must include { fingerprint }' }, 400);\n }\n const wanted = (body as Record<string, unknown>)['protected'];\n const result = await handleFingerprintPatch(handlerConfig, fingerprint, {\n ...(typeof wanted === 'boolean' ? { protected: wanted } : {}),\n });\n return c.json(result.body, result.status as 200);\n });\n\n app.delete('/', async (c) => {\n const read = await jsonBodyOf(c);\n if (!read.parsed) return c.json(NOT_JSON, 400);\n const fingerprint = fingerprintFromBody(read.body);\n if (fingerprint === undefined) {\n return c.json({ error: 'invalid_request', message: 'Body must include { fingerprint }' }, 400);\n }\n const result = await handleFingerprintDelete(handlerConfig, fingerprint);\n return c.json(result.body, result.status as 200);\n });\n\n return app;\n};\n"]}
1
+ {"version":3,"sources":["../../../src/adapters/hono/index.ts"],"names":[],"mappings":";;;;;AAYO,IAAM,YAAA,GAAe;AAE5B,IAAM,MAAA,G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M,WAAA,GAAc,mBAAA,CAAoB,IAAA,CAAK,IAAI,CAAA;AACjD,IAAA,IAAI,gBAAgB,MAAA,EAAW;AAC7B,MAAA,OAAO,CAAA,CAAE,KAAK,EAAE,KAAA,EAAO,mBAAmB,OAAA,EAAS,mCAAA,IAAuC,GAAG,CAAA;AAAA,IAC/F;AACA,IAAA,MAAM,MAAA,GAAS,MAAM,uBAAA,CAAwB,aAAA,EAAe,WAAW,CAAA;AACvE,IAAA,OAAO,CAAA,CAAE,IAAA,CAAK,MAAA,CAAO,IAAA,EAAM,OAAO,MAAa,CAAA;AAAA,EACjD,CAAC,CAAA;AAED,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["import { Hono } from 'hono';\nimport type { Context, Env } from 'hono';\nimport type { QueryEngine } from '../../types.js';\nimport type { ScopePolicy, ScopeValues } from '../../scope/scope.types.js';\nimport type { MutationClient } from '../../mutations/engine.js';\nimport { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete, warnOfOpenManagement } from '../../handler.js';\nimport type { WriteEvent, ExecuteRecord, VexLive } from '../../handler.js';\nimport type { QueryResponse } from '../../schemas/request.schema.js';\n\n// A request made in-process may carry a follower under this key in hono's env\n// (`app.request(url, init, env)`). One off the network cannot: its env is the\n// runtime's, which nothing a client sends reaches.\nexport const VEX_LIVE_ENV = 'vexLive';\n\nconst liveOf = (env: unknown): VexLive | undefined => {\n if (env === null || typeof env !== 'object' || !(VEX_LIVE_ENV in env)) return undefined;\n const live: unknown = Reflect.get(env, VEX_LIVE_ENV);\n if (live === null || typeof live !== 'object' || !('signal' in live) || !('onChange' in live)) return undefined;\n const { signal, onChange } = live;\n if (!(signal instanceof AbortSignal) || typeof onChange !== 'function') return undefined;\n return { signal, onChange: (response: QueryResponse) => void Reflect.apply(onChange, undefined, [response]) };\n};\n\nexport type VexHonoConfig<E extends Env = Env> = {\n engine: QueryEngine;\n entities?: string[];\n locked?: boolean;\n manageFingerprints?: boolean;\n getScope?: (c: Context<E>) => Promise<ScopeValues> | ScopeValues;\n getPolicy?: (c: Context<E>) => Promise<ScopePolicy | undefined> | ScopePolicy | undefined;\n getPolicyForReach?: (c: Context<E>, reach: string) => Promise<ScopePolicy | undefined> | ScopePolicy | undefined;\n mutations?: {\n client: MutationClient;\n policy?: ScopePolicy;\n onWrite?: (event: WriteEvent) => void;\n checkMovedRows?: boolean;\n answerReadableRows?: boolean;\n };\n onExecute?: (record: ExecuteRecord) => void;\n};\n\n// A fingerprint may contain '/' (a named slot such as \"deals/table\"), so it\n// travels in the request body, not the path.\nconst fingerprintFromBody = (body: unknown): string | undefined => {\n if (body === null || typeof body !== 'object') return undefined;\n const fp = (body as Record<string, unknown>)['fingerprint'];\n return typeof fp === 'string' && fp.length > 0 ? fp : undefined;\n};\n\nconst NOT_JSON = { error: 'invalid_request', message: 'Body must be JSON' };\n\nexport const vex = <E extends Env = Env>(config: VexHonoConfig<E>): Hono<E> => {\n const app = new Hono<E>();\n warnOfOpenManagement(config);\n // Read through hono's own `c.req.json()`, which shares hono's body cache with\n // a host middleware that read the body first.\n const jsonBodyOf = async (c: Context<E>): Promise<{ parsed: true; body: unknown } | { parsed: false }> => {\n try {\n const body: unknown = await c.req.json();\n return { parsed: true, body };\n } catch (err) {\n if (err instanceof SyntaxError) return { parsed: false };\n throw err;\n }\n };\n const requestConfig = async (c: Context<E>) => {\n const policy = config.getPolicy ? await config.getPolicy(c) : undefined;\n const mutationPolicy = policy ?? config.mutations?.policy;\n return {\n engine: config.engine,\n entities: config.entities,\n ...(config.locked === true ? { locked: true } : {}),\n ...(policy !== undefined ? { scopePolicy: policy } : {}),\n ...(config.getPolicyForReach !== undefined\n ? { policyForReach: (reach: string) => config.getPolicyForReach?.(c, reach) }\n : {}),\n ...(config.onExecute !== undefined ? { onExecute: config.onExecute } : {}),\n ...(config.mutations !== undefined && mutationPolicy !== undefined\n ? {\n mutations: {\n client: config.mutations.client,\n policy: mutationPolicy,\n ...(config.mutations.onWrite !== undefined ? { onWrite: config.mutations.onWrite } : {}),\n ...(config.mutations.checkMovedRows !== undefined ? { checkMovedRows: config.mutations.checkMovedRows } : {}),\n ...(config.mutations.answerReadableRows === true ? { answerReadableRows: true } : {}),\n },\n }\n : {}),\n };\n };\n // Fingerprint management is an operator's surface, not a principal's: it\n // carries no per-request policy.\n const handlerConfig = {\n engine: config.engine,\n entities: config.entities,\n ...(config.locked === true ? { locked: true } : {}),\n ...(config.manageFingerprints === false ? { manageFingerprints: false } : {}),\n };\n\n app.get('/', async (c) => c.json(await handleDiscovery(await requestConfig(c))));\n\n app.post('/', async (c) => {\n const scope = config.getScope ? await config.getScope(c) : {};\n const read = await jsonBodyOf(c);\n if (!read.parsed) return c.json(NOT_JSON, 400);\n const result = await handleQuery(await requestConfig(c), read.body, scope, liveOf(c.env));\n return c.json(result.body, result.status as 200);\n });\n\n app.patch('/', async (c) => {\n const read = await jsonBodyOf(c);\n if (!read.parsed) return c.json(NOT_JSON, 400);\n const body = read.body;\n const fingerprint = fingerprintFromBody(body);\n if (fingerprint === undefined) {\n return c.json({ error: 'invalid_request', message: 'Body must include { fingerprint }' }, 400);\n }\n const wanted = (body as Record<string, unknown>)['protected'];\n const result = await handleFingerprintPatch(handlerConfig, fingerprint, {\n ...(typeof wanted === 'boolean' ? { protected: wanted } : {}),\n });\n return c.json(result.body, result.status as 200);\n });\n\n app.delete('/', async (c) => {\n const read = await jsonBodyOf(c);\n if (!read.parsed) return c.json(NOT_JSON, 400);\n const fingerprint = fingerprintFromBody(read.body);\n if (fingerprint === undefined) {\n return c.json({ error: 'invalid_request', message: 'Body must include { fingerprint }' }, 400);\n }\n const result = await handleFingerprintDelete(handlerConfig, fingerprint);\n return c.json(result.body, result.status as 200);\n });\n\n return app;\n};\n"]}
@@ -165,16 +165,16 @@ var QuerySchema = zod.z.lazy(
165
165
 
166
166
  // src/agent/tools.ts
167
167
  var GetSchemaInputSchema = zod.z.object({
168
- entities: zod.z.array(zod.z.string()).optional().describe("Filter to specific entity names")
168
+ entities: zod.z.array(zod.z.string()).nullish().describe("Filter to specific entity names")
169
169
  });
170
170
  var GetSampleRowsInputSchema = zod.z.object({
171
171
  entity: zod.z.string().describe("Entity name to sample rows from"),
172
- limit: zod.z.number().int().positive().max(50).optional().describe("Max rows to return (default: 5)")
172
+ limit: zod.z.number().int().positive().max(50).nullish().describe("Max rows to return (default: 5)")
173
173
  });
174
174
  var GetDistinctValuesInputSchema = zod.z.object({
175
175
  entity: zod.z.string().describe("Entity name"),
176
176
  field: zod.z.string().describe("Field name within the entity"),
177
- limit: zod.z.number().int().positive().max(200).optional().describe("Max distinct values to return (default: 20)")
177
+ limit: zod.z.number().int().positive().max(200).nullish().describe("Max distinct values to return (default: 20)")
178
178
  });
179
179
  var DescribeFieldInputSchema = zod.z.object({
180
180
  entity: zod.z.string().describe("Entity name"),
@@ -183,14 +183,14 @@ var DescribeFieldInputSchema = zod.z.object({
183
183
  var inSpec = (what) => `${what} \u2014 written as the DSL spec (OUTPUT SCHEMA) says.`;
184
184
  var TestQueryInputSchema = zod.z.object({
185
185
  from: zod.z.array(zod.z.unknown()).describe(inSpec("The data sources: entity names (or subqueries); every entity the query uses is listed here")),
186
- fields: zod.z.array(zod.z.unknown()).optional().describe(inSpec("Raw columns to select, `entity.field` or `{ field, as }`; omit for an aggregate-only query")),
187
- filter: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe(inSpec("Filter conditions")),
188
- compute: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe(inSpec("Computed fields: output alias \u2192 expression")),
189
- aggregate: zod.z.record(zod.z.string(), zod.z.unknown()).optional().describe(inSpec("Aggregates (count, sum, avg, \u2026): output alias \u2192 function")),
190
- groupBy: zod.z.array(zod.z.unknown()).optional().describe(inSpec("Fields to group by, for aggregates")),
191
- sort: zod.z.array(zod.z.unknown()).optional().describe(inSpec("Sort order")),
192
- limit: zod.z.number().optional().describe("Maximum rows to return."),
193
- distinct: zod.z.boolean().optional().describe("Eliminate duplicate rows.")
186
+ fields: zod.z.array(zod.z.unknown()).nullish().describe(inSpec("Raw columns to select, `entity.field` or `{ field, as }`; omit for an aggregate-only query")),
187
+ filter: zod.z.record(zod.z.string(), zod.z.unknown()).nullish().describe(inSpec("Filter conditions")),
188
+ compute: zod.z.record(zod.z.string(), zod.z.unknown()).nullish().describe(inSpec("Computed fields: output alias \u2192 expression")),
189
+ aggregate: zod.z.record(zod.z.string(), zod.z.unknown()).nullish().describe(inSpec("Aggregates (count, sum, avg, \u2026): output alias \u2192 function")),
190
+ groupBy: zod.z.array(zod.z.unknown()).nullish().describe(inSpec("Fields to group by, for aggregates")),
191
+ sort: zod.z.array(zod.z.unknown()).nullish().describe(inSpec("Sort order")),
192
+ limit: zod.z.number().nullish().describe("Maximum rows to return."),
193
+ distinct: zod.z.boolean().nullish().describe("Eliminate duplicate rows.")
194
194
  }).catchall(zod.z.unknown()).describe("Your draft DSL query \u2014 the query object itself, NOT wrapped in any field.");
195
195
  var CannotSatisfyInputSchema = zod.z.object({
196
196
  reason: zod.z.string().describe("Why the request cannot be satisfied")
@@ -301,7 +301,7 @@ var createQueryTools = (deps) => {
301
301
  input: TestQueryInputSchema,
302
302
  execute: async (input) => {
303
303
  if (strata.exceedsDepth(input)) return { rows: [], sql: "", warnings: [], errors: [strata.depthRefusal()] };
304
- const parseResult = QuerySchema.safeParse(input);
304
+ const parseResult = QuerySchema.safeParse(Object.fromEntries(Object.entries(input).filter(([, value]) => value !== null)));
305
305
  if (!parseResult.success) {
306
306
  const validationErrors = parseResult.error.issues.map(
307
307
  (issue) => `${issue.path.join(".")}: ${issue.message}`
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/errors.ts","../../src/schemas/value.schema.ts","../../src/schemas/identifier.schema.ts","../../src/schemas/filter.schema.ts","../../src/schemas/compute.schema.ts","../../src/schemas/aggregate.schema.ts","../../src/schemas/query.schema.ts","../../src/agent/tools.ts","../../src/agent/compact.ts","../../src/agent/declared.ts","../../src/agent/query.agent.ts","../../src/agent/index.ts"],"names":["z","defineTool","exceedsDepth","depthRefusal","isRecord","defineAgent","stepCount","outputRetries","repeatedCalls","compile","execute","attempt","mappingAgent"],"mappings":";;;;;;;;;AAKA,IAAM,SAAA,mBAAY,MAAA,CAAO,GAAA,CAAI,uBAAuB,CAAA;AAE7C,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA,EACzB,IAAA;AAAA,EACA,OAAA;AAAA,EAET,WAAA,CAAY,IAAA,EAAsB,OAAA,EAAiB,OAAA,EAAmC;AACpF,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,UAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AACF,CAAA;AAEA,MAAA,CAAO,eAAe,QAAA,CAAS,SAAA,EAAW,WAAW,EAAE,KAAA,EAAO,MAAM,CAAA;ACjB7D,IAAM,gBAAA,GAAmBA,MAC7B,MAAA,CAAO;AAAA,EACN,QAAA,EAAUA,KAAA,CAAE,MAAA,EAAO,CAAE,SAAS,8CAA8C;AAC9E,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,8CAA8C,CAAA;AAEnD,IAAM,cAAA,GAAiBA,MAC3B,MAAA,CAAO;AAAA,EACN,MAAA,EAAQA,KAAA,CAAE,MAAA,EAAO,CAAE,SAAS,gDAAgD;AAC9E,CAAC,CAAA,CACA,MAAA,EAAO,CACP,QAAA,CAAS,6DAA6D,CAAA;AAElE,IAAM,kBAAA,GAAqBA,MAC/B,KAAA,CAAM;AAAA,EACLA,KAAA,CAAE,MAAA,EAAO,CAAE,QAAA,CAAS,wDAAwD,CAAA;AAAA,EAC5EA,KAAA,CAAE,MAAA,EAAO,CAAE,QAAA,CAAS,kBAAkB,CAAA;AAAA,EACtCA,KAAA,CAAE,OAAA,EAAQ,CAAE,QAAA,CAAS,mBAAmB,CAAA;AAAA,EACxCA,KAAA,CAAE,IAA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AAA,CAAS,cAAA,EAAgB,CAAA,wDAAA,EAA2D,MAAA,IAAU,iBAAiB,CAAA,CAAE,CAAA;AAAA,EAC7H,CAAA;AACF","file":"index.cjs","sourcesContent":["import type { QueryErrorCode } from './schemas/request.schema.js';\n\n// The CommonJS build gives each entry point its own copy of this class, and an\n// app can load the ESM and CommonJS builds side by side, so `instanceof` fails\n// across copies. Every copy marks its prototype under this process-wide key.\nconst VEX_ERROR = Symbol.for('@niscorp/vex:VexError');\n\nexport class VexError extends Error {\n readonly code: QueryErrorCode;\n readonly details?: Record<string, unknown>;\n\n constructor(code: QueryErrorCode, message: string, details?: Record<string, unknown>) {\n super(message);\n this.name = 'VexError';\n this.code = code;\n this.details = details;\n }\n}\n\nObject.defineProperty(VexError.prototype, VEX_ERROR, { value: true });\n\nexport const isVexError = (err: unknown): err is VexError =>\n err instanceof VexError || (err instanceof Error && Reflect.get(err, VEX_ERROR) === true);\n","import { z } from 'zod';\n\nexport const ContextRefSchema = z\n .object({\n $context: z.string().describe('Key to look up in the request context object'),\n })\n .strict()\n .describe('Reference to a caller-provided context value');\n\nexport const ScopeRefSchema = z\n .object({\n $scope: z.string().describe('Key to look up in the server-side scope values'),\n })\n .strict()\n .describe('Reference to a server-injected scope value (access control)');\n\nexport const FieldOrValueSchema = z\n .union([\n z.string().describe('A field path (entity.field format) or a literal string'),\n z.number().describe('A literal number'),\n z.boolean().describe('A literal boolean'),\n z.null().describe('A literal null'),\n ContextRefSchema,\n ScopeRefSchema,\n ])\n .describe('A field path, literal value, or dynamic reference');\n\nexport type ContextRef = z.infer<typeof ContextRefSchema>;\nexport type ScopeRef = z.infer<typeof ScopeRefSchema>;\nexport type FieldOrValue = z.infer<typeof FieldOrValueSchema>;\n","import { z } from 'zod';\n\n// A name is the only authored text that reaches SQL as text (values bind as\n// parameters or are quoted as literals), so it is held to this grammar. In a\n// value position, `isFieldPathShape` decides whether a string is a column or\n// a literal.\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]*\\.[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport const isIdentifier = (value: string): boolean => IDENTIFIER.test(value);\n\nexport const isFieldPathShape = (value: unknown): value is string => typeof value === 'string' && FIELD_PATH.test(value);\n\nexport const IdentifierSchema = z\n .string()\n .regex(IDENTIFIER, 'A name is letters, digits and underscores, not starting with a digit');\n\nexport const FieldPathSchema = z\n .string()\n .regex(FIELD_PATH, 'A field path is entity.field — each part letters, digits and underscores, not starting with a digit');\n","import { z } from 'zod';\nimport { ContextRefSchema, ScopeRefSchema, FieldOrValueSchema } from './value.schema.js';\nimport { FieldPathSchema } from './identifier.schema.js';\nimport type { ContextRef, ScopeRef, FieldOrValue } from './value.schema.js';\n\nexport type ExistsQuery = {\n from: string[];\n filter?: Filter;\n};\n\nexport type Filter =\n | { exists: ExistsQuery }\n | { eq: [FieldOrValue, FieldOrValue] }\n | { neq: [FieldOrValue, FieldOrValue] }\n | { gt: [FieldOrValue, FieldOrValue] }\n | { gte: [FieldOrValue, FieldOrValue] }\n | { lt: [FieldOrValue, FieldOrValue] }\n | { lte: [FieldOrValue, FieldOrValue] }\n | { in: [string, FieldOrValue[] | ContextRef | ScopeRef] }\n | { notIn: [string, FieldOrValue[] | ContextRef | ScopeRef] }\n | { like: [string, FieldOrValue] }\n | { ilike: [string, FieldOrValue] }\n | { isNull: string }\n | { isNotNull: string }\n | { and: Filter[] }\n | { or: Filter[] }\n | { not: Filter }\n | { semantic: { field: string; query: ContextRef | ScopeRef; minScore?: number } }\n | { fuzzy: { field: string; query: ContextRef | ScopeRef; maxDistance?: number } }\n | { optional: { key: string | string[]; then: Filter } };\n\nconst comparisonPair = z\n .tuple([FieldOrValueSchema, FieldOrValueSchema])\n .describe('[left, right] — both can be field paths, literals, or references');\n\nconst fieldString = FieldPathSchema.describe('Field path in entity.field format');\n\nconst collectionTarget = z\n .union([\n z.array(FieldOrValueSchema).min(1).describe('Array of literal values or references'),\n ContextRefSchema,\n ScopeRefSchema,\n ])\n .describe('A set of values or a reference that resolves to an array');\n\nconst ExistsSchema: z.ZodType<ExistsQuery> = z.lazy(() =>\n z\n .object({\n from: z.array(z.string()).min(1).describe('Entities the subquery reads. Joined by foreign key like any other from.'),\n filter: FilterSchema.optional().describe('The correlation, and any extra condition. Reference the outer query by its own entity path: { eq: [\"<inner>.<fk>\", \"<outer>.id\"] }.'),\n })\n .strict(),\n);\n\nexport const FilterSchema: z.ZodType<Filter> = z.lazy(() =>\n z.union([\n z.object({ exists: ExistsSchema }).strict().describe('EXISTS: true when the subquery matches at least one row. Wrap in `not` for NOT EXISTS.'),\n z.object({ eq: comparisonPair }).strict().describe('Equals: tests equality between two values'),\n z.object({ neq: comparisonPair }).strict().describe('Not equals'),\n z.object({ gt: comparisonPair }).strict().describe('Greater than'),\n z.object({ gte: comparisonPair }).strict().describe('Greater than or equal'),\n z.object({ lt: comparisonPair }).strict().describe('Less than'),\n z.object({ lte: comparisonPair }).strict().describe('Less than or equal'),\n z.object({ in: z.tuple([fieldString, collectionTarget]) }).strict().describe('Field value is in a set'),\n z.object({ notIn: z.tuple([fieldString, collectionTarget]) }).strict().describe('Field value is not in a set'),\n z.object({ like: z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe('Case-sensitive LIKE pattern match (use % as wildcard)'),\n z.object({ ilike: z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe('Case-insensitive ILIKE pattern match (use % as wildcard)'),\n z.object({ isNull: fieldString }).strict().describe('Field value is NULL'),\n z.object({ isNotNull: fieldString }).strict().describe('Field value is NOT NULL'),\n z.object({ and: z.array(FilterSchema).min(2) }).strict().describe('Logical AND: all conditions must be true'),\n z.object({ or: z.array(FilterSchema).min(2) }).strict().describe('Logical OR: at least one condition must be true'),\n z.object({ not: FilterSchema }).strict().describe('Logical NOT: negates the condition'),\n z.object({\n semantic: z.object({\n field: FieldPathSchema.describe('Vector column field path (entity.field)'),\n query: z.union([ContextRefSchema, ScopeRefSchema]).describe('Text to embed and compare'),\n minScore: z.number().min(0).max(1).optional().describe('Minimum cosine similarity (0–1)'),\n }).strict(),\n }).strict().describe('Semantic vector similarity search'),\n z.object({\n fuzzy: z.object({\n field: FieldPathSchema.describe('String field path'),\n query: z.union([ContextRefSchema, ScopeRefSchema]).describe('Text to fuzzy-match'),\n maxDistance: z.number().int().nonnegative().optional().describe('Maximum Levenshtein edit distance'),\n }).strict(),\n }).strict().describe('Fuzzy string match'),\n z.object({\n optional: z.object({\n key: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('The context key this condition depends on, or EVERY key it depends on. A condition referencing two keys must name both — gating on one leaves the other conditionally required, which surfaces as an empty result rather than as a condition that did not apply.'),\n // Bare, never `.describe()`d: that call clones the schema, and zod's\n // to-json-schema detects recursion by instance identity, so a clone\n // expands the filter union into itself until the stack overflows.\n then: FilterSchema,\n }).strict(),\n }).strict().describe(\n 'A condition the caller turns on by supplying context keys. When any named key is absent the condition is REMOVED from the query before it compiles — it does not match everything, it is not there. Absent means missing, undefined or null; \"\" is a value and keeps the condition. Direction follows position: under `and` supplying the key NARROWS, under `or` it WIDENS. Either way an absent key reads exactly as if the condition had never been written, and scope is injected afterwards regardless. Reads only: a mutation may not contain one, and neither may the inside of an `exists` (its correlation must be unconditional).',\n ),\n ]),\n);\n","import { z } from 'zod';\nimport { FieldOrValueSchema } from './value.schema.js';\nimport { FilterSchema } from './filter.schema.js';\n\nconst CaseWhenSchema = z\n .object({\n condition: FilterSchema,\n then: FieldOrValueSchema.describe('Value when condition is true'),\n })\n .strict();\n\nexport const ComputeExpressionSchema = z\n .union([\n z.object({ add: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Addition: a + b'),\n z.object({ subtract: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Subtraction: a - b'),\n z.object({ multiply: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Multiplication: a * b'),\n z.object({ divide: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Division: a / b'),\n z.object({ concat: z.array(FieldOrValueSchema).min(2) }).strict().describe('String concatenation'),\n z.object({ coalesce: z.array(FieldOrValueSchema).min(2) }).strict().describe('Returns first non-null value'),\n z.object({\n case: z\n .object({\n when: z.array(CaseWhenSchema).min(1).describe('Condition/result pairs evaluated in order'),\n else: FieldOrValueSchema.describe('Default value when no condition matches'),\n })\n .strict(),\n }).strict().describe('CASE WHEN conditional expression'),\n ])\n .describe('Computed expression: arithmetic, string, or conditional');\n\nexport type ComputeExpression = z.infer<typeof ComputeExpressionSchema>;\n","import { z } from 'zod';\nimport { ComputeExpressionSchema } from './compute.schema.js';\nimport { FieldPathSchema } from './identifier.schema.js';\n\nconst fieldPath = FieldPathSchema.describe('Field path in entity.field format');\n\nconst fieldOrExpr = z.union([fieldPath, ComputeExpressionSchema]).describe('A field path or a compute expression');\n\nexport const AggregateExpressionSchema = z\n .union([\n z.object({ count: z.union([FieldPathSchema, z.literal('*')]).describe('Field path or \"*\" for COUNT(*)') }).strict().describe('COUNT'),\n z.object({ countDistinct: FieldPathSchema.describe('Field path whose distinct non-null values are counted') }).strict().describe('COUNT(DISTINCT field)'),\n z.object({ sum: fieldOrExpr }).strict().describe('SUM'),\n z.object({ avg: fieldOrExpr }).strict().describe('AVG'),\n z.object({ min: fieldOrExpr }).strict().describe('MIN'),\n z.object({ max: fieldOrExpr }).strict().describe('MAX'),\n ])\n .describe('Aggregate function applied to a field or expression');\n\nexport type AggregateExpression = z.infer<typeof AggregateExpressionSchema>;\n","import { z } from 'zod';\nimport { FilterSchema } from './filter.schema.js';\nimport { ComputeExpressionSchema } from './compute.schema.js';\nimport { AggregateExpressionSchema } from './aggregate.schema.js';\nimport { FieldPathSchema, IdentifierSchema } from './identifier.schema.js';\nimport type { Filter } from './filter.schema.js';\nimport type { ComputeExpression } from './compute.schema.js';\nimport type { AggregateExpression } from './aggregate.schema.js';\n\nexport const SortEntrySchema = z\n .object({\n field: z.union([FieldPathSchema, IdentifierSchema]).describe('Field path (entity.field), computed field name, or aggregate alias'),\n dir: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n })\n .strict()\n .describe('Sort specification');\n\nexport type SortEntry = z.infer<typeof SortEntrySchema>;\n\nexport type Source = string | { as: string; query: Query };\n\nexport type FieldRef = string | { field: string; as: string };\n\nexport type Query = {\n from: Source[];\n fields?: FieldRef[];\n filter?: Filter;\n compute?: Record<string, ComputeExpression>;\n aggregate?: Record<string, AggregateExpression>;\n groupBy?: string[];\n sort?: SortEntry[];\n limit?: number;\n distinct?: boolean;\n};\n\nconst SubquerySourceSchema = z\n .object({\n as: IdentifierSchema.describe('Alias for subquery results — use as prefix in field paths'),\n query: z.lazy((): z.ZodType<Query> => QuerySchema).describe('A nested query'),\n })\n .strict()\n .describe('Subquery data source: a nested query read as a table under `as`, its columns referenced as `<as>.<field>` anywhere in the outer query. Joined by foreign key like an entity when one links them; otherwise every outer row is paired with every subquery row (a cross join), so a one-row subquery puts its values beside each outer row.');\n\nconst SourceSchema = z\n .union([\n z.string().describe('Entity name from the database schema'),\n SubquerySourceSchema,\n ])\n .describe('Data source: entity name or subquery');\n\nconst FieldRefSchema = z\n .union([\n FieldPathSchema.describe('A column in entity.field format'),\n z\n .object({\n field: FieldPathSchema.describe('A column in entity.field format'),\n as: IdentifierSchema.describe('Output key for this column'),\n })\n .strict()\n .describe('An aliased column: output under `as` instead of the column name'),\n ])\n .describe('A selected field — a bare `entity.field`, or `{ field, as }` to alias the output key');\n\nexport const QuerySchema: z.ZodType<Query> = z.lazy(() =>\n z\n .object({\n from: z.array(SourceSchema).min(1).describe('Data sources — entity names or subqueries. Every entity used anywhere in the query must be listed here. Listed entities are JOINED FOR YOU along their foreign keys — a nullable key as a LEFT JOIN, so a row whose key is empty is kept, with the joined columns null. Never restate a join as a filter comparing the two keys: that throws those rows away.'),\n fields: z.array(FieldRefSchema).optional().describe('Raw columns to select — each `entity.field`, or `{ field, as }` to alias the output key (no SELECT *). Optional: omit it for an aggregate-only query (e.g. a bare COUNT). Do not list compute or aggregate aliases here — those are added automatically.'),\n filter: FilterSchema.optional().describe('Filter conditions'),\n compute: z.record(IdentifierSchema, ComputeExpressionSchema).optional().describe('Computed fields — key is output alias, value is the expression'),\n aggregate: z.record(IdentifierSchema, AggregateExpressionSchema).optional().describe('Aggregate functions — key is output alias, value is the function'),\n groupBy: z.array(FieldPathSchema).optional().describe('Fields to group by for aggregation'),\n sort: z.array(SortEntrySchema).optional().describe('Sort order'),\n limit: z.number().int().positive().optional().describe('Maximum rows to return'),\n distinct: z.boolean().optional().describe('Eliminate duplicate rows'),\n })\n .strict()\n .refine(\n (q) => (q.fields?.length ?? 0) > 0 || Object.keys(q.aggregate ?? {}).length > 0,\n { message: 'A query must select at least one of `fields` or `aggregate`.' },\n ),\n);\n\nexport { SubquerySourceSchema, SourceSchema };\n","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
+ {"version":3,"sources":["../../src/errors.ts","../../src/schemas/value.schema.ts","../../src/schemas/identifier.schema.ts","../../src/schemas/filter.schema.ts","../../src/schemas/compute.schema.ts","../../src/schemas/aggregate.schema.ts","../../src/schemas/query.schema.ts","../../src/agent/tools.ts","../../src/agent/compact.ts","../../src/agent/declared.ts","../../src/agent/query.agent.ts","../../src/agent/index.ts"],"names":["z","defineTool","exceedsDepth","depthRefusal","isRecord","defineAgent","stepCount","outputRetries","repeatedCalls","compile","execute","attempt","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AA,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.cjs","sourcesContent":["import type { QueryErrorCode } from './schemas/request.schema.js';\n\n// The CommonJS build gives each entry point its own copy of this class, and an\n// app can load the ESM and CommonJS builds side by side, so `instanceof` fails\n// across copies. Every copy marks its prototype under this process-wide key.\nconst VEX_ERROR = Symbol.for('@niscorp/vex:VexError');\n\nexport class VexError extends Error {\n readonly code: QueryErrorCode;\n readonly details?: Record<string, unknown>;\n\n constructor(code: QueryErrorCode, message: string, details?: Record<string, unknown>) {\n super(message);\n this.name = 'VexError';\n this.code = code;\n this.details = details;\n }\n}\n\nObject.defineProperty(VexError.prototype, VEX_ERROR, { value: true });\n\nexport const isVexError = (err: unknown): err is VexError =>\n err instanceof VexError || (err instanceof Error && Reflect.get(err, VEX_ERROR) === true);\n","import { z } from 'zod';\n\nexport const ContextRefSchema = z\n .object({\n $context: z.string().describe('Key to look up in the request context object'),\n })\n .strict()\n .describe('Reference to a caller-provided context value');\n\nexport const ScopeRefSchema = z\n .object({\n $scope: z.string().describe('Key to look up in the server-side scope values'),\n })\n .strict()\n .describe('Reference to a server-injected scope value (access control)');\n\nexport const FieldOrValueSchema = z\n .union([\n z.string().describe('A field path (entity.field format) or a literal string'),\n z.number().describe('A literal number'),\n z.boolean().describe('A literal boolean'),\n z.null().describe('A literal null'),\n ContextRefSchema,\n ScopeRefSchema,\n ])\n .describe('A field path, literal value, or dynamic reference');\n\nexport type ContextRef = z.infer<typeof ContextRefSchema>;\nexport type ScopeRef = z.infer<typeof ScopeRefSchema>;\nexport type FieldOrValue = z.infer<typeof FieldOrValueSchema>;\n","import { z } from 'zod';\n\n// A name is the only authored text that reaches SQL as text (values bind as\n// parameters or are quoted as literals), so it is held to this grammar. In a\n// value position, `isFieldPathShape` decides whether a string is a column or\n// a literal.\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst FIELD_PATH = /^[A-Za-z_][A-Za-z0-9_]*\\.[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport const isIdentifier = (value: string): boolean => IDENTIFIER.test(value);\n\nexport const isFieldPathShape = (value: unknown): value is string => typeof value === 'string' && FIELD_PATH.test(value);\n\nexport const IdentifierSchema = z\n .string()\n .regex(IDENTIFIER, 'A name is letters, digits and underscores, not starting with a digit');\n\nexport const FieldPathSchema = z\n .string()\n .regex(FIELD_PATH, 'A field path is entity.field — each part letters, digits and underscores, not starting with a digit');\n","import { z } from 'zod';\nimport { ContextRefSchema, ScopeRefSchema, FieldOrValueSchema } from './value.schema.js';\nimport { FieldPathSchema } from './identifier.schema.js';\nimport type { ContextRef, ScopeRef, FieldOrValue } from './value.schema.js';\n\nexport type ExistsQuery = {\n from: string[];\n filter?: Filter;\n};\n\nexport type Filter =\n | { exists: ExistsQuery }\n | { eq: [FieldOrValue, FieldOrValue] }\n | { neq: [FieldOrValue, FieldOrValue] }\n | { gt: [FieldOrValue, FieldOrValue] }\n | { gte: [FieldOrValue, FieldOrValue] }\n | { lt: [FieldOrValue, FieldOrValue] }\n | { lte: [FieldOrValue, FieldOrValue] }\n | { in: [string, FieldOrValue[] | ContextRef | ScopeRef] }\n | { notIn: [string, FieldOrValue[] | ContextRef | ScopeRef] }\n | { like: [string, FieldOrValue] }\n | { ilike: [string, FieldOrValue] }\n | { isNull: string }\n | { isNotNull: string }\n | { and: Filter[] }\n | { or: Filter[] }\n | { not: Filter }\n | { semantic: { field: string; query: ContextRef | ScopeRef; minScore?: number } }\n | { fuzzy: { field: string; query: ContextRef | ScopeRef; maxDistance?: number } }\n | { optional: { key: string | string[]; then: Filter } };\n\nconst comparisonPair = z\n .tuple([FieldOrValueSchema, FieldOrValueSchema])\n .describe('[left, right] — both can be field paths, literals, or references');\n\nconst fieldString = FieldPathSchema.describe('Field path in entity.field format');\n\nconst collectionTarget = z\n .union([\n z.array(FieldOrValueSchema).min(1).describe('Array of literal values or references'),\n ContextRefSchema,\n ScopeRefSchema,\n ])\n .describe('A set of values or a reference that resolves to an array');\n\nconst ExistsSchema: z.ZodType<ExistsQuery> = z.lazy(() =>\n z\n .object({\n from: z.array(z.string()).min(1).describe('Entities the subquery reads. Joined by foreign key like any other from.'),\n filter: FilterSchema.optional().describe('The correlation, and any extra condition. Reference the outer query by its own entity path: { eq: [\"<inner>.<fk>\", \"<outer>.id\"] }.'),\n })\n .strict(),\n);\n\nexport const FilterSchema: z.ZodType<Filter> = z.lazy(() =>\n z.union([\n z.object({ exists: ExistsSchema }).strict().describe('EXISTS: true when the subquery matches at least one row. Wrap in `not` for NOT EXISTS.'),\n z.object({ eq: comparisonPair }).strict().describe('Equals: tests equality between two values'),\n z.object({ neq: comparisonPair }).strict().describe('Not equals'),\n z.object({ gt: comparisonPair }).strict().describe('Greater than'),\n z.object({ gte: comparisonPair }).strict().describe('Greater than or equal'),\n z.object({ lt: comparisonPair }).strict().describe('Less than'),\n z.object({ lte: comparisonPair }).strict().describe('Less than or equal'),\n z.object({ in: z.tuple([fieldString, collectionTarget]) }).strict().describe('Field value is in a set'),\n z.object({ notIn: z.tuple([fieldString, collectionTarget]) }).strict().describe('Field value is not in a set'),\n z.object({ like: z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe('Case-sensitive LIKE pattern match (use % as wildcard)'),\n z.object({ ilike: z.tuple([fieldString, FieldOrValueSchema]) }).strict().describe('Case-insensitive ILIKE pattern match (use % as wildcard)'),\n z.object({ isNull: fieldString }).strict().describe('Field value is NULL'),\n z.object({ isNotNull: fieldString }).strict().describe('Field value is NOT NULL'),\n z.object({ and: z.array(FilterSchema).min(2) }).strict().describe('Logical AND: all conditions must be true'),\n z.object({ or: z.array(FilterSchema).min(2) }).strict().describe('Logical OR: at least one condition must be true'),\n z.object({ not: FilterSchema }).strict().describe('Logical NOT: negates the condition'),\n z.object({\n semantic: z.object({\n field: FieldPathSchema.describe('Vector column field path (entity.field)'),\n query: z.union([ContextRefSchema, ScopeRefSchema]).describe('Text to embed and compare'),\n minScore: z.number().min(0).max(1).optional().describe('Minimum cosine similarity (0–1)'),\n }).strict(),\n }).strict().describe('Semantic vector similarity search'),\n z.object({\n fuzzy: z.object({\n field: FieldPathSchema.describe('String field path'),\n query: z.union([ContextRefSchema, ScopeRefSchema]).describe('Text to fuzzy-match'),\n maxDistance: z.number().int().nonnegative().optional().describe('Maximum Levenshtein edit distance'),\n }).strict(),\n }).strict().describe('Fuzzy string match'),\n z.object({\n optional: z.object({\n key: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .describe('The context key this condition depends on, or EVERY key it depends on. A condition referencing two keys must name both — gating on one leaves the other conditionally required, which surfaces as an empty result rather than as a condition that did not apply.'),\n // Bare, never `.describe()`d: that call clones the schema, and zod's\n // to-json-schema detects recursion by instance identity, so a clone\n // expands the filter union into itself until the stack overflows.\n then: FilterSchema,\n }).strict(),\n }).strict().describe(\n 'A condition the caller turns on by supplying context keys. When any named key is absent the condition is REMOVED from the query before it compiles — it does not match everything, it is not there. Absent means missing, undefined or null; \"\" is a value and keeps the condition. Direction follows position: under `and` supplying the key NARROWS, under `or` it WIDENS. Either way an absent key reads exactly as if the condition had never been written, and scope is injected afterwards regardless. Reads only: a mutation may not contain one, and neither may the inside of an `exists` (its correlation must be unconditional).',\n ),\n ]),\n);\n","import { z } from 'zod';\nimport { FieldOrValueSchema } from './value.schema.js';\nimport { FilterSchema } from './filter.schema.js';\n\nconst CaseWhenSchema = z\n .object({\n condition: FilterSchema,\n then: FieldOrValueSchema.describe('Value when condition is true'),\n })\n .strict();\n\nexport const ComputeExpressionSchema = z\n .union([\n z.object({ add: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Addition: a + b'),\n z.object({ subtract: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Subtraction: a - b'),\n z.object({ multiply: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Multiplication: a * b'),\n z.object({ divide: z.tuple([FieldOrValueSchema, FieldOrValueSchema]) }).strict().describe('Division: a / b'),\n z.object({ concat: z.array(FieldOrValueSchema).min(2) }).strict().describe('String concatenation'),\n z.object({ coalesce: z.array(FieldOrValueSchema).min(2) }).strict().describe('Returns first non-null value'),\n z.object({\n case: z\n .object({\n when: z.array(CaseWhenSchema).min(1).describe('Condition/result pairs evaluated in order'),\n else: FieldOrValueSchema.describe('Default value when no condition matches'),\n })\n .strict(),\n }).strict().describe('CASE WHEN conditional expression'),\n ])\n .describe('Computed expression: arithmetic, string, or conditional');\n\nexport type ComputeExpression = z.infer<typeof ComputeExpressionSchema>;\n","import { z } from 'zod';\nimport { ComputeExpressionSchema } from './compute.schema.js';\nimport { FieldPathSchema } from './identifier.schema.js';\n\nconst fieldPath = FieldPathSchema.describe('Field path in entity.field format');\n\nconst fieldOrExpr = z.union([fieldPath, ComputeExpressionSchema]).describe('A field path or a compute expression');\n\nexport const AggregateExpressionSchema = z\n .union([\n z.object({ count: z.union([FieldPathSchema, z.literal('*')]).describe('Field path or \"*\" for COUNT(*)') }).strict().describe('COUNT'),\n z.object({ countDistinct: FieldPathSchema.describe('Field path whose distinct non-null values are counted') }).strict().describe('COUNT(DISTINCT field)'),\n z.object({ sum: fieldOrExpr }).strict().describe('SUM'),\n z.object({ avg: fieldOrExpr }).strict().describe('AVG'),\n z.object({ min: fieldOrExpr }).strict().describe('MIN'),\n z.object({ max: fieldOrExpr }).strict().describe('MAX'),\n ])\n .describe('Aggregate function applied to a field or expression');\n\nexport type AggregateExpression = z.infer<typeof AggregateExpressionSchema>;\n","import { z } from 'zod';\nimport { FilterSchema } from './filter.schema.js';\nimport { ComputeExpressionSchema } from './compute.schema.js';\nimport { AggregateExpressionSchema } from './aggregate.schema.js';\nimport { FieldPathSchema, IdentifierSchema } from './identifier.schema.js';\nimport type { Filter } from './filter.schema.js';\nimport type { ComputeExpression } from './compute.schema.js';\nimport type { AggregateExpression } from './aggregate.schema.js';\n\nexport const SortEntrySchema = z\n .object({\n field: z.union([FieldPathSchema, IdentifierSchema]).describe('Field path (entity.field), computed field name, or aggregate alias'),\n dir: z.enum(['asc', 'desc']).default('asc').describe('Sort direction'),\n })\n .strict()\n .describe('Sort specification');\n\nexport type SortEntry = z.infer<typeof SortEntrySchema>;\n\nexport type Source = string | { as: string; query: Query };\n\nexport type FieldRef = string | { field: string; as: string };\n\nexport type Query = {\n from: Source[];\n fields?: FieldRef[];\n filter?: Filter;\n compute?: Record<string, ComputeExpression>;\n aggregate?: Record<string, AggregateExpression>;\n groupBy?: string[];\n sort?: SortEntry[];\n limit?: number;\n distinct?: boolean;\n};\n\nconst SubquerySourceSchema = z\n .object({\n as: IdentifierSchema.describe('Alias for subquery results — use as prefix in field paths'),\n query: z.lazy((): z.ZodType<Query> => QuerySchema).describe('A nested query'),\n })\n .strict()\n .describe('Subquery data source: a nested query read as a table under `as`, its columns referenced as `<as>.<field>` anywhere in the outer query. Joined by foreign key like an entity when one links them; otherwise every outer row is paired with every subquery row (a cross join), so a one-row subquery puts its values beside each outer row.');\n\nconst SourceSchema = z\n .union([\n z.string().describe('Entity name from the database schema'),\n SubquerySourceSchema,\n ])\n .describe('Data source: entity name or subquery');\n\nconst FieldRefSchema = z\n .union([\n FieldPathSchema.describe('A column in entity.field format'),\n z\n .object({\n field: FieldPathSchema.describe('A column in entity.field format'),\n as: IdentifierSchema.describe('Output key for this column'),\n })\n .strict()\n .describe('An aliased column: output under `as` instead of the column name'),\n ])\n .describe('A selected field — a bare `entity.field`, or `{ field, as }` to alias the output key');\n\nexport const QuerySchema: z.ZodType<Query> = z.lazy(() =>\n z\n .object({\n from: z.array(SourceSchema).min(1).describe('Data sources — entity names or subqueries. Every entity used anywhere in the query must be listed here. Listed entities are JOINED FOR YOU along their foreign keys — a nullable key as a LEFT JOIN, so a row whose key is empty is kept, with the joined columns null. Never restate a join as a filter comparing the two keys: that throws those rows away.'),\n fields: z.array(FieldRefSchema).optional().describe('Raw columns to select — each `entity.field`, or `{ field, as }` to alias the output key (no SELECT *). Optional: omit it for an aggregate-only query (e.g. a bare COUNT). Do not list compute or aggregate aliases here — those are added automatically.'),\n filter: FilterSchema.optional().describe('Filter conditions'),\n compute: z.record(IdentifierSchema, ComputeExpressionSchema).optional().describe('Computed fields — key is output alias, value is the expression'),\n aggregate: z.record(IdentifierSchema, AggregateExpressionSchema).optional().describe('Aggregate functions — key is output alias, value is the function'),\n groupBy: z.array(FieldPathSchema).optional().describe('Fields to group by for aggregation'),\n sort: z.array(SortEntrySchema).optional().describe('Sort order'),\n limit: z.number().int().positive().optional().describe('Maximum rows to return'),\n distinct: z.boolean().optional().describe('Eliminate duplicate rows'),\n })\n .strict()\n .refine(\n (q) => (q.fields?.length ?? 0) > 0 || Object.keys(q.aggregate ?? {}).length > 0,\n { message: 'A query must select at least one of `fields` or `aggregate`.' },\n ),\n);\n\nexport { SubquerySourceSchema, SourceSchema };\n","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()).nullish().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).nullish().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).nullish().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()).nullish().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()).nullish().describe(inSpec('Filter conditions')),\n compute: z.record(z.string(), z.unknown()).nullish().describe(inSpec('Computed fields: output alias → expression')),\n aggregate: z.record(z.string(), z.unknown()).nullish().describe(inSpec('Aggregates (count, sum, avg, …): output alias → function')),\n groupBy: z.array(z.unknown()).nullish().describe(inSpec('Fields to group by, for aggregates')),\n sort: z.array(z.unknown()).nullish().describe(inSpec('Sort order')),\n limit: z.number().nullish().describe('Maximum rows to return.'),\n distinct: z.boolean().nullish().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 // A top-level key the model sent as null is one it left out.\n const parseResult = QuerySchema.safeParse(Object.fromEntries(Object.entries(input).filter(([, value]) => value !== null)));\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"]}