@niscorp/prism 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,50 @@
1
1
  # @niscorp/prism
2
2
 
3
+ ## 0.3.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 7bcf306: An error says what the op got, where in the program, and the op's form, in its message. The message is what a caller passes on to a program's author, often a model that sees nothing else, and it said too little to fix anything: `Expected string for $trim`, `Path not found`, `Invalid config`.
8
+ - **A wrong type** names the value and where: `$trim needs text, but got an object: {"value":"Quarterly contributor outreach"}. … At $map.body.title.$trim. Form: {"$trim": <node>}`. Where the field was written as an object without a `$` key, it says such an object builds an object. The form is printed from the schema.
9
+ - **A path that found nothing** says where it stopped and what is there: `$ref "$.rows.name" stopped at "name": the value at $.rows is a list of 1 item: […], and a list is read by index, a number`. A missing key lists the keys there; a `$var` that is not there lists the variables in scope.
10
+ - **Inside a sugar op** the position is the author's: `At s.$sum, in the $add that $sum runs as.`
11
+ - **A refused config** puts its issues in `evaluate`'s message, as `compile` did, each with the form of the op it is on: `Invalid config: x: Unrecognized key: "fallback". Form: {"$trim": <node>}`. `validate`'s issue messages carry the same form.
12
+ - **An object whose only key names an op is checked as that op alone.** A reader of `ConfigSchema`'s issues that picks among a union's branches, as cortex's `flattenSchemaIssues` does, now gets the op's own issues (`$map/over: Unrecognized keys: "as", "body"`) instead of `$map: Invalid key in record`, and an op name that does not exist reads `Not a Prism op…`. Which configs are accepted is unchanged.
13
+ - The budget says where evaluation stopped; `E_NODE_SHAPE` puts the node in its message; `check: 'always'` names the first value of a source that is not plain JSON (`source.d is a Date`).
14
+
15
+ Codes, `PrismError`, `.context` (`op`, `path`, `details`) and every export are unchanged. `$assert`'s message is the program's own and is unchanged.
16
+
17
+ **What to change:** nothing. Code that compared a message's exact text gets the new text.
18
+
19
+ - ee625f7: `$get` reads a path segment of digits as an index when the value there is a list: `["link", "0"]` reads the first item of `link`, as `["link", 0]` does, and as JavaScript and JSON Pointer read it. Only digits count: `"01"`, `"-1"` and `" 0"` stay keys, and a key asked of a list is refused as before (`E_TYPE`, or the fallback).
20
+
21
+ Before, `"0"` on a list was a key, which a list does not have: without a `fallback` it threw `E_TYPE`, and with one it answered the fallback for every item, which is easy to miss. A model writing a mapping wrote `["link", "0"]` with a `null` fallback and got `null` for all twelve records; lyra's people roll reads its page cursor with `["0", field]` and has answered `""` every time.
22
+
23
+ **What to change:** nothing. A config that used a digit key on a list and relied on getting its fallback now gets the item.
24
+
25
+ - ef23b8e: `$join`, `$interpolate`, `$keyBy` and `$groupBy` refuse an object or a list where they need text, with `E_TYPE` and a message that says which item or key and what it was. They turned it into text with `String()`: an object became `"[object Object]"` and a list its items joined by commas, and nothing said so.
26
+ - `$join`: a part that is an object or a list (`$join.parts needs items that are text, a number, true, false or null, but item 1 is an object: {"a":1}.`). `null` is still `""`.
27
+ - `$interpolate`: a value for a `{{key}}` in the template that is an object or a list. A value the template does not use is not looked at, and a missing one is still `""`.
28
+ - `$keyBy` and `$groupBy`: a key that is an object or a list. Text, numbers, `true`, `false` and `null` are keys as before.
29
+
30
+ **What to change:** a config that joined or interpolated an object or a list, or grouped by one, now fails instead of answering `"[object Object]"` or `"a,b"`. Pick the field you meant (`$get`), or join the list first (`$join`).
31
+
32
+ ## 0.3.1
33
+
34
+ ### Patch Changes
35
+
36
+ - f55fcbe: DOCS.md and the README state seven facts about the API that were written only in source comments.
37
+
38
+ DOCS.md: a negative index in a `$ref` path is refused, the generated JSON Schema does not carry the `$ref` path rule, and `maxValues` counts a value each time it appears. README: an example's `id` is unique and in kebab-case, an example of several operators has no `op`, which ops `MAPPING_OPS` leaves out, and that the mapping agent's `data` is the config itself.
39
+
40
+ No behaviour changed.
41
+
42
+ **What to change:** nothing.
43
+
44
+ - 89adcc3: The optimizer no longer keeps a local `isPlainObject` that only called `isJsonObject`; its three uses call `isJsonObject`. Prism's own `isPlainObject` means an object with no `$` key, and the local one of the same name meant any JSON object. No behaviour changed.
45
+
46
+ **What to change:** nothing.
47
+
3
48
  ## 0.3.0
4
49
 
5
50
  ### Minor Changes
