@niscorp/vex 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/DESIGN.md +11 -7
  3. package/DOCS.md +52 -9
  4. package/dist/adapters/express/index.cjs +1 -1
  5. package/dist/adapters/express/index.cjs.map +1 -1
  6. package/dist/adapters/express/index.d.cts +3 -2
  7. package/dist/adapters/express/index.d.ts +3 -2
  8. package/dist/adapters/express/index.js +3 -2
  9. package/dist/adapters/express/index.js.map +1 -1
  10. package/dist/adapters/hono/index.cjs +1 -1
  11. package/dist/adapters/hono/index.cjs.map +1 -1
  12. package/dist/adapters/hono/index.d.cts +3 -2
  13. package/dist/adapters/hono/index.d.ts +3 -2
  14. package/dist/adapters/hono/index.js +3 -2
  15. package/dist/adapters/hono/index.js.map +1 -1
  16. package/dist/agent/index.cjs +144 -21
  17. package/dist/agent/index.cjs.map +1 -1
  18. package/dist/agent/index.d.cts +3 -2
  19. package/dist/agent/index.d.ts +3 -2
  20. package/dist/agent/index.js +146 -22
  21. package/dist/agent/index.js.map +1 -1
  22. package/dist/{chunk-3HORTMZ7.js → chunk-AKR6HU34.js} +9 -5
  23. package/dist/chunk-AKR6HU34.js.map +1 -0
  24. package/dist/chunk-F7RDSWYF.js +7 -0
  25. package/dist/chunk-F7RDSWYF.js.map +1 -0
  26. package/dist/{chunk-J7JYKCUA.js → chunk-UPQMKAAX.js} +3 -18
  27. package/dist/chunk-UPQMKAAX.js.map +1 -0
  28. package/dist/chunk-XTOK7YOR.js +18 -0
  29. package/dist/chunk-XTOK7YOR.js.map +1 -0
  30. package/dist/{handler-B4NAi4k_.d.cts → handler-CoJxInw-.d.ts} +2 -1
  31. package/dist/{handler-BRVhWuNk.d.ts → handler-CsFbanZA.d.cts} +2 -1
  32. package/dist/index.cjs +26 -13
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +6 -4
  35. package/dist/index.d.ts +6 -4
  36. package/dist/index.js +30 -20
  37. package/dist/index.js.map +1 -1
  38. package/dist/migrations/index.cjs +173 -0
  39. package/dist/migrations/index.cjs.map +1 -0
  40. package/dist/migrations/index.d.cts +20 -0
  41. package/dist/migrations/index.d.ts +20 -0
  42. package/dist/migrations/index.js +23 -0
  43. package/dist/migrations/index.js.map +1 -0
  44. package/dist/query.schema-B-LVNfyX.d.cts +461 -0
  45. package/dist/query.schema-B-LVNfyX.d.ts +461 -0
  46. package/dist/{types-DUJp5B3o.d.cts → types-B2HEmyNq.d.cts} +11 -463
  47. package/dist/{types-DUJp5B3o.d.ts → types-DC68ZUuq.d.ts} +11 -463
  48. package/package.json +12 -1
  49. package/dist/chunk-3HORTMZ7.js.map +0 -1
  50. package/dist/chunk-J7JYKCUA.js.map +0 -1
@@ -1,6 +1,7 @@
1
1
  import { Env, Context, Hono } from 'hono';
2
- import { a as QueryEngine, al as ScopeValues, S as ScopePolicy } from '../../types-DUJp5B3o.cjs';
3
- import { M as MutationClient, W as WriteEvent, E as ExecuteRecord } from '../../handler-B4NAi4k_.cjs';
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';
4
+ import '../../query.schema-B-LVNfyX.cjs';
4
5
  import 'zod';
5
6
  import '@niscorp/prism';
6
7
  import '@niscorp/strata';
@@ -1,6 +1,7 @@
1
1
  import { Env, Context, Hono } from 'hono';
