@mnmal-ai/substrate-nl 1.0.0-alpha.17 → 1.0.0-alpha.19

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/README.md CHANGED
@@ -4,7 +4,7 @@ Natural-language ask surface. A deterministic parser reads a question against a
4
4
 
5
5
  ## Contract
6
6
 
7
- - `POST /substrate/v1/nl` with `{ namespace, question, project?, type?, asOf? }` returns one of `rows`, `recall`, `clarify` or `refuse`, plus a `trail` of how it got there. Send `accept: text/event-stream` for the same as SSE events (`parsed`, `judging`, `judged`, then the outcome, then `done`), otherwise it is one JSON body.
7
+ - `POST /substrate/v1/nl` with `{ namespace, question, project?, type?, asOf? }` returns one of `rows`, `recall`, `clarify` or `refuse`, plus a `trail` of how it got there. Send `accept: application/vnd.substrate.frames+json` for the same as a stream of length-prefixed JSON frames, each `{ event, data }` (`parsed`, `judging`, `judged`, then the outcome, then `done`; a failure mid-stream is an `error` event). Otherwise it is one JSON body. `+pack` is refused `406 not_acceptable`.
8
8
  - `asOf` is "now" for relative dates ("yesterday", "last week") and for the year of a month-day ("on Oct 23"): an ISO-8601 date-time with an offset, such as `2026-10-02T12:00:00-05:00`. Day boundaries are in its offset. Anything else is `400 invalid_params`. Without it the server clock is used. The `parsed` event's `asOf` says which clock the question was read against.
9
9
  - Aggregates: `average|avg|mean <field>`, `total|sum [of] <field>`, `min|minimum|max|maximum <field>`, each over the seed type with every filter, value and time range the question also names. The field must be a seed number field (min and max also take a date field). An unknown field, a wrong kind or a field on a walked type is dropped with a reason, and the answer is `unknown`. `highest|lowest <field>` is an aggregate only when `of` or `for` follows the field, a type is named after the field, and no type is named before the superlative ("the highest price of items"). Otherwise it orders ("items with the highest price", "items with the highest price for last week"). A recency or limit word inside a count or an aggregate ("the last sale", "the first 3 items") is dropped as a filter, so the answer is `unknown`. So is an aggregate inside a "how many" question. The outcome is `rows` with `answer: 'aggregate'`, the engine's `data`, and `aggregate: { fn, field, value }`. A store that answers no walks, or a seed under a row policy, refuses the frame: `aggregate` is then absent and `errors` says why. Unlike a count, there is no paged fallback.
10
10
  - Grouping an aggregate: `by|per day|hour` groups by the type's time field, truncated to the day or hour through `groupBy` and `dateTrunc` (the `timeField` ruling; without one the grouping is dropped with a reason, since `createdAt` is row metadata and cannot sit inside an expression). `by|per <field>` groups by a seed enum or yes/no field, as one aggregate per value (at most 20) plus one for rows with no value. That last group is keyed `null` and is left out when its value is null. Either one gives `aggregate: { fn, field, by, groups: [{ key, value }], truncated? }`. `week`, `month` and `year` buckets, and grouping by any other field, are dropped with a reason, and the ungrouped value still answers.
@@ -1,9 +1,10 @@
1
1
  import type { NlEvent, NlOutcome } from './events.js';