package/DESIGN.md CHANGED
@@ -138,6 +138,8 @@ All errors are `PrismError` instances with a `.code` string and optional `.conte
138
138
  | `E_ASSERT` | A config's own `$assert` refused its input |
139
139
  | `E_BUDGET` | An evaluation went past its budget (`engine/budget.ts`) |
140
140
 
141
+ The message is the one thing a caller passes on to the author, so it carries what the op got, the position in the program and, for a wrong type, the op's form (DOCS.md, "What a message says"). An op refuses through `failAt` (`errors.ts`), which keeps the node beside the error; `evaluate` and `execute` catch it once on the way out and `placeError` (`engine/place.ts`) finds the node and writes the position. Describing, finding and printing happen only for an error, never while a program succeeds.
142
+
141
143
  ---
142
144
 
143
145
  ## File Structure
@@ -145,7 +147,7 @@ All errors are `PrismError` instances with a `.code` string and optional `.conte
145
147
  ```
146
148
  src/
147
149
  ├── index.ts # Public API barrel
148
- ├── errors.ts # PrismError + error codes
150
+ ├── errors.ts # PrismError + error codes; failAt keeps the node an error came from
149
151
  ├── types.ts # JsonValue, EvalContext, CompiledIr, etc.
150
152
  ├── schemas/
151
153
  │ ├── index.ts # Schema barrel
@@ -173,9 +175,11 @@ src/
173
175
  │ ├── optimize.ts # Compile-time passes (ref segments, handlers, constant folding)
174
176
  │ ├── budget.ts # Limits: steps, string length, result size
175
177
  │ ├── execute.ts # CompiledIr + source → result
178
+ │ ├── place.ts # On the way out: an error's position, in the author's config, and the op's form
176
179
  │ ├── validate.ts # Config validation
177
180
  │ └── documentation.ts # JSON Schema generation
178
181
  ├── ops/ # One implementation file per category
182
+ │ ├── refuse.ts # The sentence for an op given the wrong kind of value
179
183
  │ ├── core.ops.ts
180
184
  │ ├── array.ops.ts
181
185
  │ ├── math.ops.ts
@@ -224,7 +228,7 @@ and a mapping over a thousand rows would otherwise build a thousand of them.
224
228
 
225
229
  1. **Linear if-chain over Map dispatch.** Type narrowing. Each guard narrows the node type. A Map would need casts.
226
230
 
227
- 2. **Desugar before execution, not during.** One canonical representation. Compiler stores desugared form. Error messages reference core ops only.
231
+ 2. **Desugar before execution, not during.** One canonical representation. Compiler stores desugared form. An error inside a sugar op names the core op that refused and the sugar op the author wrote: `engine/place.ts` follows the position back into the author's config, and where a sugar op's keys stop matching, rewrites a copy of it with a marker in each field to see where each field went. Nothing records the rewrite while it runs; the work is done only for an error.
228
232
 
229
233
  3. **JSONPath subset, not full spec.** Filters, recursive descent, and unions overlap with `$filter`, `$map`, and `$merge`. The subset covers path access; ops cover everything else.
230
234
 
package/DOCS.md CHANGED
@@ -44,7 +44,7 @@ If `$.user.nickname` doesn't exist, the result is `{ "name": "Alice" }` — no e
44
44
 
45
45
  ### `$ref` — Read from source
46
46
 
47
- Resolves a path against the source data. A path is keys and indexes: `.key` and `[index]`. The rest of JSONPath — a wildcard `[*]`, a filter `[?(…)]`, a slice, a quoted key, `..` — is refused when the config is checked (`E_SCHEMA`, "Not a path Prism reads"); for every item of a list use `$map` or `$pluck`.
47
+ Resolves a path against the source data. A path is keys and indexes: `.key` and `[index]`. The rest of JSONPath — a wildcard `[*]`, a filter `[?(…)]`, a slice, a negative index, a quoted key, `..` — is refused when the config is checked (`E_SCHEMA`, "Not a path Prism reads"); for every item of a list use `$map` or `$pluck`. The JSON Schema from `getConfigJsonSchema`, `getNodeJsonSchema` and `getProfileJsonSchema` does not carry this rule: its pattern for `$ref` is `^\$(\..*)?$`, so a path can pass the JSON Schema and still be refused by `validate`.
48
48
 
49
49
  ```json
50
50
  { "$ref": "$.user.name" }
@@ -81,7 +81,7 @@ Throws `E_VAR_NOT_FOUND` if the variable doesn't exist in scope.
81
81
 
82
82
  ### `$get` — Dynamic path access
83
83
 
84
- Navigates into a value using an array of path segments. Segments can be strings (object keys), numbers (array indices), or node expressions (evaluated dynamically).
84
+ Navigates into a value using an array of path segments. Segments can be strings (object keys), numbers (array indices), or node expressions (evaluated dynamically). On a list, a string of digits is an index too, as JavaScript and JSON Pointer read it: `["link", "0"]` and `["link", 0]` both read the first item of `link`. Only digits count: `"01"`, `"-1"` and `" 0"` are keys, and a list has none.
85
85
 
86
86
  ```json
87
87
  { "$get": { "from": { "$ref": "$.user" }, "path": ["address", "city"] } }
@@ -278,7 +278,7 @@ A number is answered as it is. Text is read as a number when it is one written i
278
278
  ```json
279
279
  { "$join": { "parts": [{ "$ref": "$.first" }, { "$ref": "$.last" }], "sep": " " } }
280
280
  ```
281
- Parts are coerced to strings. `sep` defaults to `""`. `parts` may also be any
281
+ Parts are coerced to strings; `null` is `""`. A part that is an object or a list is refused (`E_TYPE`): it has no text of its own. `sep` defaults to `""`. `parts` may also be any
282
282
  node that evaluates to an array — a mapped list, a `$var`:
283
283
  ```json
284
284
  { "$join": { "parts": { "$map": { "over": { "$ref": "$.tags" }, "as": "t", "body": { "$upper": { "$var": "t" } } } }, "sep": ", " } }
@@ -299,7 +299,7 @@ Numbers → `"42"`, null → `"null"`, objects → JSON string.
299
299
  }
300
300
  }
301
301
  ```
302
- Replaces `{{key}}` placeholders with values from the evaluated object. Missing keys become empty strings.
302
+ Replaces `{{key}}` placeholders with values from the evaluated object. Missing keys become empty strings. A value that is an object or a list is refused (`E_TYPE`).
303
303
 
304
304
  ### `$fill` — Fill a counted phrase
305
305
  ```json