2
- import { a as QueryEngine, al as ScopeValues, S as ScopePolicy } from '../../types-DUJp5B3o.js';
3
- import { M as MutationClient, W as WriteEvent, E as ExecuteRecord } from '../../handler-BRVhWuNk.js';
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';
4
+ import '../../query.schema-B-LVNfyX.js';
4
5
  import 'zod';
5
6
  import '@niscorp/prism';
6
7
  import '@niscorp/strata';
@@ -1,5 +1,6 @@
1
- import { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../chunk-3HORTMZ7.js';
2
- import '../../chunk-J7JYKCUA.js';
1
+ import { handleDiscovery, handleQuery, handleFingerprintPatch, handleFingerprintDelete } from '../../chunk-AKR6HU34.js';
2
+ import '../../chunk-XTOK7YOR.js';
3
+ import '../../chunk-UPQMKAAX.js';
3
4
  import { Hono } from 'hono';
4
5
 
5
6
  var VEX_LIVE_ENV = "vexLive";
@@ -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,KAA4B,KAAK,OAAA,CAAQ,KAAA,CAAM,QAAA,EAAU,MAAA,EAAW,CAAC,QAAQ,CAAC,CAAA,EAAE;AAC9G,CAAA;AAmBA,IAAM,mBAAA,GAAsB,CAAC,IAAA,KAAsC;AACjE,EAA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AAC,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,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,OAA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AAI,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,GAAU,KAAiC,WAAW,CAAA;AAC5D,IAAA,MAAM,MAAA,GAAS,MAAM,sBAAA,CAAuB,aAAA,EAAe,WAAA,EAAa;AAAA,MACtE,GAAI,OAAO,MAAA,KAAW,SAAA,GAAY,EAAE,SAAA,EAAW,MAAA,KAAW;AAAC,KAC5D,CAAA;AACD,IAAA,OAAO,CAAA,CAAE,IAAA,CAAK,MAAA,CAAO,IAAA,EAAM,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"]}
@@ -332,6 +332,114 @@ var createQueryTools = (deps) => {
332
332
  cannotSatisfyTool
333
333
  ];
334
334
  };