2
- /** Same headers as substrate-compose's SSE routes (not exported from its entry). */
3
- export declare const SSE_HEADERS: Record<string, string>;
4
- /** One named SSE event. JSON.stringify emits no raw newline, so one data line is safe. */
5
- export declare function sseEvent(name: string, data: unknown): string;
6
- export declare function toSseStream(events: AsyncGenerator<NlEvent>, onCancel?: () => void, onError?: (err: unknown) => void): ReadableStream<Uint8Array>;
2
+ /** One NL event as wire bytes. */
3
+ export type EncodeEvent = (name: string, data: unknown) => Uint8Array;
4
+ /** A length-prefixed JSON frame carrying `{ event, data }`, the client's `NlWireEvent`. */
5
+ export declare const frameBytes: EncodeEvent;
6
+ export declare const FRAMES_HEADERS: Record<string, string>;
7
+ export declare function toEventStream(events: AsyncGenerator<NlEvent>, encode: EncodeEvent, onCancel?: () => void, onError?: (err: unknown) => void): ReadableStream<Uint8Array>;
7
8
  export declare function toJson(events: AsyncGenerator<NlEvent>): Promise<{
8
9
  outcome: NlOutcome | null;
9
10
  trail: NlEvent[];
@@ -1 +1 @@
1
- {"version":3,"file":"encode.d.ts","sourceRoot":"","sources":["../../src/ask/encode.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAEtD,oFAAoF;AACpF,eAAO,MAAM,WAAW,EAAE,MAAM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AAE,SAAS,GAAG,IAAI,CAAC;IAAC,KAAK,EAAE,OAAO,EAAE,CAAA;CAAE,CAAC,CAQ1D"}
@@ -1,6 +1,7 @@
1
1
  import { METADATA_AUTHOR_FIELDS, METADATA_FILTER_FIELDS, ROW_POLICY_BLOCKS_WALK, WALKS_NEED_PARTITIONED, WALKS_UNSUPPORTED_STORE, defineBootstrap, error400, jsonResponse, parseJsonBody, trimTrailingSlashes } from "@mnmal-ai/substrate/sdk";
2
2
  import { z } from "zod";
3
3
  import { createHash } from "node:crypto";
4
+ import { FRAMES_JSON_MIME, encodeStreamFrame, framesEncodingFromAccept } from "@mnmal-ai/substrate/pack";
4
5
 
5
6
  //#region src/own.ts
6
7
  /**
@@ -3486,36 +3487,35 @@ function canonical(v) {
3486
3487
 
3487
3488
  //#endregion
3488
3489
  //#region src/ask/encode.ts
3489
- /** Same headers as substrate-compose's SSE routes (not exported from its entry). */
3490
- const SSE_HEADERS = {
3491
- "content-type": "text/event-stream",
3492
- "cache-control": "no-store",
3493
- "x-accel-buffering": "no"
3494
- };
3495
- /** One named SSE event. JSON.stringify emits no raw newline, so one data line is safe. */
3496
- function sseEvent(name, data) {
3497
- return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
3498
- }
3499
3490
  function wireName(ev) {
3500
3491
  if (ev.event === "outcome") return [ev.outcome.kind, ev.outcome];
3501
3492
  const { event, ...rest } = ev;
3502
3493
  return [event, rest];
3503
3494
  }
3504
- function toSseStream(events, onCancel, onError) {
3505
- const enc = new TextEncoder();
3495
+ /** A length-prefixed JSON frame carrying `{ event, data }`, the client's `NlWireEvent`. */
3496
+ const frameBytes = (event, data) => encodeStreamFrame({
3497
+ event,
3498
+ data
3499
+ }, "json");
3500
+ const FRAMES_HEADERS = {
3501
+ "content-type": FRAMES_JSON_MIME,
3502
+ "cache-control": "no-store",
3503
+ "x-accel-buffering": "no"
3504
+ };
3505
+ function toEventStream(events, encode, onCancel, onError) {
3506
3506
  return new ReadableStream({
3507
3507
  async pull(controller) {
3508
3508
  try {
3509
3509
  const next = await events.next();
3510
3510
  if (next.done === true) return controller.close();
3511
3511
  const [name, data] = wireName(next.value);
3512
- controller.enqueue(enc.encode(sseEvent(name, data)));
3512
+ controller.enqueue(encode(name, data));
3513
3513
  } catch (err) {
3514
3514
  onError?.(err);
3515
- controller.enqueue(enc.encode(sseEvent("error", {
3515
+ controller.enqueue(encode("error", {
3516
3516
  code: "nl_engine_error",
3517
3517
  message: "NL query failed"
3518
- })));
3518
+ }));
3519
3519
  controller.close();
3520
3520
  }
3521
3521
  },
@@ -3585,6 +3585,11 @@ function askHandler(deps) {
3585
3585
  code: "nl_unknown_namespace"
3586
3586
  });
3587
3587
  if (ask.type !== void 0 && !Object.hasOwn(served.pack.types, ask.type)) return error400(`unknown type '${ask.type}'`);
3588
+ const frames = framesEncodingFromAccept(req.headers.accept);
3589
+ if (frames === "pack") return jsonResponse(406, {
3590
+ error: `NL streams ${FRAMES_JSON_MIME} only`,
3591
+ code: "not_acceptable"
3592
+ });
3588
3593
  const events = runAsk(ask, req, {
3589
3594
  pack: served.pack,
3590
3595
  engine: deps.engine,
@@ -3592,10 +3597,10 @@ function askHandler(deps) {
3592
3597
  ...deps.judgeTimeoutMs !== void 0 ? { judgeTimeoutMs: deps.judgeTimeoutMs } : {},
3593
3598
  ...deps.now !== void 0 ? { now: deps.now } : {}
3594
3599
  });
3595
- if ((req.headers.accept ?? "").toLowerCase().includes("text/event-stream")) return {
3600
+ if (frames === "json") return {
3596
3601
  status: 200,
3597
- headers: SSE_HEADERS,
3598
- body: toSseStream(events, void 0, log)
3602
+ headers: FRAMES_HEADERS,
3603
+ body: toEventStream(events, frameBytes, void 0, log)
3599
3604
  };
3600
3605
  try {
3601
3606
  return jsonResponse(200, await toJson(events));
package/dist/bootstrap.js CHANGED
@@ -1,3 +1,3 @@
1
- import { n as bootstrap, t as NlBootstrapConfigSchema } from "./bootstrap-DZv1ymCg.js";
1
+ import { n as bootstrap, t as NlBootstrapConfigSchema } from "./bootstrap-Cla0ceiy.js";
2
2
 
3
3
  export { NlBootstrapConfigSchema, bootstrap, bootstrap as default };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as askHandler, c as profileNamespace, d as runAsk, f as parseWithJudge, g as readRulings, h as mergeRulings, i as createNlPlugin, l as buildNamespacePack, m as NamespaceRulingsSchema, n as bootstrap, o as packHandler, p as parseQuestion, r as CONTRACT_VERSION, s as PackService, t as NlBootstrapConfigSchema, u as OllamaJudge } from "./bootstrap-DZv1ymCg.js";
1
+ import { a as askHandler, c as profileNamespace, d as runAsk, f as parseWithJudge, g as readRulings, h as mergeRulings, i as createNlPlugin, l as buildNamespacePack, m as NamespaceRulingsSchema, n as bootstrap, o as packHandler, p as parseQuestion, r as CONTRACT_VERSION, s as PackService, t as NlBootstrapConfigSchema, u as OllamaJudge } from "./bootstrap-Cla0ceiy.js";
2
2
  import { complete } from "./complete.js";
3
3
 
4
4
  export { CONTRACT_VERSION, NamespaceRulingsSchema, NlBootstrapConfigSchema, OllamaJudge, PackService, askHandler, bootstrap, buildNamespacePack, complete, createNlPlugin, mergeRulings, packHandler, parseQuestion, parseWithJudge, profileNamespace, readRulings, runAsk };
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAqB,MAAM,yBAAyB,CAAC;AAE9E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAIlD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGrD,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,cAAc,CAAC;IACvB,KAAK,EAAE,WAAW,CAAC;IACnB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;IACjB,6EAA6E;IAC7E,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAC;CAC9B;AAkBD,wBAAgB,UAAU,CAAC,IAAI,EAAE,WAAW,GAAG,WAAW,CA8DzD;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,WAAW,GAAG,WAAW,CAwB1D"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAqB,MAAM,yBAAyB,CAAC;AAE9E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAIlD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGrD,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,cAAc,CAAC;IACvB,KAAK,EAAE,WAAW,CAAC;IACnB,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC;IACjB,6EAA6E;IAC7E,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAC;CAC9B;AAkBD,wBAAgB,UAAU,CAAC,IAAI,EAAE,WAAW,GAAG,WAAW,CAwEzD;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,WAAW,GAAG,WAAW,CAwB1D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mnmal-ai/substrate-nl",
3
- "version": "1.0.0-alpha.17",
3
+ "version": "1.0.0-alpha.19",
4
4
  "description": "Natural-language questions for Substrate — a deterministic parser with an optional constrained judge, served at POST /substrate/v1/nl and GET /substrate/v1/nl/pack/:ns, plus browser-safe completion.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -37,15 +37,15 @@
37
37
  },
38
38
  "devDependencies": {
39
39
  "@biomejs/biome": "2.6.4",
40
- "@mnmal-ai/substrate": "1.0.0-alpha.17",
41
- "@mnmal-ai/substrate-config": "1.0.0-alpha.17",
40
+ "@mnmal-ai/substrate": "1.0.0-alpha.19",
41
+ "@mnmal-ai/substrate-config": "1.0.0-alpha.19",
42
42
  "@types/node": "^26.6.4",
43
43
  "tsdown": "^0.23.0",
44
44
  "typescript": "^7.0.2",
45
45
  "vitest": "^5.0.3"
46
46
  },
47
47
  "peerDependencies": {
48
- "@mnmal-ai/substrate": ">=1.0.0-alpha.11 <2.0.0"
48
+ "@mnmal-ai/substrate": ">=1.0.0-alpha.19 <2.0.0"
49
49
  },
50
50
  "engines": {
51
51
  "node": ">=26.13.1"