@@ -442,7 +442,7 @@ Evaluates branches in order, returns the `then` of the first truthy `when`. Fall
442
442
  ```
443
443
  `[{ "id": "u1", "name": "Alice" }]` → `{ "u1": { "id": "u1", "name": "Alice" } }`
444
444
 
445
- Last element wins on key collision.
445
+ Last element wins on key collision. A key is text, a number, `true`, `false` or `null`, written as text; an object or a list is refused (`E_TYPE`).
446
446
 
447
447
  ### `$groupBy` — Array to grouped object
448
448
  ```json
@@ -454,7 +454,7 @@ Last element wins on key collision.
454
454
  }
455
455
  }
456
456
  ```
457
- Groups elements into arrays by computed key: `{ "fruit": [...], "vegetable": [...] }`
457
+ Groups elements into arrays by computed key: `{ "fruit": [...], "vegetable": [...] }`. A key is text, a number, `true`, `false` or `null`, written as text; an object or a list is refused (`E_TYPE`).
458
458
 
459
459
  ---
460
460
 
@@ -812,7 +812,9 @@ third argument: a `Partial<Limits>`, merged over `DEFAULT_LIMITS`:
812
812
  | `maxStringLength` | `1_000_000` | Characters in any one string a node produces |
813
813
  | `maxValues` | `1_000_000` | Values (scalars, array items, object fields) in a `$reduce` accumulator, a `$with` binding, or the result |
814
814
 
815
- Past any of them the evaluation throws `E_BUDGET`.
815
+ Past any of them the evaluation throws `E_BUDGET`. `maxValues` counts a value
816
+ each time it appears, as it would be serialized: a `$reduce` whose body is
817
+ `[{ "$var": "acc" }, { "$var": "acc" }]` doubles its count with every item.
816
818
 
817
819
  ## Error Codes
818
820
 
@@ -830,4 +832,17 @@ Past any of them the evaluation throws `E_BUDGET`.
830
832
 
831
833
  All errors are instances of `PrismError` with `.code` and optional `.context`.
832
834
 
835
+ **What a message says.** The message is written for the program's author, often a model that sees nothing else, so it carries everything needed to fix the program:
836
+
837
+ - **what the op got:** `null`, `the number 5`, `text "…"` (up to 60 characters), `a list of 2 items: […]` or `an object: {…}` (up to 80 characters of JSON). Where the field was written in the program as an object without a `$` key, it says so: such an object builds an object.
838
+ - **where:** `At $map.body.title.$trim.`, a position in the config as it was handed to `evaluate`. Inside a sugar op it is the sugar op's position (`At s.$sum, in the $add that $sum runs as.`). `execute` gives the position in the compiled tree.
839
+ - **the op's form**, for a wrong type and for a `$get` path: `Form: {"$split": {"value": <node>, "sep": <text>}}`, printed from the schema.
840
+ - for a path that found nothing, where it stopped and what is there (`stopped at "fields": the value at $.records is a list of 2 items`); for a variable that is not there, the ones in scope.
841
+
842
+ A refused config says the same in `evaluate`'s and `compile`'s message: `Invalid config: <path>: <issue>; …`, with the form of the op the issue is on. `.context` is unchanged: `op`, `path` and `details` are as before.
843
+
844
+ ```
845
+ $trim needs text, but got an object: {"value":"Quarterly contributor outreach"}. That object was written in the program as {"value":{"$get":…}}, and an object without a "$" key builds an object; put the node itself there. At $map.body.title.$trim. Form: {"$trim": <node>}
846
+ ```
847
+
833
848
  **Valid, and what it does not promise.** `validate`, `evaluate` and `compile` hold a config to the same schema, so a config that validates has no node the evaluator cannot dispatch: every object in it is an op Prism has or a plain object with no `$` key. It can still fail on the data it is given — a missing path, a wrong type, a budget. `E_NODE_SHAPE` is what is left for a tree the schema never saw: an IR handed to `execute`, which does not validate.
package/README.md CHANGED
@@ -107,6 +107,9 @@ form that does not need the config object to be the same one.
107
107
  `@niscorp/prism/examples` is the reference as data: one example for each
108
108
  operator, named by the operator — a config, the source it is given, and what
109
109
  comes out — then a few configs of several operators working together.
110
+ Each `id` is unique across the set and in kebab-case (`sort-by` for `$sortBy`),
111
+ so an address can be built on it. An example of several operators working
112
+ together has no `op`.
110
113
 
111
114
  ```typescript
112
115
  import { evaluate } from '@niscorp/prism';
@@ -130,9 +133,14 @@ own. So whatever shows them — a documentation page, an agent reading
130
133
  `getProfileJsonSchema(ops, target?)` is the config JSON Schema documenting only
131
134
  the ops you name — derived from the full schema, never restated. `MAPPING_OPS`
132
135
  is the set a mapping uses (rows into a shape), about 28% less prompt than the
133
- whole grammar; the mapping agent is documented with it. A profile narrows what
134
- a prompt teaches, never what Prism accepts: validation is always the full
136
+ whole grammar; the mapping agent is documented with it. That agent's `data` is
137
+ the Prism config itself, and its `reasoning` is one sentence on the mapping. A
138
+ profile narrows what a prompt teaches, never what Prism accepts: validation is always the full
135
139
  `ConfigSchema`, and a config using an op outside the profile is still valid.
140
+ `MAPPING_OPS` leaves out the transform ops (`$has`, `$renameKeys`, `$update`,
141
+ `$assert`, `$walk`) and `$fill`, `$replace`, `$keyBy`, `$entriesOf`,
142
+ `$fromEntries`, `$keys`, `$values`, `$type`, `$flatten`, `$flatMap`, `$match`,
143
+ `$drop`, `$dateAdd`, `$startsWith` and `$endsWith`.
136
144
 