335
+
336
+ // src/agent/compact.ts
337
+ var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
338
+ var compactSchema = (schema) => schema.entities.map((entity) => {
339
+ const fields = entity.fields.map((field) => `${field.name} ${field.type}${field.primaryKey ? " key" : ""}${field.nullable ? " null" : ""}`);
340
+ const relations = entity.relations.map((relation) => `${relation.type} ${relation.entity} (${relation.localFields.join(", ")} = ${relation.entity}.${relation.foreignFields.join(", ")})`);
341
+ const indexed = entity.indexes.filter((index) => !(index.unique && index.fields.length === 1 && entity.fields.some((field) => field.primaryKey && field.name === index.fields[0])));
342
+ return [
343
+ `${entity.name}${entity.table === entity.name ? "" : ` (table ${entity.table})`}: ${fields.join(", ")}`,
344
+ ...relations.length > 0 ? [` relations: ${relations.join("; ")}`] : [],
345
+ ...indexed.length > 0 ? [` indexed: ${indexed.map((index) => `${index.fields.join("+")}${index.unique ? " unique" : ""}`).join(", ")}`] : []
346
+ ].join("\n");
347
+ }).join("\n");
348
+ var nameOf = (ref) => ref.replace(/^#\/definitions\/(?:__schema)?/, "D");
349
+ var noteOf = (node) => {
350
+ const limits = ["minItems", "maxItems", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "minLength", "maxLength", "pattern", "format", "default"].filter((key) => key in node).map((key) => `${key} ${JSON.stringify(node[key])}`);
351
+ return limits.length > 0 ? ` (${limits.join(", ")})` : "";
352
+ };
353
+ var describedOf = (node) => isRecord(node) && typeof node["description"] === "string" ? ` /* ${node["description"]} */` : "";
354
+ var SPELLED = /* @__PURE__ */ 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"]);
355
+ var typeOf = (node, indent) => isRecord(node) && !Object.keys(node).some((key) => !SPELLED.has(key)) ? `${shapeOf(node, indent)}${describedOf(node)}` : JSON.stringify(node);
356
+ var shapeOf = (node, indent) => {
357
+ if (typeof node["$ref"] === "string") return nameOf(node["$ref"]);
358
+ const alternatives = node["anyOf"] ?? node["oneOf"];
359
+ if (Array.isArray(alternatives)) {
360
+ if (!alternatives.some((alternative) => describedOf(alternative) !== "")) return alternatives.map((alternative) => typeOf(alternative, indent)).join(" | ");
361
+ return alternatives.map((alternative) => `
362
+ ${indent} | ${typeOf(alternative, `${indent} `)}`).join("");
363
+ }
364
+ if (Array.isArray(node["allOf"])) return node["allOf"].map((part) => typeOf(part, indent)).join(" & ");
365
+ if (Array.isArray(node["enum"])) return node["enum"].map((value) => JSON.stringify(value)).join(" | ");
366
+ if ("const" in node) return JSON.stringify(node["const"]);
367
+ const kind = node["type"];
368
+ if (kind === "array") {
369
+ const item = typeOf(node["items"], indent);
370
+ return `${/[ |&]/.test(item) ? `(${item})` : item}[]${noteOf(node)}`;
371
+ }
372
+ if (kind === "object" || isRecord(node["properties"])) {
373
+ const required = new Set(Array.isArray(node["required"]) ? node["required"] : []);
374
+ const properties = Object.entries(isRecord(node["properties"]) ? node["properties"] : {}).map(
375
+ ([key, value]) => `${key}${required.has(key) ? "" : "?"}: ${typeOf(value, indent)}`
376
+ );
377
+ const rest = isRecord(node["additionalProperties"]) ? [`[key: string]: ${typeOf(node["additionalProperties"], indent)}`] : [];
378
+ return `{ ${[...properties, ...rest].join(", ")} }`;
379
+ }
380
+ if (Array.isArray(kind)) return kind.join(" | ");
381
+ if (typeof kind === "string") return `${kind}${noteOf(node)}`;
382
+ return JSON.stringify(node);
383
+ };
384
+ var compactSpec = (jsonSchema) => {
385
+ const root = jsonSchema;
386
+ const definitions = isRecord(root["definitions"]) ? root["definitions"] : {};
387
+ const number = (name) => Number(name.replace(/\D/g, "")) || 0;
388
+ return [
389
+ 'The query is one JSON object of type Query; every Dn is defined below. "a?: T" is optional, "A | B" is either.',
390
+ `Query = ${typeOf({ type: "object", properties: root["properties"], required: root["required"] }, "")}`,
391
+ ...Object.entries(definitions).sort(([a], [b]) => number(a) - number(b)).map(([name, node]) => `${nameOf(`#/definitions/${name}`)} = ${typeOf(node, "")}`)
392
+ ].join("\n");
393
+ };
394
+
395
+ // src/agent/declared.ts
396
+ var isRecord2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
397
+ var isExpression = (value) => isRecord2(value) && Object.keys(value).length === 1 && Object.keys(value)[0]?.startsWith("$") === true;
398
+ var templateOf = (shape) => Array.isArray(shape) ? shape[0] : shape;
399
+ var readsOf = (value) => {
400
+ if (Array.isArray(value)) return value.flatMap(readsOf);
401
+ if (!isRecord2(value)) return [];
402
+ const ref = value["$ref"];
403
+ const own = typeof ref === "string" && ref.startsWith("$.") ? [ref.slice(2).split(".")[0] ?? ""] : [];
404
+ return [...own, ...Object.values(value).flatMap(readsOf)].filter((field) => field !== "");
405
+ };
406
+ var fieldsOf = (shape) => {
407
+ const template = templateOf(shape);
408
+ if (!isRecord2(template)) return void 0;
409
+ const entries = Object.entries(template);
410
+ if (entries.some(([, value]) => (isRecord2(value) || Array.isArray(value)) && !isExpression(value))) return void 0;
411
+ return {
412
+ plain: entries.filter(([, value]) => !isExpression(value)).map(([key]) => key),
413
+ declared: entries.filter((entry) => isExpression(entry[1]))
414
+ };
415
+ };
416
+ var storedShape = (shape) => {
417
+ const fields = fieldsOf(shape);
418
+ if (fields === void 0 || fields.declared.length === 0) return { shape, declared: false };
419
+ const template = templateOf(shape);
420
+ const kept = Object.fromEntries(fields.plain.map((key) => [key, template[key]]));
421
+ for (const [, expression] of fields.declared) for (const field of readsOf(expression)) if (!(field in kept)) kept[field] = "";
422
+ return { shape: Array.isArray(shape) ? [kept] : kept, declared: true };
423
+ };
424
+ var onRow = (value) => {
425
+ if (Array.isArray(value)) return value.map(onRow);
426
+ if (!isRecord2(value)) return value;
427
+ const ref = value["$ref"];
428
+ if (typeof ref === "string" && ref.startsWith("$.") && Object.keys(value).length === 1) return { $get: { from: { $var: "row" }, path: ref.slice(2).split("."), fallback: null } };
429
+ return Object.fromEntries(Object.entries(value).map(([key, inner]) => [key, onRow(inner)]));
430
+ };
431
+ var declaredMapping = (shape) => {
432
+ const fields = fieldsOf(shape);
433
+ if (fields === void 0) return void 0;
434
+ const template = templateOf(shape);
435
+ const body = Object.fromEntries([
436
+ ...fields.plain.map((key) => [key, { $get: { from: { $var: "row" }, path: [key], fallback: null } }]),
437
+ ...fields.declared.map(([key, expression]) => [key, onRow(expression)])
438
+ ]);
439
+ const reads = [.../* @__PURE__ */ new Set([...fields.plain, ...fields.declared.flatMap(([, expression]) => readsOf(expression))])];
440
+ const config = Array.isArray(shape) ? { $map: { over: { $ref: "$.result" }, as: "row", body } } : { $with: { let: { row: { $ref: "$.result" } }, value: body } };
441
+ return { config, reads, examples: Object.fromEntries(fields.plain.map((key) => [key, template[key]])) };
442
+ };
335
443
  var describeCaller = (bindings) => bindings.length === 0 ? '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.' : [
336
444
  "The caller \u2014 the person or service this query is for \u2014 is identified by server-side scope values bound to these columns:",
337
445
  ...bindings.map((b) => `- ${b.entity}.${b.field} is the caller's { "$scope": "${b.key}" }`),
@@ -341,9 +449,9 @@ var INSTRUCTIONS = `You are Vex's query agent. You turn a caller's request \u201
341
449
 
342
450
  Context gives you two things:
343
451
  - the database schema: the entities, fields, relations, and indexes that actually exist;
344
- - the DSL JSON Schema: the exact structure your query must take. Its field
345
- descriptions ARE the rules \u2014 read them and follow them. They are the single
346
- source of truth for how every part of a query is written.
452
+ - the DSL specification, written as types: the exact structure your query must
453
+ take. Its descriptions ARE the rules \u2014 read them and follow them. They are the
454
+ single source of truth for how every part of a query is written.
347
455
 
348
456
  Your job is to RETRIEVE the data the request needs: choose the entities, columns,
349
457
  filters, computed values, and aggregates the schema supports. A separate step runs
@@ -380,7 +488,7 @@ var vexQueryDslAgent = cortex.defineAgent({
380
488
  ${deps.schemaJson}`,
381
489
  ({ deps }) => deps.caller ?? describeCaller([]),
382
490
  // Named OUTPUT SCHEMA because cortex's finish protocol refers to it by that name.
383
- ({ deps }) => `OUTPUT SCHEMA \u2014 the DSL specification (JSON Schema), the single source of truth for your query:
491
+ ({ deps }) => `OUTPUT SCHEMA \u2014 the DSL specification, written as types, the single source of truth for your query:
384
492
  ${deps.dslSpecJson}`
385
493
  ],
386
494
  // The DSL spec in the context is the schema documentation; with `doc` on it would be injected twice.
@@ -395,11 +503,14 @@ var reasonFrom = (args) => {
395
503
  return typeof reason === "string" ? reason : void 0;
396
504
  };
397
505
  var createQueryDsl = (config) => {
506
+ const dslSpec = compactSpec(config.queryJsonSchema);
398
507
  return async (request, schema, caller) => {
399
508
  const tools = createQueryTools({ getSchema: () => schema, read: caller.read });
509
+ const stored = storedShape(request.shape);
400
510
  const agentInput = {
401
- intent: request.intent,
402
- shape: request.shape,
511
+ intent: stored.declared ? `${request.intent ?? ""}
512
+ Return the stored fields the shape names; how a field is shown is worked out from them after the query.` : request.intent,
513
+ shape: stored.shape,
403
514
  contextKeys: Object.keys(request.context)
404
515
  };
405
516
  let unsatisfiableReason;
@@ -407,8 +518,8 @@ var createQueryDsl = (config) => {
407
518
  run = vexQueryDslAgent.run(agentInput, {
408
519
  llm: config.llm,
409
520
  deps: {
410
- schemaJson: JSON.stringify(schema),
411
- dslSpecJson: JSON.stringify(config.queryJsonSchema),
521
+ schemaJson: compactSchema(schema),
522
+ dslSpecJson: dslSpec,
412
523
  caller: describeCaller(caller.bindings)
413
524
  },
414
525
  tools,
@@ -444,23 +555,35 @@ var rowsFitShape = (rows, shape) => {
444
555
  return value === null || typeof value === typeof sample;
445
556
  });
446
557
  };
447
- var IDENTITY = { $ref: "$.result" };
558
+ var MAPPING_ATTEMPTS = 3;
448
559
  var createShapeMapper = (llm) => {
449
- return async (rows, shape) => {
560
+ return async (rows, shape, intent) => {
450
561
  const single = !Array.isArray(shape);
451
562
  const envelope = { result: single ? rows[0] ?? null : rows };
452
- if (rowsFitShape(rows, shape)) {
453
- const ir2 = await prism.compile(IDENTITY);
454
- return { ir: ir2, transformed: prism.execute(ir2, envelope) };
563
+ const declared = declaredMapping(shape);
564
+ const first = rows[0];
565
+ const carried = first === void 0 || declared !== void 0 && declared.reads.every((field) => field in first) && Object.entries(declared.examples).every(([field, example]) => first[field] === null || typeof first[field] === typeof example);
566
+ if (declared !== void 0 && carried) {
567
+ const ir = await prism.compile(declared.config);
568
+ return { ir, config: declared.config, transformed: prism.execute(ir, envelope) };
569
+ }
570
+ let failed;
571
+ for (let attempt2 = 1; attempt2 <= MAPPING_ATTEMPTS; attempt2 += 1) {
572
+ const notes = [
573
+ ...intent !== void 0 ? [`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.`] : [],
574
+ ...failed !== void 0 ? [`Your last config failed on these rows: ${failed}. Write one that runs on them.`] : []
575
+ ].join("\n");
576
+ const result = await agent.mappingAgent.run({ sampleInput: envelope, targetShape: shape, ...notes !== "" ? { notes } : {} }, { llm }).result;
577
+ if (!result.ok) throw new VexError("agent_failed", `${result.error.code}: ${result.error.message}`);
578
+ const config = result.output.data;
579
+ try {
580
+ const ir = await prism.compile(config);
581
+ return { ir, config, transformed: prism.execute(ir, envelope) };
582
+ } catch (error) {
583
+ failed = error instanceof Error ? error.message : String(error);
584
+ }
455
585
  }
456
- const result = await agent.mappingAgent.run(
457
- { sampleInput: envelope, targetShape: shape },
458
- { llm }
459
- ).result;
460
- if (!result.ok) throw new VexError("agent_failed", `${result.error.code}: ${result.error.message}`);
461
- const ir = await prism.compile(result.output.data);
462
- const transformed = prism.execute(ir, envelope);
463
- return { ir, transformed };
586
+ throw new VexError("agent_failed", `the mapping did not run on the rows it was written for: ${failed ?? "no reason given"}`);
464
587
  };
465
588
  };
466
589