137
145
  ## Transform ops and the grammar
138
146
 
package/dist/agent.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkOLZQK2ZF_cjs = require('./chunk-OLZQK2ZF.cjs');
4
- var chunk66YSI4PX_cjs = require('./chunk-66YSI4PX.cjs');
3
+ var chunkROYHYYIL_cjs = require('./chunk-ROYHYYIL.cjs');
4
+ var chunkQUI2X5JB_cjs = require('./chunk-QUI2X5JB.cjs');
5
5
  var zod = require('zod');
6
6
  var cortex = require('@niscorp/cortex');
7
7
 
@@ -21,17 +21,15 @@ Worked example (illustrative only \u2014 read the schema for op details):
21
21
  INPUT { "sampleInput": { "first": "Ada", "last": "Lovelace" }, "targetShape": { "fullName": "" } }
22
22
  data { "fullName": { "$interpolate": { "template": "{{f}} {{l}}", "values": { "f": { "$ref": "$.first" }, "l": { "$ref": "$.last" } } } } }`;
23
23
  var OUTPUT_DOC = `OUTPUT SCHEMA \u2014 your output MUST validate against this JSON Schema:
24
- ${JSON.stringify(chunkOLZQK2ZF_cjs.getProfileJsonSchema(chunkOLZQK2ZF_cjs.MAPPING_OPS, "draft-7"))}`;
24
+ ${JSON.stringify(chunkROYHYYIL_cjs.getProfileJsonSchema(chunkROYHYYIL_cjs.MAPPING_OPS, "draft-7"))}`;
25
25
  var mappingAgent = cortex.defineAgent({
26
26
  id: "prism.mapping",
27
27
  description: "Generates a Prism transformation config from a sample input row and a target shape.",
28
28
  instructions: INSTRUCTIONS,
29
- // Validated against the FULL grammar — a config using any op is accepted,
30
- // exactly as before — but documented with the mapping profile: the ops a
31
- // mapping uses, about 28% less prompt than the whole grammar
32
- // (schemas/profiles.ts). The heading is cortex's own (context/schema-doc.ts),
33
- // so the finish protocol's "OUTPUT SCHEMA" still names it.
34
- output: { schema: chunk66YSI4PX_cjs.ConfigSchema, doc: OUTPUT_DOC }
29
+ // Validated against the full grammar, documented with the mapping profile:
30
+ // a config using an op outside the profile is still accepted. The doc keeps
31
+ // cortex's own heading, "OUTPUT SCHEMA", which its finish protocol names.
32
+ output: { schema: chunkQUI2X5JB_cjs.ConfigSchema, doc: OUTPUT_DOC }
35
33
  });
36
34
 
37
35
  exports.MappingAgentInputSchema = MappingAgentInputSchema;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent/mapping-agent.ts"],"names":["z","getProfileJsonSchema","MAPPING_OPS","defineAgent","ConfigSchema"],"mappings":";;;;;;;AA6CO,IAAM,uBAAA,GAA0BA,MAAE,MAAA,CAAO;AAAA,EAC9C,WAAA,EAAaA,KAAA,CACV,MAAA,CAAOA,KAAA,CAAE,MAAA,EAAO,EAAGA,KAAA,CAAE,OAAA,EAAS,CAAA,CAC9B,QAAA,CAAS,qFAAqF,CAAA;AAAA,EACjG,WAAA,EAAaA,KAAA,CACV,OAAA,EAAQ,CACR,QAAA;AAAA,IACC;AAAA,GACF;AAAA,EACF,iBAAA,EAAmBA,KAAA,CAChB,MAAA,CAAOA,KAAA,CAAE,MAAA,EAAO,EAAGA,KAAA,CAAE,MAAA,EAAQ,CAAA,CAC7B,QAAA,EAAS,CACT,SAAS,sFAAsF,CAAA;AAAA,EAClG,OAAOA,KAAA,CACJ,MAAA,GACA,QAAA,EAAS,CACT,SAAS,8DAA8D;AAC5E,CAAC;AAiBD,IAAM,YAAA,GAAe,CAAA;;AAAA;;AAAA;AAAA;AAAA,6IAAA,CAAA;AAQrB,IAAM,UAAA,GAAa,CAAA;AAAA,EAAwE,KAAK,SAAA,CAAUC,sCAAA,CAAqBC,6BAAA,EAAa,SAAS,CAAC,CAAC,CAAA,CAAA;AAMhJ,IAAM,eAAwCC,kBAAA,CAAoB;AAAA,EACvE,EAAA,EAAI,eAAA;AAAA,EACJ,WAAA,EAAa,qFAAA;AAAA,EACb,YAAA,EAAc,YAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMd,MAAA,EAAQ,EAAE,MAAA,EAAQC,8BAAA,EAAc,KAAK,UAAA;AACvC,CAAC","file":"agent.cjs","sourcesContent":["// ═══════════════════════════════════════════════════════════\n// @niscorp/prism/agent — Prism mapping agent\n// ═══════════════════════════════════════════════════════════\n//\n// Given a sample input row and a target shape, the mapping agent\n// produces a Prism Config that transforms input → target.\n//\n// This is the canonical \"package owns its agent, runs it on Cortex\"\n// pattern. Cortex is an optional peer dep: the rest of @niscorp/prism\n// does not need it.\n//\n// Usage:\n//\n// import { createSignal } from '@niscorp/signal';\n// import { mappingAgent } from '@niscorp/prism/agent';\n// import { evaluate } from '@niscorp/prism';\n//\n// const llm = createSignal('groq', { apiKey }); // qwen/qwen3.8-27b, the registry default\n// const result = await mappingAgent.run({\n// sampleInput: { first: 'Ada', last: 'Lovelace' },\n// targetShape: { fullName: '' },\n// }, { llm }).result;\n//\n// if (result.ok) {\n// // result.output.data is a fully-validated Prism Config;\n// // result.output.reasoning is the model's one-line why.\n// const output = evaluate(result.output.data, sampleInput);\n// }\n//\n// The Config schema itself is NOT embedded in this prompt — cortex\n// injects it (output.doc 'auto' → schemaDoc(ConfigSchema)) because the\n// recursive Node union can't ride the respond tool's params. One\n// source of truth, zero hand-maintained schema prose.\n\nimport { z } from 'zod';\nimport { defineAgent, type AgentDefinition } from '@niscorp/cortex';\n\nimport { ConfigSchema, type Config } from '../schemas';\nimport { MAPPING_OPS } from '../schemas/profiles';\nimport { getProfileJsonSchema } from '../engine/documentation';\n\n// ───────────────────────────────────────────────────────────\n// Input schema\n// ───────────────────────────────────────────────────────────\n\nexport const MappingAgentInputSchema = z.object({\n sampleInput: z\n .record(z.string(), z.unknown())\n .describe('A representative input row. The transformation will run against rows of this shape.'),\n targetShape: z\n .unknown()\n .describe(\n 'A JSON example of the desired output shape. Field values are placeholders; the agent infers the structure from this example.',\n ),\n fieldDescriptions: z\n .record(z.string(), z.string())\n .optional()\n .describe('Optional human-readable descriptions for fields the agent might not infer correctly.'),\n notes: z\n .string()\n .optional()\n .describe('Free-form additional context (data quirks, semantics, etc.).'),\n});\n\nexport type MappingAgentInput = z.infer<typeof MappingAgentInputSchema>;\n\n// The agent's payload IS the Prism Config. The model's explanation\n// rides the envelope's `reasoning` field — no wrapper schema.\nexport type MappingAgentOutput = Config;\n\n// ───────────────────────────────────────────────────────────\n// System prompt — role + worked example, nothing else\n// ───────────────────────────────────────────────────────────\n//\n// Per niscorp/STYLE_GUIDE.md: every operation, constraint and gotcha\n// lives in the Prism schema's .describe() calls, and the prompt carries\n// the JSON Schema (OUTPUT_DOC below). If the model gets an op wrong,\n// sharpen the relevant .describe() in @niscorp/prism — do not add prose here.\n\nconst INSTRUCTIONS = `You are the Prism mapping agent. Given a sample input row and a target output shape, produce a Prism Config that maps rows of the input shape into the target shape.\n\nYour envelope's \\`data\\` is the Prism Config; \\`reasoning\\` is a one-sentence explanation of the mapping. The config must validate against the OUTPUT SCHEMA below (every constraint, format rule and example is in the schema's field descriptions).\n\nWorked example (illustrative only — read the schema for op details):\nINPUT { \"sampleInput\": { \"first\": \"Ada\", \"last\": \"Lovelace\" }, \"targetShape\": { \"fullName\": \"\" } }\ndata { \"fullName\": { \"$interpolate\": { \"template\": \"{{f}} {{l}}\", \"values\": { \"f\": { \"$ref\": \"$.first\" }, \"l\": { \"$ref\": \"$.last\" } } } } }`;\n\nconst OUTPUT_DOC = `OUTPUT SCHEMA — your output MUST validate against this JSON Schema:\\n${JSON.stringify(getProfileJsonSchema(MAPPING_OPS, 'draft-7'))}`;\n\n// ───────────────────────────────────────────────────────────\n// Agent definition — the entire public surface\n// ───────────────────────────────────────────────────────────\n\nexport const mappingAgent: AgentDefinition<Config> = defineAgent<Config>({\n id: 'prism.mapping',\n description: 'Generates a Prism transformation config from a sample input row and a target shape.',\n instructions: INSTRUCTIONS,\n // Validated against the FULL grammar — a config using any op is accepted,\n // exactly as before — but documented with the mapping profile: the ops a\n // mapping uses, about 28% less prompt than the whole grammar\n // (schemas/profiles.ts). The heading is cortex's own (context/schema-doc.ts),\n // so the finish protocol's \"OUTPUT SCHEMA\" still names it.\n output: { schema: ConfigSchema, doc: OUTPUT_DOC },\n});\n"]}
1
+ {"version":3,"sources":["../src/agent/mapping-agent.ts"],"names":["z","getProfileJsonSchema","MAPPING_OPS","defineAgent","ConfigSchema"],"mappings":";;;;;;;AAOO,IAAM,uBAAA,GAA0BA,MAAE,MAAA,CAAO;AAAA,EAC9C,WAAA,EAAaA,KAAA,CACV,MAAA,CAAOA,KAAA,CAAE,MAAA,EAAO,EAAGA,KAAA,CAAE,OAAA,EAAS,CAAA,CAC9B,QAAA,CAAS,qFAAqF,CAAA;AAAA,EACjG,WAAA,EAAaA,KAAA,CACV,OAAA,EAAQ,CACR,QAAA;AAAA,IACC;AAAA,GACF;AAAA,EACF,iBAAA,EAAmBA,KAAA,CAChB,MAAA,CAAOA,KAAA,CAAE,MAAA,EAAO,EAAGA,KAAA,CAAE,MAAA,EAAQ,CAAA,CAC7B,QAAA,EAAS,CACT,SAAS,sFAAsF,CAAA;AAAA,EAClG,OAAOA,KAAA,CACJ,MAAA,GACA,QAAA,EAAS,CACT,SAAS,8DAA8D;AAC5E,CAAC;AAMD,IAAM,YAAA,GAAe,CAAA;;AAAA;;AAAA;AAAA;AAAA,6IAAA,CAAA;AAQrB,IAAM,UAAA,GAAa,CAAA;AAAA,EAAwE,KAAK,SAAA,CAAUC,sCAAA,CAAqBC,6BAAA,EAAa,SAAS,CAAC,CAAC,CAAA,CAAA;AAEhJ,IAAM,eAAwCC,kBAAA,CAAoB;AAAA,EACvE,EAAA,EAAI,eAAA;AAAA,EACJ,WAAA,EAAa,qFAAA;AAAA,EACb,YAAA,EAAc,YAAA;AAAA;AAAA;AAAA;AAAA,EAId,MAAA,EAAQ,EAAE,MAAA,EAAQC,8BAAA,EAAc,KAAK,UAAA;AACvC,CAAC","file":"agent.cjs","sourcesContent":["import { z } from 'zod';\nimport { defineAgent, type AgentDefinition } from '@niscorp/cortex';\n\nimport { ConfigSchema, type Config } from '../schemas';\nimport { MAPPING_OPS } from '../schemas/profiles';\nimport { getProfileJsonSchema } from '../engine/documentation';\n\nexport const MappingAgentInputSchema = z.object({\n sampleInput: z\n .record(z.string(), z.unknown())\n .describe('A representative input row. The transformation will run against rows of this shape.'),\n targetShape: z\n .unknown()\n .describe(\n 'A JSON example of the desired output shape. Field values are placeholders; the agent infers the structure from this example.',\n ),\n fieldDescriptions: z\n .record(z.string(), z.string())\n .optional()\n .describe('Optional human-readable descriptions for fields the agent might not infer correctly.'),\n notes: z\n .string()\n .optional()\n .describe('Free-form additional context (data quirks, semantics, etc.).'),\n});\n\nexport type MappingAgentInput = z.infer<typeof MappingAgentInputSchema>;\n\nexport type MappingAgentOutput = Config;\n\nconst INSTRUCTIONS = `You are the Prism mapping agent. Given a sample input row and a target output shape, produce a Prism Config that maps rows of the input shape into the target shape.\n\nYour envelope's \\`data\\` is the Prism Config; \\`reasoning\\` is a one-sentence explanation of the mapping. The config must validate against the OUTPUT SCHEMA below (every constraint, format rule and example is in the schema's field descriptions).\n\nWorked example (illustrative only — read the schema for op details):\nINPUT { \"sampleInput\": { \"first\": \"Ada\", \"last\": \"Lovelace\" }, \"targetShape\": { \"fullName\": \"\" } }\ndata { \"fullName\": { \"$interpolate\": { \"template\": \"{{f}} {{l}}\", \"values\": { \"f\": { \"$ref\": \"$.first\" }, \"l\": { \"$ref\": \"$.last\" } } } } }`;\n\nconst OUTPUT_DOC = `OUTPUT SCHEMA — your output MUST validate against this JSON Schema:\\n${JSON.stringify(getProfileJsonSchema(MAPPING_OPS, 'draft-7'))}`;\n\nexport const mappingAgent: AgentDefinition<Config> = defineAgent<Config>({\n id: 'prism.mapping',\n description: 'Generates a Prism transformation config from a sample input row and a target shape.',\n instructions: INSTRUCTIONS,\n // Validated against the full grammar, documented with the mapping profile:\n // a config using an op outside the profile is still accepted. The doc keeps\n // cortex's own heading, \"OUTPUT SCHEMA\", which its finish protocol names.\n output: { schema: ConfigSchema, doc: OUTPUT_DOC },\n});\n"]}
package/dist/agent.js CHANGED
@@ -1,5 +1,5 @@
1
- import { getProfileJsonSchema, MAPPING_OPS } from './chunk-BKXCULZV.js';
2
- import { ConfigSchema } from './chunk-7VMFSXBM.js';
1
+ import { getProfileJsonSchema, MAPPING_OPS } from './chunk-VNGBVDUM.js';
2
+ import { ConfigSchema } from './chunk-OL4CCYWX.js';
3
3
  import { z } from 'zod';
4
4
  import { defineAgent } from '@niscorp/cortex';
5
5
 
@@ -24,11 +24,9 @@ var mappingAgent = defineAgent({
24
24
  id: "prism.mapping",
25
25
  description: "Generates a Prism transformation config from a sample input row and a target shape.",
26
26
  instructions: INSTRUCTIONS,
27
- // Validated against the FULL grammar — a config using any op is accepted,
28
- // exactly as before — but documented with the mapping profile: the ops a
29
- // mapping uses, about 28% less prompt than the whole grammar
30
- // (schemas/profiles.ts). The heading is cortex's own (context/schema-doc.ts),
31
- // so the finish protocol's "OUTPUT SCHEMA" still names it.
27
+ // Validated against the full grammar, documented with the mapping profile:
28
+ // a config using an op outside the profile is still accepted. The doc keeps
29
+ // cortex's own heading, "OUTPUT SCHEMA", which its finish protocol names.
32
30
  output: { schema: ConfigSchema, doc: OUTPUT_DOC }
33
31
  });
34
32
 
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/agent/mapping-agent.ts"],"names":[],"mappings":";;;;;AA6CO,IAAM,uBAAA,GAA0B,EAAE,MAAA,CAAO;AAAA,EAC9C,WAAA,EAAa,CAAA,CACV,MAAA,CAAO,CAAA,CAAE,MAAA,EAAO,EAAG,CAAA,CAAE,OAAA,EAAS,CAAA,CAC9B,QAAA,CAAS,qFAAqF,CAAA;AAAA,EACjG,WAAA,EAAa,CAAA,CACV,OAAA,EAAQ,CACR,QAAA;AAAA,IACC;AAAA,GACF;AAAA,EACF,iBAAA,EAAmB,CAAA,CAChB,MAAA,CAAO,CAAA,CAAE,MAAA,EAAO,EAAG,CAAA,CAAE,MAAA,EAAQ,CAAA,CAC7B,QAAA,EAAS,CACT,SAAS,sFAAsF,CAAA;AAAA,EAClG,OAAO,CAAA,CACJ,MAAA,GACA,QAAA,EAAS,CACT,SAAS,8DAA8D;AAC5E,CAAC;AAiBD,IAAM,YAAA,GAAe,CAAA;;AAAA;;AAAA;AAAA;AAAA,6IAAA,CAAA;AAQrB,IAAM,UAAA,GAAa,CAAA;AAAA,EAAwE,KAAK,SAAA,CAAU,oBAAA,CAAqB,WAAA,EAAa,SAAS,CAAC,CAAC,CAAA,CAAA;AAMhJ,IAAM,eAAwC,WAAA,CAAoB;AAAA,EACvE,EAAA,EAAI,eAAA;AAAA,EACJ,WAAA,EAAa,qFAAA;AAAA,EACb,YAAA,EAAc,YAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMd,MAAA,EAAQ,EAAE,MAAA,EAAQ,YAAA,EAAc,KAAK,UAAA;AACvC,CAAC","file":"agent.js","sourcesContent":["// ═══════════════════════════════════════════════════════════\n// @niscorp/prism/agent — Prism mapping agent\n// ═══════════════════════════════════════════════════════════\n//\n// Given a sample input row and a target shape, the mapping agent\n// produces a Prism Config that transforms input → target.\n//\n// This is the canonical \"package owns its agent, runs it on Cortex\"\n// pattern. Cortex is an optional peer dep: the rest of @niscorp/prism\n// does not need it.\n//\n// Usage:\n//\n// import { createSignal } from '@niscorp/signal';\n// import { mappingAgent } from '@niscorp/prism/agent';\n// import { evaluate } from '@niscorp/prism';\n//\n// const llm = createSignal('groq', { apiKey }); // qwen/qwen3.8-27b, the registry default\n// const result = await mappingAgent.run({\n// sampleInput: { first: 'Ada', last: 'Lovelace' },\n// targetShape: { fullName: '' },\n// }, { llm }).result;\n//\n// if (result.ok) {\n// // result.output.data is a fully-validated Prism Config;\n// // result.output.reasoning is the model's one-line why.\n// const output = evaluate(result.output.data, sampleInput);\n// }\n//\n// The Config schema itself is NOT embedded in this prompt — cortex\n// injects it (output.doc 'auto' → schemaDoc(ConfigSchema)) because the\n// recursive Node union can't ride the respond tool's params. One\n// source of truth, zero hand-maintained schema prose.\n\nimport { z } from 'zod';\nimport { defineAgent, type AgentDefinition } from '@niscorp/cortex';\n\nimport { ConfigSchema, type Config } from '../schemas';\nimport { MAPPING_OPS } from '../schemas/profiles';\nimport { getProfileJsonSchema } from '../engine/documentation';\n\n// ───────────────────────────────────────────────────────────\n// Input schema\n// ───────────────────────────────────────────────────────────\n\nexport const MappingAgentInputSchema = z.object({\n sampleInput: z\n .record(z.string(), z.unknown())\n .describe('A representative input row. The transformation will run against rows of this shape.'),\n targetShape: z\n .unknown()\n .describe(\n 'A JSON example of the desired output shape. Field values are placeholders; the agent infers the structure from this example.',\n ),\n fieldDescriptions: z\n .record(z.string(), z.string())\n .optional()\n .describe('Optional human-readable descriptions for fields the agent might not infer correctly.'),\n notes: z\n .string()\n .optional()\n .describe('Free-form additional context (data quirks, semantics, etc.).'),\n});\n\nexport type MappingAgentInput = z.infer<typeof MappingAgentInputSchema>;\n\n// The agent's payload IS the Prism Config. The model's explanation\n// rides the envelope's `reasoning` field — no wrapper schema.\nexport type MappingAgentOutput = Config;\n\n// ───────────────────────────────────────────────────────────\n// System prompt — role + worked example, nothing else\n// ───────────────────────────────────────────────────────────\n//\n// Per niscorp/STYLE_GUIDE.md: every operation, constraint and gotcha\n// lives in the Prism schema's .describe() calls, and the prompt carries\n// the JSON Schema (OUTPUT_DOC below). If the model gets an op wrong,\n// sharpen the relevant .describe() in @niscorp/prism — do not add prose here.\n\nconst INSTRUCTIONS = `You are the Prism mapping agent. Given a sample input row and a target output shape, produce a Prism Config that maps rows of the input shape into the target shape.\n\nYour envelope's \\`data\\` is the Prism Config; \\`reasoning\\` is a one-sentence explanation of the mapping. The config must validate against the OUTPUT SCHEMA below (every constraint, format rule and example is in the schema's field descriptions).\n\nWorked example (illustrative only — read the schema for op details):\nINPUT { \"sampleInput\": { \"first\": \"Ada\", \"last\": \"Lovelace\" }, \"targetShape\": { \"fullName\": \"\" } }\ndata { \"fullName\": { \"$interpolate\": { \"template\": \"{{f}} {{l}}\", \"values\": { \"f\": { \"$ref\": \"$.first\" }, \"l\": { \"$ref\": \"$.last\" } } } } }`;\n\nconst OUTPUT_DOC = `OUTPUT SCHEMA — your output MUST validate against this JSON Schema:\\n${JSON.stringify(getProfileJsonSchema(MAPPING_OPS, 'draft-7'))}`;\n\n// ───────────────────────────────────────────────────────────\n// Agent definition — the entire public surface\n// ───────────────────────────────────────────────────────────\n\nexport const mappingAgent: AgentDefinition<Config> = defineAgent<Config>({\n id: 'prism.mapping',\n description: 'Generates a Prism transformation config from a sample input row and a target shape.',\n instructions: INSTRUCTIONS,\n // Validated against the FULL grammar — a config using any op is accepted,\n // exactly as before — but documented with the mapping profile: the ops a\n // mapping uses, about 28% less prompt than the whole grammar\n // (schemas/profiles.ts). The heading is cortex's own (context/schema-doc.ts),\n // so the finish protocol's \"OUTPUT SCHEMA\" still names it.\n output: { schema: ConfigSchema, doc: OUTPUT_DOC },\n});\n"]}
1
+ {"version":3,"sources":["../src/agent/mapping-agent.ts"],"names":[],"mappings":";;;;;AAOO,IAAM,uBAAA,GAA0B,EAAE,MAAA,CAAO;AAAA,EAC9C,WAAA,EAAa,CAAA,CACV,MAAA,CAAO,CAAA,CAAE,MAAA,EAAO,EAAG,CAAA,CAAE,OAAA,EAAS,CAAA,CAC9B,QAAA,CAAS,qFAAqF,CAAA;AAAA,EACjG,WAAA,EAAa,CAAA,CACV,OAAA,EAAQ,CACR,QAAA;AAAA,IACC;AAAA,GACF;AAAA,EACF,iBAAA,EAAmB,CAAA,CAChB,MAAA,CAAO,CAAA,CAAE,MAAA,EAAO,EAAG,CAAA,CAAE,MAAA,EAAQ,CAAA,CAC7B,QAAA,EAAS,CACT,SAAS,sFAAsF,CAAA;AAAA,EAClG,OAAO,CAAA,CACJ,MAAA,GACA,QAAA,EAAS,CACT,SAAS,8DAA8D;AAC5E,CAAC;AAMD,IAAM,YAAA,GAAe,CAAA;;AAAA;;AAAA;AAAA;AAAA,6IAAA,CAAA;AAQrB,IAAM,UAAA,GAAa,CAAA;AAAA,EAAwE,KAAK,SAAA,CAAU,oBAAA,CAAqB,WAAA,EAAa,SAAS,CAAC,CAAC,CAAA,CAAA;AAEhJ,IAAM,eAAwC,WAAA,CAAoB;AAAA,EACvE,EAAA,EAAI,eAAA;AAAA,EACJ,WAAA,EAAa,qFAAA;AAAA,EACb,YAAA,EAAc,YAAA;AAAA;AAAA;AAAA;AAAA,EAId,MAAA,EAAQ,EAAE,MAAA,EAAQ,YAAA,EAAc,KAAK,UAAA;AACvC,CAAC","file":"agent.js","sourcesContent":["import { z } from 'zod';\nimport { defineAgent, type AgentDefinition } from '@niscorp/cortex';\n\nimport { ConfigSchema, type Config } from '../schemas';\nimport { MAPPING_OPS } from '../schemas/profiles';\nimport { getProfileJsonSchema } from '../engine/documentation';\n\nexport const MappingAgentInputSchema = z.object({\n sampleInput: z\n .record(z.string(), z.unknown())\n .describe('A representative input row. The transformation will run against rows of this shape.'),\n targetShape: z\n .unknown()\n .describe(\n 'A JSON example of the desired output shape. Field values are placeholders; the agent infers the structure from this example.',\n ),\n fieldDescriptions: z\n .record(z.string(), z.string())\n .optional()\n .describe('Optional human-readable descriptions for fields the agent might not infer correctly.'),\n notes: z\n .string()\n .optional()\n .describe('Free-form additional context (data quirks, semantics, etc.).'),\n});\n\nexport type MappingAgentInput = z.infer<typeof MappingAgentInputSchema>;\n\nexport type MappingAgentOutput = Config;\n\nconst INSTRUCTIONS = `You are the Prism mapping agent. Given a sample input row and a target output shape, produce a Prism Config that maps rows of the input shape into the target shape.\n\nYour envelope's \\`data\\` is the Prism Config; \\`reasoning\\` is a one-sentence explanation of the mapping. The config must validate against the OUTPUT SCHEMA below (every constraint, format rule and example is in the schema's field descriptions).\n\nWorked example (illustrative only — read the schema for op details):\nINPUT { \"sampleInput\": { \"first\": \"Ada\", \"last\": \"Lovelace\" }, \"targetShape\": { \"fullName\": \"\" } }\ndata { \"fullName\": { \"$interpolate\": { \"template\": \"{{f}} {{l}}\", \"values\": { \"f\": { \"$ref\": \"$.first\" }, \"l\": { \"$ref\": \"$.last\" } } } } }`;\n\nconst OUTPUT_DOC = `OUTPUT SCHEMA — your output MUST validate against this JSON Schema:\\n${JSON.stringify(getProfileJsonSchema(MAPPING_OPS, 'draft-7'))}`;\n\nexport const mappingAgent: AgentDefinition<Config> = defineAgent<Config>({\n id: 'prism.mapping',\n description: 'Generates a Prism transformation config from a sample input row and a target shape.',\n instructions: INSTRUCTIONS,\n // Validated against the full grammar, documented with the mapping profile:\n // a config using an op outside the profile is still accepted. The doc keeps\n // cortex's own heading, \"OUTPUT SCHEMA\", which its finish protocol names.\n output: { schema: ConfigSchema, doc: OUTPUT_DOC },\n});\n"]}