@mnmal-ai/substrate-nl 1.0.0-alpha.9 → 1.0.0-beta.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.
@@ -1,1862 +0,0 @@
1
- import { defineBootstrap, error400, jsonResponse, parseJsonBody, trimTrailingSlashes } from "@mnmal-ai/substrate/sdk";
2
- import { z } from "zod";
3
- import { createHash } from "node:crypto";
4
-
5
- //#region src/own.ts
6
- /**
7
- * A lookup into a plain-object record by a user-supplied key. Inherited
8
- * names (`constructor`, `__proto__`, `toString`) are not entries.
9
- */
10
- function own(rec, key) {
11
- return rec !== void 0 && Object.hasOwn(rec, key) ? rec[key] : void 0;
12
- }
13
-
14
- //#endregion
15
- //#region src/pack/words.ts
16
- /** `AgentMessage` -> ['agent', 'message']; `shortId` -> ['short', 'id']. */
17
- function splitWords(name) {
18
- return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/[\s_-]+/).filter((w) => w.length > 0);
19
- }
20
- /** English plural for a lower-case noun, by suffix rule. */
21
- function pluralize(word) {
22
- if (/(s|x|z|ch|sh)$/.test(word)) return `${word}es`;
23
- if (/[^aeiou]y$/.test(word)) return `${word.slice(0, -1)}ies`;
24
- return `${word}s`;
25
- }
26
- /** Sorted, de-duplicated. */
27
- function uniqueSorted(xs) {
28
- return [...new Set(xs)].sort();
29
- }
30
-
31
- //#endregion
32
- //#region src/parse/time.ts
33
- const WEEKDAYS = [
34
- "sunday",
35
- "monday",
36
- "tuesday",
37
- "wednesday",
38
- "thursday",
39
- "friday",
40
- "saturday"
41
- ];
42
- /**
43
- * The range a time phrase names, relative to `asOf` and in its offset:
44
- * today, yesterday, this/last week (weeks start Monday), this/last month,
45
- * rolling "past <unit>" and "last N <units>", "since <weekday>". Null when
46
- * the phrase is not a time phrase.
47
- */
48
- function rangeFor(phrase, asOf) {
49
- const m = /^(\d{4})-(\d{2})-(\d{2})T[\d:.]+(Z|[+-]\d{2}:\d{2})$/.exec(asOf);
50
- if (m === null) throw new Error(`asOf must be ISO-8601 with an offset: ${asOf}`);
51
- const [, y, mo, d, offset] = m;
52
- const today = Date.UTC(Number(y), Number(mo) - 1, Number(d));
53
- const day = 864e5;
54
- const at = (utcMidnight) => `${new Date(utcMidnight).toISOString().slice(0, 10)}T00:00:00${offset === "Z" ? "Z" : offset}`;
55
- const weekday = new Date(today).getUTCDay();
56
- const monday = today - (weekday + 6) % 7 * day;
57
- const monthStart = Date.UTC(Number(y), Number(mo) - 1, 1);
58
- const nextMonth = Date.UTC(Number(y), Number(mo), 1);
59
- const lastMonth = Date.UTC(Number(y), Number(mo) - 2, 1);
60
- switch (phrase) {
61
- case "today": return {
62
- gte: at(today),
63
- lt: at(today + day)
64
- };
65
- case "yesterday": return {
66
- gte: at(today - day),
67
- lt: at(today)
68
- };
69
- case "this week": return {
70
- gte: at(monday),
71
- lt: at(monday + 7 * day)
72
- };
73
- case "last week": return {
74
- gte: at(monday - 7 * day),
75
- lt: at(monday)
76
- };
77
- case "this month": return {
78
- gte: at(monthStart),
79
- lt: at(nextMonth)
80
- };
81
- case "last month": return {
82
- gte: at(lastMonth),
83
- lt: at(monthStart)
84
- };
85
- }
86
- const rolling = /^(?:past|last) (\d+ )?(day|week|month|year)s?$/.exec(phrase);
87
- if (rolling !== null && (rolling[1] !== void 0 || phrase.startsWith("past"))) {
88
- const n = rolling[1] === void 0 ? 1 : Number(rolling[1]);
89
- const unit = rolling[2];
90
- const back = new Date(today);
91
- if (unit === "day") back.setUTCDate(back.getUTCDate() - n);
92
- if (unit === "week") back.setUTCDate(back.getUTCDate() - 7 * n);
93
- if (unit === "month") back.setUTCMonth(back.getUTCMonth() - n);
94
- if (unit === "year") back.setUTCFullYear(back.getUTCFullYear() - n);
95
- return {
96
- gte: at(back.getTime()),
97
- lt: at(today + day)
98
- };
99
- }
100
- const since = /^since (\w+)$/.exec(phrase);
101
- if (since !== null) {
102
- const target = WEEKDAYS.indexOf(since[1]);
103
- if (target < 0) return null;
104
- return {
105
- gte: at(today - (weekday - target + 7) % 7 * day),
106
- lt: at(today + day)
107
- };
108
- }
109
- return null;
110
- }
111
-
112
- //#endregion
113
- //#region src/parse/parse.ts
114
- /** Words that carry no query meaning on their own. */
115
- const GLUE = new Set("a about again all am an and any anything are as at be been by can could current did do does for from get give go got have hey i i'm in is it it's let let's lets list me more my need needs next now of ok on or our please raised see show so some still talk tell that the their them there these this those to us want was we we've we'd what what's whats when where which who whose why will with would you your yo up thought handled judgement judgment make nice there's anymore stuff things few runs run lives wrote write written created made filed logged".split(/\s+/));
116
- /** First word of an imperative edit, which substrate-nl refuses: it only reads. */
117
- const MUTATIONS = new Set("close delete remove archive merge approve approved create add update set mark rename reopen assign ack deploy cut land".split(" "));
118
- const LEADING_FILLER = new Set("please can could would you go ahead let let's lets hey ok yo so and then".split(" "));
119
- const STATE_CUES = new Set("what what's whats show talk tell status is describe about see which who".split(" "));
120
- const CLOSE_VERBS = new Set("close closed closing done finished completed resolved ship shipped drop dropped cancel cancelled abandoned".split(" "));
121
- const UPDATE_VERBS = new Set("updated changed edited touched".split(" "));
122
- /** Terminal status values: matching one is a question about the past. */
123
- const TERMINAL = [
124
- "closed",
125
- "complete",
126
- "completed",
127
- "done",
128
- "resolved",
129
- "superseded"
130
- ];
131
- /** Terminal statuses a closing verb selects: finished, not merely replaced. */
132
- const CLOSED = [
133
- "closed",
134
- "complete",
135
- "completed",
136
- "done",
137
- "resolved"
138
- ];
139
- const HISTORY_WORDS = new Set("archived archive history historical ever previously past trend trends over-time all-time total".split(" "));
140
- const LATEST = new Set("latest newest recent last".split(" "));
141
- const OLDEST = new Set("oldest earliest first".split(" "));
142
- const AUTHOR_VERBS = new Set("raised created written filed authored opened made sent logged".split(" "));
143
- const BUILTIN_FIELD_ALIASES = { author: "createdById" };
144
- /** `field:value`, `field:[a,b]`, `field:"two words"`; optionally wrapped in quotes. A clock time starts with a digit. */
145
- const CLAUSE = /(['"]?)\b([A-Za-z][A-Za-z0-9]*):(\[[^\]]*\]|"[^"]*"|[^\s,'"]+)\1/g;
146
- function parseClause(span, field, raw) {
147
- const unquote = (v) => v.trim().replace(/^["']|["']$/g, "");
148
- if (raw.startsWith("[")) return {
149
- span,
150
- field,
151
- op: "in",
152
- values: raw.slice(1, -1).split(",").map(unquote).filter((v) => v.length > 0)
153
- };
154
- if (raw.startsWith("\"")) return {
155
- span,
156
- field,
157
- op: "eq",
158
- values: [unquote(raw)]
159
- };
160
- const cmp = /^(>=|<=|>|<)(.+)$/.exec(raw);
161
- if (cmp !== null) return {
162
- span,
163
- field,
164
- op: {
165
- ">": "gt",
166
- ">=": "gte",
167
- "<": "lt",
168
- "<=": "lte"
169
- }[cmp[1]],
170
- values: [cmp[2]]
171
- };
172
- const range = /^(.+)\.\.(.+)$/.exec(raw);
173
- if (range !== null) return {
174
- span,
175
- field,
176
- op: "between",
177
- values: [range[1], range[2]]
178
- };
179
- if (raw.startsWith("!")) return {
180
- span,
181
- field,
182
- op: "neq",
183
- values: [raw.slice(1)]
184
- };
185
- if (raw.startsWith("~")) return {
186
- span,
187
- field,
188
- op: "contains",
189
- values: [raw.slice(1)]
190
- };
191
- return {
192
- span,
193
- field,
194
- op: "eq",
195
- values: [raw]
196
- };
197
- }
198
- function parseQuestion(question, pack, ctx) {
199
- const rulings = ctx.rulings ?? {};
200
- const clauses = [];
201
- const tokens = (question.replace(CLAUSE, (span, _q, field, raw) => {
202
- clauses.push(parseClause(span, field, raw));
203
- return " ";
204
- }).toLowerCase().replace(/[‘’]/g, "'").match(/#\d+|[a-z0-9@[][a-z0-9@._'\]-]*/g) ?? []).map((t) => t.replace(/[.'-]+$/, "").replace(/'s$/, "")).filter((t) => t.length > 0).map((text) => ({
205
- text,
206
- used: false
207
- }));
208
- const words = tokens.map((t) => t.text);
209
- const evidence = [];
210
- const lead = words.find((w) => !LEADING_FILLER.has(w));
211
- if (lead !== void 0 && MUTATIONS.has(lead)) return {
212
- status: "refuse",
213
- candidates: [],
214
- residual: [],
215
- reason: `"${lead}" is an edit; substrate-nl answers questions and does not change data`
216
- };
217
- const values = [];
218
- claimNgrams(tokens, 4, (key, at) => {
219
- const alias = own(rulings.valueAliases, key);
220
- if (alias === void 0) return false;
221
- values.push({
222
- span: key,
223
- key: null,
224
- alias,
225
- at
226
- });
227
- return true;
228
- });
229
- const mentioned = /* @__PURE__ */ new Map();
230
- for (const entry of buildTypeIndex(pack, rulings)) {
231
- const n = entry.phrase.split(" ").length;
232
- for (let i = 0; i + n <= tokens.length; i++) {
233
- const slice = tokens.slice(i, i + n);
234
- if (slice.some((t) => t.used) || slice.map((t) => t.text).join(" ") !== entry.phrase) continue;
235
- for (const t of slice) t.used = true;
236
- for (const type of entry.types) mentioned.set(type, {
237
- span: entry.phrase,
238
- plural: entry.plural
239
- });
240
- }
241
- }
242
- for (const [type, m] of mentioned) evidence.push({
243
- span: m.span,
244
- role: "type",
245
- detail: type
246
- });
247
- const time = claimTime(tokens, ctx.asOf);
248
- if (time !== null) evidence.push({
249
- span: time.span,
250
- role: "time",
251
- detail: `${time.range.gte} .. ${time.range.lt}`
252
- });
253
- const ids = [];
254
- let bareNumber = false;
255
- tokens.forEach((t, i) => {
256
- if (t.used) return;
257
- if (/^#\d+$/.test(t.text)) {
258
- ids.push(Number(t.text.slice(1)));
259
- t.used = true;
260
- evidence.push({
261
- span: t.text,
262
- role: "id",
263
- detail: "shortId"
264
- });
265
- } else if (/^\d+$/.test(t.text)) {
266
- if (tokens[i - 1]?.used === true && mentioned.size > 0) {
267
- ids.push(Number(t.text));
268
- t.used = true;
269
- evidence.push({
270
- span: t.text,
271
- role: "id",
272
- detail: "shortId"
273
- });
274
- } else bareNumber = true;
275
- }
276
- });
277
- let order = null;
278
- let count = false;
279
- let allProjects = false;
280
- let historyWord = false;
281
- const singularMention = [...mentioned.values()].some((m) => !m.plural);
282
- tokens.forEach((t, i) => {
283
- if (t.used) return;
284
- const next = tokens[i + 1];
285
- if (LATEST.has(t.text) || t.text === "most" && /^recent(ly)?$/.test(next?.text ?? "") || t.text === "current" && singularMention) {
286
- order = "desc";
287
- t.used = true;
288
- if (t.text === "most" && next !== void 0) next.used = true;
289
- evidence.push({
290
- span: t.text,
291
- role: "order",
292
- detail: "createdAt desc, limit 1"
293
- });
294
- } else if (OLDEST.has(t.text)) {
295
- order = "asc";
296
- t.used = true;
297
- evidence.push({
298
- span: t.text,
299
- role: "order",
300
- detail: "createdAt asc, limit 1"
301
- });
302
- } else if (t.text === "how" && next?.text === "many") {
303
- count = true;
304
- t.used = true;
305
- next.used = true;
306
- evidence.push({
307
- span: "how many",
308
- role: "count",
309
- detail: "answer = count"
310
- });
311
- } else if ((t.text === "every" || t.text === "all") && /^projects?$/.test(next?.text ?? "")) {
312
- allProjects = true;
313
- t.used = true;
314
- next.used = true;
315
- evidence.push({
316
- span: `${t.text} ${next?.text}`,
317
- role: "scope",
318
- detail: "no project scope"
319
- });
320
- } else if (t.text === "across") {
321
- allProjects = true;
322
- t.used = true;
323
- } else if (HISTORY_WORDS.has(t.text)) {
324
- historyWord = true;
325
- t.used = true;
326
- evidence.push({
327
- span: t.text,
328
- role: "history",
329
- detail: "search the whole record"
330
- });
331
- }
332
- });
333
- let author = null;
334
- tokens.forEach((t, i) => {
335
- const prev = tokens[i - 1];
336
- const next = tokens[i + 1];
337
- if (t.text === "by" && prev !== void 0 && AUTHOR_VERBS.has(prev.text) && next !== void 0) {
338
- author = next.text;
339
- for (const x of [
340
- prev,
341
- t,
342
- next
343
- ]) x.used = true;
344
- } else if (t.text === "sent" && prev !== void 0 && !GLUE.has(prev.text) && !prev.used) {
345
- author = prev.text;
346
- prev.used = true;
347
- t.used = true;
348
- }
349
- });
350
- if (author !== null) evidence.push({
351
- span: author,
352
- role: "author",
353
- detail: `createdById startsWith ${author}`
354
- });
355
- const fieldAliases = {
356
- ...BUILTIN_FIELD_ALIASES,
357
- ...rulings.fieldAliases ?? {}
358
- };
359
- let askField = null;
360
- tokens.forEach((t, i) => {
361
- if (t.used || tokens[i - 1]?.text !== "which") return;
362
- for (const form of [t.text, t.text.replace(/s$/, "")]) {
363
- const field = own(fieldAliases, form) ?? (fieldNamed(pack, form) ? form : null);
364
- if (field === null) continue;
365
- askField = {
366
- field,
367
- group: form !== t.text
368
- };
369
- t.used = true;
370
- evidence.push({
371
- span: t.text,
372
- role: "field",
373
- detail: askField.group ? `group by ${field}` : `answer = ${field}`
374
- });
375
- return;
376
- }
377
- });
378
- const flagClaims = /* @__PURE__ */ new Map();
379
- for (const type of mentioned.keys()) for (const [name, f] of Object.entries(own(pack.types, type)?.fields ?? {})) {
380
- if (f.valueType !== "boolean" || name === "archived") continue;
381
- const t = tokens.find((x) => !x.used && f.phrases.includes(x.text));
382
- if (t === void 0) continue;
383
- t.used = true;
384
- flagClaims.set(type, [...flagClaims.get(type) ?? [], {
385
- span: t.text,
386
- role: "value",
387
- detail: name
388
- }]);
389
- }
390
- claimNgrams(tokens, 4, (key, at) => {
391
- if (at.length === 1 && GLUE.has(key)) return false;
392
- if (at.length === 1 && CLOSE_VERBS.has(key)) return false;
393
- const found = own(pack.values, key) !== void 0 ? key : at.length === 1 && /[^s]s$/.test(key) && own(pack.values, key.slice(0, -1)) !== void 0 ? key.slice(0, -1) : null;
394
- if (found === null) return false;
395
- values.push({
396
- span: key,
397
- key: found,
398
- at
399
- });
400
- return true;
401
- });
402
- const closeVerb = words.some((w) => CLOSE_VERBS.has(w));
403
- const updateVerb = words.some((w) => UPDATE_VERBS.has(w));
404
- for (const t of tokens) if (CLOSE_VERBS.has(t.text) || UPDATE_VERBS.has(t.text)) t.used = true;
405
- let types = [...mentioned.keys()].sort();
406
- if (ctx.forceType !== void 0 && own(pack.types, ctx.forceType) !== void 0) {
407
- types = [ctx.forceType];
408
- if (!mentioned.has(ctx.forceType)) evidence.push({
409
- span: "",
410
- role: "type",
411
- detail: ctx.forceType
412
- });
413
- }
414
- if (types.length === 0 && ids.length > 0 && ctx.defaultIdType !== void 0) types = [ctx.defaultIdType];
415
- if (types.length === 0 && values.length > 0) {
416
- types = typesCovering(pack, values);
417
- const live = types.filter((t) => values.some((v) => v.key !== null && v.key === own(rulings.liveStatus, t)));
418
- if (types.length > 1 && live.length > 0) types = live;
419
- }
420
- if (types.length === 0 && clauses.length > 0) types = typesWithFields(pack, clauses, rulings);
421
- if (types.length === 0 && closeVerb) types = closableTypes(pack);
422
- const named = mentioned.size > 0 || ctx.forceType !== void 0;
423
- if (bareNumber && ids.length === 0 && !named) return {
424
- status: "clarify",
425
- candidates: [],
426
- residual: [],
427
- reason: "a bare number with no type"
428
- };
429
- if (ids.length > 0 && !named && !words.some((w) => STATE_CUES.has(w))) return {
430
- status: "clarify",
431
- candidates: [],
432
- residual: [],
433
- reason: "#N with no question about it: a Todo or a PR?"
434
- };
435
- if (types.length === 0) return {
436
- status: "unparsed",
437
- candidates: [],
438
- evidence,
439
- residual: contentWords(tokens),
440
- reason: "no type, id or known value"
441
- };
442
- const candidates = [];
443
- const ruledOut = [];
444
- for (const type of types) {
445
- const c = assemble(type, {
446
- pack,
447
- ctx,
448
- tokens: tokens.map((t) => ({ ...t })),
449
- evidence: evidence.filter((e) => e.role !== "type" || e.detail === type),
450
- ids,
451
- values,
452
- clauses,
453
- time,
454
- order,
455
- count,
456
- allProjects,
457
- historyWord,
458
- flags: flagClaims.get(type) ?? [],
459
- author,
460
- askField,
461
- closeVerb,
462
- updateVerb
463
- });
464
- if ("reason" in c) ruledOut.push(`${type}: ${c.reason}`);
465
- else candidates.push(c);
466
- }
467
- if (candidates.length === 0) {
468
- const reason = ruledOut.length > 0 ? ruledOut.join("; ") : "no type fits every value";
469
- return {
470
- status: "unparsed",
471
- candidates,
472
- evidence,
473
- residual: contentWords(tokens),
474
- reason
475
- };
476
- }
477
- if (candidates.length > 1) return {
478
- status: "ambiguous",
479
- candidates,
480
- residual: [],
481
- reason: `${candidates.length} readings`
482
- };
483
- const only = candidates[0];
484
- if (only.residual.length > 0 && ids.length === 0) return {
485
- status: "partial",
486
- candidates,
487
- residual: only.residual,
488
- reason: `unexplained: ${only.residual.join(", ")}`
489
- };
490
- return {
491
- status: "resolved",
492
- candidates,
493
- residual: only.residual
494
- };
495
- }
496
- /** One reading of the question as `type`, or why there is none. */
497
- function assemble(type, a) {
498
- const { pack, ctx, tokens } = a;
499
- const rulings = ctx.rulings ?? {};
500
- const fields = own(pack.types, type)?.fields ?? {};
501
- const words = tokens.map((t) => t.text);
502
- const ev = [...a.evidence];
503
- const where = [];
504
- if (a.ids.length > 0) where.push({ shortId: a.ids.length === 1 ? { eq: a.ids[0] } : { in: a.ids } });
505
- const byField = /* @__PURE__ */ new Map();
506
- const usedFields = /* @__PURE__ */ new Set();
507
- let terminal = false;
508
- for (const v of a.ids.length > 0 ? [] : a.values) {
509
- if (v.alias !== void 0) {
510
- const hit = v.alias.find((x) => x.type === type);
511
- if (hit === void 0) return { reason: `"${v.span}" does not apply to ${type}` };
512
- const op = hit.in !== void 0 ? { in: hit.in } : hit.eq !== void 0 ? { eq: hit.eq } : hit.startsWith !== void 0 ? { startsWith: hit.startsWith } : { contains: hit.contains };
513
- where.push({ [hit.field]: op });
514
- usedFields.add(hit.field);
515
- ev.push({
516
- span: v.span,
517
- role: "value",
518
- detail: `${hit.field} ${JSON.stringify(op)}`
519
- });
520
- continue;
521
- }
522
- const refs = (own(a.pack.values, v.key) ?? []).filter((r) => r.type === type);
523
- if (refs.length === 0) return { reason: `"${v.span}" is not a ${type} value` };
524
- const field = pickField(refs.map((r) => r.field), fields, words);
525
- const stored = refs.find((r) => r.field === field)?.value ?? v.key;
526
- if (TERMINAL.includes(stored)) terminal = true;
527
- byField.set(field, [...byField.get(field) ?? [], stored]);
528
- usedFields.add(field);
529
- ev.push({
530
- span: v.span,
531
- role: "value",
532
- detail: `${field} = ${stored}`
533
- });
534
- }
535
- for (const [field, vals] of [...byField].sort(([x], [y]) => x.localeCompare(y))) if (fields[field]?.kind === "list") for (const v of vals) where.push({ [field]: { has: v } });
536
- else where.push({ [field]: vals.length === 1 ? { eq: vals[0] } : { in: vals } });
537
- for (const c of a.clauses) {
538
- const name = resolveField(c.field, fields, rulings);
539
- const f = name === null ? void 0 : fields[name];
540
- if (name === null || f === void 0) return { reason: `${type} has no field "${c.field}"` };
541
- if (!f.operators.includes(c.op)) return { reason: `${name} does not accept ${c.op}` };
542
- const coerced = c.values.map((v) => coerce(v, f));
543
- if (coerced.some((v) => v === void 0)) return { reason: `"${c.span}" is not a ${f.valueType} value` };
544
- const operand = c.op === "in" || c.op === "between" ? coerced : coerced[0];
545
- where.push({ [name]: { [c.op]: operand } });
546
- usedFields.add(name);
547
- ev.push({
548
- span: c.span,
549
- role: "value",
550
- detail: `${name} ${c.op} ${JSON.stringify(operand)} (inline)`
551
- });
552
- }
553
- for (const field of usedFields) creditFieldWords(tokens, fields[field]);
554
- if (a.author !== null) where.push({ createdById: { startsWith: a.author } });
555
- for (const flag of a.flags) {
556
- usedFields.add(flag.detail);
557
- where.push({ [flag.detail]: { eq: true } });
558
- ev.push({
559
- ...flag,
560
- detail: `${flag.detail} = true`
561
- });
562
- }
563
- for (const [name, f] of Object.entries(fields)) {
564
- if (f.valueType !== "boolean" || name === "archived" || usedFields.has(name)) continue;
565
- const t = tokens.find((x) => !x.used && f.phrases.includes(x.text));
566
- if (t === void 0) continue;
567
- t.used = true;
568
- usedFields.add(name);
569
- where.push({ [name]: { eq: true } });
570
- ev.push({
571
- span: t.text,
572
- role: "value",
573
- detail: `${name} = true`
574
- });
575
- }
576
- const historical = a.historyWord || a.time !== null || a.closeVerb || terminal;
577
- if (a.time !== null) {
578
- const dateField = Object.entries(fields).find(([, f]) => f.valueType === "date" && f.kind !== "metadata" && creditFieldWords(tokens, f))?.[0] ?? (a.closeVerb || a.updateVerb ? "updatedAt" : own(rulings.timeField, type) ?? "createdAt");
579
- where.push({ [dateField]: {
580
- gte: a.time.range.gte,
581
- lt: a.time.range.lt
582
- } });
583
- }
584
- if (a.ids.length === 0) {
585
- const statusField = fields.status;
586
- const live = own(rulings.liveStatus, type);
587
- if (a.closeVerb && statusField?.enum !== void 0 && !byField.has("status")) {
588
- const closed = statusField.enum.filter((s) => CLOSED.includes(s));
589
- if (closed.length > 0) where.push({ status: { in: closed } });
590
- } else if (!historical && live !== void 0 && statusField?.enum?.includes(live) === true && !usedFields.has("status") && a.order === null) where.push({ status: { eq: live } });
591
- if (!historical && fields.archived !== void 0) where.push({ archived: { eq: false } });
592
- else if (historical) ev.push({
593
- span: "(history)",
594
- role: "history",
595
- detail: "archived rows included"
596
- });
597
- if (fields.active?.valueType === "boolean" && !usedFields.has("active") && !words.includes("inactive")) where.push({ active: { eq: true } });
598
- const scoped = fields.project !== void 0 && !(rulings.unscopedTypes ?? []).includes(type);
599
- const groupedByProject = a.askField?.group === true && a.askField.field === "project";
600
- if (scoped && !usedFields.has("project") && !a.allProjects && !groupedByProject && ctx.project !== void 0) {
601
- where.push({ OR: [{ project: { eq: ctx.project } }, { project: { eq: null } }] });
602
- ev.push({
603
- span: "(context)",
604
- role: "scope",
605
- detail: `project = ${ctx.project} or none`
606
- });
607
- }
608
- }
609
- const params = {};
610
- if (where.length === 1) params.where = where[0];
611
- else if (where.length > 1) params.where = { AND: where };
612
- if (a.order !== null) {
613
- params.orderBy = [{ createdAt: a.order }];
614
- params.limit = 1;
615
- }
616
- const answer = a.askField !== null ? a.askField.group ? `group:${a.askField.field}` : `field:${a.askField.field}` : a.count ? "count" : a.order !== null || a.ids.length === 1 ? "single" : "rows";
617
- return {
618
- type,
619
- frame: { [`${pack.namespace}/${type}`]: { params } },
620
- answer,
621
- evidence: ev,
622
- residual: contentWords(tokens)
623
- };
624
- }
625
- /** A clause's field name: the field itself, case-insensitively, then the rulings' and built-in aliases. */
626
- function resolveField(raw, fields, rulings) {
627
- const lower = raw.toLowerCase();
628
- const direct = Object.keys(fields).find((f) => f.toLowerCase() === lower);
629
- if (direct !== void 0) return direct;
630
- const aliased = own(rulings.fieldAliases, lower) ?? own(BUILTIN_FIELD_ALIASES, lower);
631
- return aliased !== void 0 && Object.hasOwn(fields, aliased) ? aliased : null;
632
- }
633
- /** A clause value as the field's type, or undefined when it is not one. */
634
- function coerce(raw, f) {
635
- if (f.valueType === "number") {
636
- const n = Number(raw);
637
- return Number.isFinite(n) ? n : void 0;
638
- }
639
- if (f.valueType === "boolean") return raw === "true" ? true : raw === "false" ? false : void 0;
640
- return raw;
641
- }
642
- /** Types that have every field the clauses name, sorted. */
643
- function typesWithFields(pack, clauses, rulings) {
644
- return Object.entries(pack.types).filter(([, t]) => clauses.every((c) => resolveField(c.field, t.fields, rulings) !== null)).map(([name]) => name).sort();
645
- }
646
- /** Marks unused tokens naming `field` as explained; true when any did. */
647
- function creditFieldWords(tokens, field) {
648
- if (field === void 0) return false;
649
- let hit = false;
650
- for (const phrase of field.phrases) {
651
- const parts = phrase.split(" ");
652
- const stem = (parts[parts.length - 1] ?? "").replace(/s$/, "");
653
- for (let i = 0; i + parts.length <= tokens.length; i++) {
654
- const slice = tokens.slice(i, i + parts.length);
655
- if (slice.some((t) => t.used)) continue;
656
- const text = slice.map((t) => t.text).join(" ");
657
- const last = slice[slice.length - 1]?.text ?? "";
658
- const head = slice.slice(0, -1).map((t) => t.text).join(" ");
659
- const headWant = parts.slice(0, -1).join(" ");
660
- if (text === phrase || head === headWant && stem.length >= 3 && last.startsWith(stem)) {
661
- for (const t of slice) t.used = true;
662
- hit = true;
663
- }
664
- }
665
- }
666
- return hit;
667
- }
668
- function contentWords(tokens) {
669
- return tokens.filter((t) => !t.used && !GLUE.has(t.text) && !/^\d+$/.test(t.text)).map((t) => t.text);
670
- }
671
- /** Claims the longest n-grams (up to `max` words) for which `accept` returns true. */
672
- function claimNgrams(tokens, max, accept) {
673
- for (let n = max; n >= 1; n--) for (let i = 0; i + n <= tokens.length; i++) {
674
- const slice = tokens.slice(i, i + n);
675
- if (slice.some((t) => t.used)) continue;
676
- const at = slice.map((_, j) => i + j);
677
- if (!accept(slice.map((t) => t.text).join(" "), at)) continue;
678
- for (const t of slice) t.used = true;
679
- }
680
- }
681
- /** Type phrases: rulings aliases, then the pack's, plus each multi-word type's first word. Longest first. */
682
- function buildTypeIndex(pack, rulings) {
683
- const map = /* @__PURE__ */ new Map();
684
- const add = (phrase, type, plural) => {
685
- const e = map.get(phrase) ?? {
686
- types: /* @__PURE__ */ new Set(),
687
- plural
688
- };
689
- e.types.add(type);
690
- map.set(phrase, e);
691
- };
692
- const aliased = new Set(Object.keys(rulings.typeAliases ?? {}));
693
- for (const [phrase, type] of Object.entries(rulings.typeAliases ?? {})) add(phrase, type, phrase.endsWith("s"));
694
- for (const [name, t] of Object.entries(pack.types)) {
695
- const words = splitWords(name);
696
- const singulars = /* @__PURE__ */ new Set([words.join(" "), words[words.length - 1] ?? ""]);
697
- for (const p of [...t.phrases, name.toLowerCase()]) if (!aliased.has(p)) add(p, name, !singulars.has(p) && p !== name.toLowerCase());
698
- if (words.length > 1) {
699
- const first = words[0];
700
- if (!aliased.has(first)) add(first, name, false);
701
- if (!aliased.has(pluralize(first))) add(pluralize(first), name, true);
702
- }
703
- }
704
- return [...map].map(([phrase, e]) => ({
705
- phrase,
706
- types: [...e.types].sort(),
707
- plural: e.plural
708
- })).sort((x, y) => y.phrase.split(" ").length - x.phrase.split(" ").length || x.phrase.localeCompare(y.phrase));
709
- }
710
- function fieldNamed(pack, word) {
711
- return Object.values(pack.types).some((t) => Object.values(t.fields).some((f) => f.phrases.includes(word)));
712
- }
713
- /** Types every value can be read as, sorted. */
714
- function typesCovering(pack, values) {
715
- let acc = null;
716
- for (const v of values) {
717
- const types = new Set(v.alias !== void 0 ? v.alias.map((x) => x.type) : (own(pack.values, v.key) ?? []).map((r) => r.type));
718
- acc = acc === null ? [...types] : acc.filter((t) => types.has(t));
719
- }
720
- return [...acc ?? []].sort();
721
- }
722
- /** Types whose `status` enum has a terminal value. */
723
- function closableTypes(pack) {
724
- return Object.entries(pack.types).filter(([, t]) => t.fields.status?.enum?.some((v) => CLOSED.includes(v)) === true).map(([name]) => name).sort();
725
- }
726
- /**
727
- * The field a value reads as when it fits several on one type: a field named
728
- * in the question first, then the most categorical (fewest distinct values,
729
- * enum size for enums), then name order.
730
- */
731
- function pickField(candidates, fields, words) {
732
- const unique = [...new Set(candidates)];
733
- const text = ` ${words.join(" ")} `;
734
- const stem = (p) => p.replace(/s$/, "");
735
- const named = unique.filter((f) => fields[f]?.phrases.some((p) => text.includes(` ${p} `) || stem(p).length >= 3 && words.some((w) => w !== p && w.startsWith(stem(p)))));
736
- const pool = named.length > 0 ? named : unique;
737
- const size = (f) => fields[f]?.enum?.length ?? fields[f]?.distinct ?? Number.MAX_SAFE_INTEGER;
738
- return [...pool].sort((x, y) => size(x) - size(y) || x.localeCompare(y))[0];
739
- }
740
- function claimTime(tokens, asOf) {
741
- let found = null;
742
- claimNgrams(tokens, 3, (key) => {
743
- if (found !== null) return false;
744
- const range = rangeFor(key, asOf);
745
- if (range === null) return false;
746
- found = {
747
- span: key,
748
- range
749
- };
750
- return true;
751
- });
752
- return found;
753
- }
754
-
755
- //#endregion
756
- //#region src/judge/judge.ts
757
- /** String scalar fields a binding may target, as `Type.field`. */
758
- function bindableFields(pack, types) {
759
- const out = [];
760
- for (const type of types) for (const [name, f] of Object.entries(pack.types[type]?.fields ?? {})) if (f.kind === "scalar" && f.valueType === "string" && f.indexed) out.push(`${type}.${name}`);
761
- return out.sort();
762
- }
763
- /** Build the options, the prompt and the schema for one escalated parse. */
764
- function buildJudgePrompt(question, result, pack, rulings = {}, rejected = []) {
765
- const allTypes = Object.keys(pack.types).sort();
766
- const words = [...new Set(result.residual)];
767
- const fields = bindableFields(pack, result.candidates.length > 0 ? [...new Set(result.candidates.map((c) => c.type))] : allTypes);
768
- const branch = (action, args = {}) => ({
769
- type: "object",
770
- properties: {
771
- action: { const: action },
772
- ...args
773
- },
774
- required: ["action", ...Object.keys(args)]
775
- });
776
- const schema = { anyOf: [
777
- ...result.candidates.length > 0 ? [branch("pick", { candidate: {
778
- type: "integer",
779
- enum: result.candidates.map((_, i) => i)
780
- } })] : [],
781
- branch("type", { type: {
782
- type: "string",
783
- enum: allTypes
784
- } }),
785
- ...words.length > 0 && fields.length > 0 ? [branch("bind", {
786
- word: {
787
- type: "string",
788
- enum: words
789
- },
790
- field: {
791
- type: "string",
792
- enum: fields
793
- },
794
- op: {
795
- type: "string",
796
- enum: [
797
- "eq",
798
- "startsWith",
799
- "contains"
800
- ]
801
- }
802
- })] : [],
803
- branch("recall", { type: {
804
- type: "string",
805
- enum: allTypes
806
- } }),
807
- branch("clarify"),
808
- branch("refuse"),
809
- branch("escalate")
810
- ] };
811
- const ruled = (t) => Object.entries(rulings.typeAliases ?? {}).filter(([, type]) => type === t).map(([phrase]) => phrase);
812
- const typeLines = allTypes.map((t) => {
813
- const note = rulings.typeNotes?.[t];
814
- const names = [...ruled(t), ...(pack.types[t]?.phrases ?? []).slice(0, 4)].join(", ");
815
- return `- ${t}${note !== void 0 ? ` (${note})` : ""}: ${names}`;
816
- });
817
- const candidateLines = result.candidates.map((c, i) => `${i}. ${c.type} where ${JSON.stringify(Object.values(c.frame)[0]?.params.where ?? {})} (from: ${c.evidence.map((e) => `"${e.span}"=${e.detail}`).join("; ")})`);
818
- return {
819
- system: [
820
- "You choose how a question about a data store should be answered. You do not write queries.",
821
- "A deterministic parser read the question first and could not settle it. Choose ONE action:",
822
- "- pick: one reading answers the WHOLE question as asked; leftover words are noise. If the",
823
- " question needs rows of one type found through another, no single reading answers it.",
824
- "- type: the question lists or counts rows of one type; the parser then builds the query from the",
825
- " question's own words (dates, \"latest\", known values). Prefer this when a type clearly fits.",
826
- "- bind: a leftover word is a value stored in a field: eq = the whole value, startsWith = a prefix",
827
- " of a name or id, contains = a word inside a title or subject. Never bind a word that only",
828
- " describes the question (e.g. \"status\", \"called\").",
829
- "- recall: the question asks what is known ABOUT a topic (free-text subject words, not field values);",
830
- " semantic search over the text answers it. Name the type whose rows hold that knowledge.",
831
- "- clarify: RARE. Only when the question has two specific readings and nothing in it chooses one.",
832
- " Missing detail is not ambiguity: if a type or a topic fits, choose type or recall.",
833
- "- refuse: the question is not about this store at all, or asks to change data.",
834
- "- escalate: none of these answers the question as asked (e.g. it needs two queries chained).",
835
- "",
836
- `Types in the "${pack.namespace}" store:`,
837
- ...typeLines
838
- ].join("\n"),
839
- user: [
840
- `Question: ${question}`,
841
- `Parser: ${result.status}${result.reason !== void 0 ? ` (${result.reason})` : ""}`,
842
- ...result.evidence !== void 0 && result.evidence.length > 0 ? [`Understood so far: ${result.evidence.map((e) => `"${e.span}" = ${e.role} ${e.detail}`).join("; ")}`] : [],
843
- ...candidateLines.length > 0 ? ["Readings:", ...candidateLines] : [],
844
- ...words.length > 0 ? [`Leftover words: ${words.join(", ")}`] : [],
845
- ...rejected.map((r) => `Already tried and rejected: ${r}`)
846
- ].join("\n"),
847
- schema
848
- };
849
- }
850
- /** Check a reply against the options it was offered. */
851
- function checkChoice(reply, prompt) {
852
- if (typeof reply !== "object" || reply === null) return "reply is not an object";
853
- const r = reply;
854
- const branch = (prompt.schema.anyOf ?? []).find((b) => b.properties.action?.const === r.action);
855
- if (branch === void 0) return `action ${JSON.stringify(r.action)} was not offered`;
856
- const choice = { action: r.action };
857
- for (const key of branch.required) {
858
- if (key === "action") continue;
859
- if (branch.properties[key]?.enum?.includes(r[key]) !== true) return `${String(r.action)} needs an offered ${key}`;
860
- choice[key] = r[key];
861
- }
862
- return choice;
863
- }
864
- /** A binding becomes a one-question ruling, so the parser applies it like any other. */
865
- function withBinding(rulings, choice) {
866
- const [type, field] = choice.field.split(".");
867
- const word = choice.word;
868
- const alias = choice.op === "startsWith" ? {
869
- type,
870
- field,
871
- startsWith: word
872
- } : choice.op === "contains" ? {
873
- type,
874
- field,
875
- contains: word
876
- } : {
877
- type,
878
- field,
879
- eq: word
880
- };
881
- return {
882
- ...rulings ?? {},
883
- valueAliases: {
884
- ...rulings?.valueAliases ?? {},
885
- [word]: [alias]
886
- }
887
- };
888
- }
889
- /** Why a binding cannot be applied, or null when it grounds. */
890
- async function verifyBinding(choice, earlier, pack, opts) {
891
- const [type, field] = choice.field.split(".");
892
- const word = choice.word;
893
- const def = own(own(pack.types, type)?.fields, field);
894
- if (def === void 0) return `${type}.${field} is not a field`;
895
- if (!def.operators.includes(choice.op)) return `${type}.${field} does not accept ${choice.op}`;
896
- if (def.enum !== void 0 && choice.op === "eq") {
897
- if (![...def.enum, ...Object.keys(def.aliases ?? {})].map((v) => v.toLowerCase()).includes(word.toLowerCase())) return `"${word}" is not a ${type}.${field} value`;
898
- }
899
- if (opts.exists === void 0) return null;
900
- const predicate = (c) => ({ [c.field.split(".")[1]]: { [c.op]: c.word } });
901
- const same = earlier.filter((c) => c.field.startsWith(`${type}.`));
902
- const where = same.length === 0 ? predicate(choice) : { AND: [...same, choice].map(predicate) };
903
- if (!await opts.exists(type, where)) return same.length === 0 ? `no ${type} has ${field} ${choice.op} "${word}"` : `no ${type} matches it together with ${same.map((c) => `"${c.word}"`).join(", ")}`;
904
- return null;
905
- }
906
- /**
907
- * Parse; while the parse is not resolved, ask the judge and apply its choice.
908
- * A refused, clarified or resolved parse never reaches the model.
909
- */
910
- async function parseWithJudge(question, pack, ctx, judge, opts = {}) {
911
- const trail = [];
912
- let context = ctx;
913
- let result = parseQuestion(question, pack, context);
914
- const rejected = [];
915
- const bound = [];
916
- for (let round = 0; round < (opts.rounds ?? 3); round++) {
917
- if (result.status === "resolved") return {
918
- status: "resolved",
919
- candidate: result.candidates[0],
920
- trail
921
- };
922
- if (result.status === "refuse" || result.status === "clarify") return {
923
- status: result.status,
924
- reason: result.reason ?? "",
925
- trail
926
- };
927
- const step = { parse: {
928
- status: result.status,
929
- ...result.reason !== void 0 ? { reason: result.reason } : {}
930
- } };
931
- trail.push(step);
932
- const prompt = buildJudgePrompt(question, result, pack, context.rulings, rejected);
933
- const checked = checkChoice(await judge.decide(prompt, opts.signal), prompt);
934
- if (typeof checked === "string") {
935
- step.rejected = checked;
936
- break;
937
- }
938
- step.choice = checked;
939
- switch (checked.action) {
940
- case "pick": return {
941
- status: "resolved",
942
- candidate: result.candidates[checked.candidate],
943
- trail
944
- };
945
- case "recall": return {
946
- status: "recall",
947
- query: question,
948
- type: checked.type,
949
- trail
950
- };
951
- case "clarify":
952
- case "refuse": return {
953
- status: checked.action,
954
- reason: "judge",
955
- trail
956
- };
957
- case "type":
958
- context = {
959
- ...context,
960
- forceType: checked.type
961
- };
962
- break;
963
- case "escalate": return {
964
- status: "escalated",
965
- result,
966
- trail
967
- };
968
- case "bind": {
969
- const why = await verifyBinding(checked, bound, pack, opts);
970
- if (why !== null) {
971
- step.rejected = why;
972
- rejected.push(`bind ${checked.word} to ${checked.field} (${why})`);
973
- continue;
974
- }
975
- bound.push(checked);
976
- context = {
977
- ...context,
978
- rulings: withBinding(context.rulings, checked)
979
- };
980
- break;
981
- }
982
- }
983
- result = parseQuestion(question, pack, context);
984
- }
985
- if (result.status === "resolved") return {
986
- status: "resolved",
987
- candidate: result.candidates[0],
988
- trail
989
- };
990
- return {
991
- status: "escalated",
992
- result,
993
- trail
994
- };
995
- }
996
-
997
- //#endregion
998
- //#region src/ask/run.ts
999
- const RECALL_K = 10;
1000
- /** The frame a candidate needs to run: its params plus every projectable field of its type. */
1001
- function executable(c, pack) {
1002
- const [key, value] = Object.entries(c.frame)[0];
1003
- const fields = { id: true };
1004
- for (const [name, f] of Object.entries(own(pack.types, c.type)?.fields ?? {})) if (f.kind !== "metadata") fields[name] = true;
1005
- return { [key]: {
1006
- params: value.params,
1007
- fields
1008
- } };
1009
- }
1010
- async function rows(c, source, http, deps, handoff) {
1011
- const frame = executable(c, deps.pack);
1012
- const key = Object.keys(frame)[0];
1013
- const env = await deps.engine.query(frame, http);
1014
- const data = env.data !== void 0 && key in env.data ? env.data?.[key] : void 0;
1015
- const errors = [...env.errors ?? []];
1016
- let count;
1017
- if (c.answer === "count" && Array.isArray(data)) {
1018
- const counted = await countRest(frame, key, data.length, env, http, deps);
1019
- if (typeof counted === "number") count = counted;
1020
- else errors.push(counted);
1021
- }
1022
- return {
1023
- kind: "rows",
1024
- frame,
1025
- answer: c.answer,
1026
- data,
1027
- ...count !== void 0 ? { count } : {},
1028
- ...errors.length > 0 ? { errors } : {},
1029
- source,
1030
- ...handoff !== void 0 ? { handoff } : {}
1031
- };
1032
- }
1033
- const MAX_COUNT_PAGES = 1e3;
1034
- /** The population a count candidate matches: `seen` rows from page one, then id-only pages after its cursor. */
1035
- async function countRest(frame, key, seen, first, http, deps) {
1036
- const params = frame[key]?.params ?? {};
1037
- let count = seen;
1038
- let page = first._pagination?.[key];
1039
- for (let pages = 1; page?.hasMore === true; pages++) {
1040
- if (pages >= MAX_COUNT_PAGES || page.nextCursor === void 0 || isAborted(http)) return {
1041
- code: "count_incomplete",
1042
- message: `counted ${count} rows and stopped before the end; the true count is higher`
1043
- };
1044
- const env = await deps.engine.query({ [key]: {
1045
- params: {
1046
- ...params,
1047
- cursor: page.nextCursor
1048
- },
1049
- fields: { id: true }
1050
- } }, http);
1051
- const rows = env.data?.[key];
1052
- if (!Array.isArray(rows)) return {
1053
- code: "count_incomplete",
1054
- message: `counted ${count} rows, then a page failed: ${JSON.stringify(env.errors ?? [])}`
1055
- };
1056
- count += rows.length;
1057
- page = env._pagination?.[key];
1058
- }
1059
- return count;
1060
- }
1061
- async function recall(query, ns, type, http, deps) {
1062
- const frame = { "recall/Hit": {
1063
- params: {
1064
- to: query,
1065
- namespace: ns,
1066
- type,
1067
- k: RECALL_K
1068
- },
1069
- fields: {
1070
- id: true,
1071
- namespace: true,
1072
- type: true,
1073
- score: true,
1074
- row: true
1075
- }
1076
- } };
1077
- const env = await deps.engine.query(frame, http);
1078
- const hits = env.data?.["recall/Hit"];
1079
- return {
1080
- kind: "recall",
1081
- query,
1082
- hits: Array.isArray(hits) ? hits : void 0,
1083
- ...env.errors !== void 0 && env.errors.length > 0 ? { errors: env.errors } : {}
1084
- };
1085
- }
1086
- function clarify(question, reason, candidates, pack) {
1087
- const seen = /* @__PURE__ */ new Set();
1088
- const options = [];
1089
- for (const c of candidates) {
1090
- if (seen.has(c.type)) continue;
1091
- seen.add(c.type);
1092
- const phrase = own(pack.types, c.type)?.phrases[0] ?? c.type;
1093
- options.push({
1094
- label: `${phrase} (${c.type})`,
1095
- question,
1096
- type: c.type
1097
- });
1098
- }
1099
- return {
1100
- kind: "clarify",
1101
- question,
1102
- reason,
1103
- options
1104
- };
1105
- }
1106
- const isAborted = (http) => http.signal?.aborted === true;
1107
- async function* runAsk(req, http, deps) {
1108
- const ctx = {
1109
- asOf: (deps.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
1110
- rulings: deps.pack.rulings,
1111
- ...req.project !== void 0 ? { project: req.project } : {},
1112
- ...req.type !== void 0 ? { forceType: req.type } : {}
1113
- };
1114
- const first = parseQuestion(req.question, deps.pack, ctx);
1115
- const best = first.candidates[0];
1116
- yield {
1117
- event: "parsed",
1118
- status: first.status,
1119
- ...best !== void 0 ? { frame: executable(best, deps.pack) } : {},
1120
- evidence: best?.evidence ?? first.evidence ?? [],
1121
- residual: first.residual,
1122
- ...first.reason !== void 0 ? { reason: first.reason } : {}
1123
- };
1124
- if (isAborted(http)) return yield { event: "done" };
1125
- let outcome;
1126
- if (first.status === "resolved" && best !== void 0) outcome = await rows(best, "parser", http, deps);
1127
- else if (first.status === "refuse") outcome = {
1128
- kind: "refuse",
1129
- reason: first.reason ?? "refused"
1130
- };
1131
- else if (first.status === "clarify") outcome = clarify(req.question, first.reason ?? "which did you mean?", first.candidates, deps.pack);
1132
- else if (deps.judge === void 0) outcome = best !== void 0 ? await rows(best, "handoff", http, deps, "judge not configured") : clarify(req.question, "judge not configured", first.candidates, deps.pack);
1133
- else {
1134
- yield {
1135
- event: "judging",
1136
- reason: first.reason ?? first.status
1137
- };
1138
- const ac = new AbortController();
1139
- const timer = setTimeout(() => ac.abort(/* @__PURE__ */ new Error("judge timeout")), deps.judgeTimeoutMs ?? 2e4);
1140
- const onAbort = () => ac.abort(http.signal?.reason);
1141
- http.signal?.addEventListener("abort", onAbort, { once: true });
1142
- if (isAborted(http)) onAbort();
1143
- let judged;
1144
- try {
1145
- const judging = parseWithJudge(req.question, deps.pack, ctx, deps.judge, {
1146
- signal: ac.signal,
1147
- exists: async (type, where) => {
1148
- if (ac.signal.aborted) return false;
1149
- const key = `${deps.pack.namespace}/${type}`;
1150
- const r = (await deps.engine.query({ [key]: {
1151
- params: {
1152
- where,
1153
- limit: 1
1154
- },
1155
- fields: { id: true }
1156
- } }, http)).data?.[key];
1157
- return Array.isArray(r) && r.length > 0;
1158
- }
1159
- });
1160
- judging.catch(() => {});
1161
- const gone = new Promise((_, reject) => {
1162
- const fire = () => reject(ac.signal.reason);
1163
- if (ac.signal.aborted) fire();
1164
- else ac.signal.addEventListener("abort", fire, { once: true });
1165
- });
1166
- judged = await Promise.race([judging, gone]);
1167
- } catch {
1168
- judged = void 0;
1169
- } finally {
1170
- clearTimeout(timer);
1171
- http.signal?.removeEventListener("abort", onAbort);
1172
- }
1173
- if (isAborted(http)) return yield { event: "done" };
1174
- if (judged === void 0) outcome = best !== void 0 ? await rows(best, "handoff", http, deps, "judge unavailable") : clarify(req.question, "judge unavailable", first.candidates, deps.pack);
1175
- else {
1176
- yield {
1177
- event: "judged",
1178
- status: judged.status,
1179
- trail: judged.trail
1180
- };
1181
- switch (judged.status) {
1182
- case "resolved":
1183
- outcome = await rows(judged.candidate, "judge", http, deps);
1184
- break;
1185
- case "recall":
1186
- outcome = await recall(judged.query, deps.pack.namespace, ctx.forceType ?? judged.type, http, deps);
1187
- break;
1188
- case "refuse":
1189
- outcome = {
1190
- kind: "refuse",
1191
- reason: judged.reason
1192
- };
1193
- break;
1194
- case "clarify":
1195
- outcome = clarify(req.question, judged.reason, first.candidates, deps.pack);
1196
- break;
1197
- case "escalated": outcome = best !== void 0 ? await rows(best, "handoff", http, deps, "judge could not decide") : clarify(req.question, "judge could not decide", first.candidates, deps.pack);
1198
- }
1199
- }
1200
- }
1201
- yield {
1202
- event: "outcome",
1203
- outcome
1204
- };
1205
- yield { event: "done" };
1206
- }
1207
-
1208
- //#endregion
1209
- //#region src/judge/ollama.ts
1210
- /**
1211
- * Ollama's native chat endpoint with `format` set to the question's schema,
1212
- * so decoding cannot leave the offered options. Thinking off, temperature 0
1213
- * and a fixed seed. Sends no `num_ctx` / `keep_alive`: Ollama shares one
1214
- * runner per model, and differing options force a reload for every client
1215
- * (see substrate-embedder's README).
1216
- */
1217
- var OllamaJudge = class {
1218
- #config;
1219
- constructor(config) {
1220
- this.#config = {
1221
- ...config,
1222
- baseUrl: trimTrailingSlashes(config.baseUrl)
1223
- };
1224
- }
1225
- async decide(prompt, signal) {
1226
- const timeout = AbortSignal.timeout(this.#config.timeoutMs ?? 6e4);
1227
- const res = await fetch(`${this.#config.baseUrl}/api/chat`, {
1228
- method: "POST",
1229
- headers: { "content-type": "application/json" },
1230
- signal: signal === void 0 ? timeout : AbortSignal.any([timeout, signal]),
1231
- body: JSON.stringify({
1232
- model: this.#config.model,
1233
- stream: false,
1234
- think: false,
1235
- format: prompt.schema,
1236
- options: {
1237
- temperature: 0,
1238
- seed: 0
1239
- },
1240
- messages: [{
1241
- role: "system",
1242
- content: prompt.system
1243
- }, {
1244
- role: "user",
1245
- content: prompt.user
1246
- }]
1247
- })
1248
- });
1249
- if (!res.ok) throw new Error(`ollama ${res.status} ${res.statusText}`);
1250
- const body = await res.json();
1251
- return JSON.parse(body.message?.content ?? "");
1252
- }
1253
- };
1254
-
1255
- //#endregion
1256
- //#region src/rulings/schema.ts
1257
- const ValueAliasSchema = z.object({
1258
- type: z.string().min(1),
1259
- field: z.string().min(1),
1260
- in: z.array(z.string()).optional(),
1261
- eq: z.string().optional(),
1262
- startsWith: z.string().optional(),
1263
- contains: z.string().optional()
1264
- }).strict().refine((v) => [
1265
- v.in,
1266
- v.eq,
1267
- v.startsWith,
1268
- v.contains
1269
- ].filter((x) => x !== void 0).length === 1, { message: "a value alias names exactly one of in, eq, startsWith, contains" });
1270
- const record = z.record(z.string(), z.string());
1271
- const NamespaceRulingsSchema = z.object({
1272
- unscopedTypes: z.array(z.string()).optional(),
1273
- typeAliases: record.optional(),
1274
- fieldAliases: record.optional(),
1275
- liveStatus: record.optional(),
1276
- timeField: record.optional(),
1277
- typeNotes: record.optional(),
1278
- valueAliases: z.record(z.string(), z.array(ValueAliasSchema)).optional()
1279
- }).strict();
1280
- /** Per top-level key: records merge entry-by-entry (override wins), arrays replace. */
1281
- function mergeRulings(declared, override) {
1282
- if (override === void 0) return declared;
1283
- const out = { ...declared };
1284
- for (const [key, value] of Object.entries(override)) {
1285
- const prior = out[key];
1286
- out[key] = Array.isArray(value) || prior === void 0 || Array.isArray(prior) ? value : {
1287
- ...prior,
1288
- ...value
1289
- };
1290
- }
1291
- return out;
1292
- }
1293
- /** The effective rulings for one namespace's schema, plus anything that was dropped. */
1294
- function readRulings(schema, override) {
1295
- const warnings = [];
1296
- let declared = {};
1297
- const raw = schema.annotations?.nl;
1298
- if (raw !== void 0) {
1299
- const parsed = NamespaceRulingsSchema.safeParse(raw);
1300
- if (parsed.success) declared = parsed.data;
1301
- else {
1302
- const where = parsed.error.issues.map((i) => i.path.join(".") || "(root)").join(", ");
1303
- warnings.push(`declared rulings are invalid and were ignored (${where})`);
1304
- }
1305
- }
1306
- return {
1307
- rulings: mergeRulings(declared, override),
1308
- warnings
1309
- };
1310
- }
1311
-
1312
- //#endregion
1313
- //#region src/pack/build.ts
1314
- /** Longest value worth matching as a whole phrase. */
1315
- const MAX_VALUE_LENGTH = 64;
1316
- /**
1317
- * A field is vocabulary when its values are labels rather than prose. The
1318
- * test is length, not distinct count: an `area` with hundreds of one-word
1319
- * values is vocabulary, a `title` with a dozen sentences is not.
1320
- */
1321
- const MAX_MEAN_WORDS = 3;
1322
- /** Server-managed fields every type can filter on, with their value type. */
1323
- const METADATA_FIELDS = {
1324
- createdAt: {
1325
- valueType: "date",
1326
- phrases: ["created", "created at"]
1327
- },
1328
- updatedAt: {
1329
- valueType: "date",
1330
- phrases: ["updated", "updated at"]
1331
- },
1332
- createdById: {
1333
- valueType: "string",
1334
- phrases: ["created by", "author"]
1335
- },
1336
- createdByKind: {
1337
- valueType: "string",
1338
- phrases: ["created by kind"]
1339
- },
1340
- updatedById: {
1341
- valueType: "string",
1342
- phrases: ["updated by"]
1343
- },
1344
- updatedByKind: {
1345
- valueType: "string",
1346
- phrases: ["updated by kind"]
1347
- }
1348
- };
1349
- /**
1350
- * Builds the NL vocabulary for one namespace. Pure: the same schema, operator
1351
- * table and profile always give byte-identical output, with sorted keys.
1352
- */
1353
- function buildNamespacePack(input) {
1354
- const { namespace, schema, operators, profile } = input;
1355
- const maxDistinct = input.maxDistinct ?? 1e3;
1356
- const types = {};
1357
- const refs = [];
1358
- for (const typeName of Object.keys(schema.types).sort()) {
1359
- const declared = schema.types[typeName]?.fields ?? {};
1360
- const fields = {};
1361
- for (const name of Object.keys(declared).sort()) {
1362
- const def = declared[name];
1363
- const field = packField(name, def, operators);
1364
- fields[name] = field;
1365
- for (const value of field.enum ?? []) refs.push({
1366
- type: typeName,
1367
- field: name,
1368
- value
1369
- });
1370
- for (const alias of Object.keys(field.aliases ?? {})) refs.push({
1371
- type: typeName,
1372
- field: name,
1373
- value: alias
1374
- });
1375
- const observed = profile?.types[typeName]?.[name];
1376
- if (observed !== void 0 && field.indexed && isStringy(def) && !observed.truncated && observed.values.length <= maxDistinct && areLabels(observed.values)) {
1377
- for (const value of observed.values) refs.push({
1378
- type: typeName,
1379
- field: name,
1380
- value
1381
- });
1382
- field.distinct = observed.values.length;
1383
- }
1384
- }
1385
- for (const [name, meta] of Object.entries(METADATA_FIELDS)) {
1386
- if (name in fields) continue;
1387
- fields[name] = {
1388
- name,
1389
- kind: "metadata",
1390
- valueType: meta.valueType,
1391
- indexed: true,
1392
- operators: [...operators[`scalar.${meta.valueType}`] ?? []],
1393
- phrases: meta.phrases
1394
- };
1395
- }
1396
- types[typeName] = {
1397
- name: typeName,
1398
- phrases: typePhrases(typeName),
1399
- fields: sortKeys(fields)
1400
- };
1401
- }
1402
- return {
1403
- namespace,
1404
- schemaVersion: schema.schemaVersion,
1405
- types,
1406
- values: indexValues(refs)
1407
- };
1408
- }
1409
- function packField(name, def, operators) {
1410
- const phrases = uniqueSorted([splitWords(name).join(" "), name.toLowerCase()]);
1411
- switch (def.kind) {
1412
- case "scalar": return {
1413
- name,
1414
- kind: "scalar",
1415
- valueType: def.type,
1416
- indexed: def.indexed === true,
1417
- operators: [...operators[`scalar.${def.type}`] ?? []],
1418
- phrases,
1419
- ...def.enum !== void 0 ? { enum: [...def.enum] } : {},
1420
- ...def.aliases !== void 0 ? { aliases: { ...def.aliases } } : {}
1421
- };
1422
- case "crossRef": return {
1423
- name,
1424
- kind: "crossRef",
1425
- target: def.type,
1426
- indexed: def.indexed === true,
1427
- operators: [...operators.crossRef ?? []],
1428
- phrases
1429
- };
1430
- case "list": return {
1431
- name,
1432
- kind: "list",
1433
- indexed: def.indexed === true,
1434
- operators: [...operators.list ?? []],
1435
- phrases
1436
- };
1437
- default: return {
1438
- name,
1439
- kind: "struct",
1440
- indexed: false,
1441
- operators: [],
1442
- phrases
1443
- };
1444
- }
1445
- }
1446
- function areLabels(values) {
1447
- if (values.length === 0) return false;
1448
- return values.reduce((n, v) => n + v.trim().split(/\s+/).length, 0) / values.length <= MAX_MEAN_WORDS;
1449
- }
1450
- /** A string scalar, or a list of string scalars: the fields whose values read as words. */
1451
- function isStringy(def) {
1452
- if (def.kind === "scalar") return def.type === "string";
1453
- return def.kind === "list" && def.of.kind === "scalar" && def.of.type === "string";
1454
- }
1455
- function typePhrases(typeName) {
1456
- const words = splitWords(typeName);
1457
- const last = words[words.length - 1] ?? typeName.toLowerCase();
1458
- const head = words.slice(0, -1);
1459
- const out = [[...head, last].join(" "), [...head, pluralize(last)].join(" ")];
1460
- if (head.length > 0) out.push(last, pluralize(last));
1461
- return uniqueSorted(out);
1462
- }
1463
- function indexValues(refs) {
1464
- const byKey = /* @__PURE__ */ new Map();
1465
- for (const ref of refs) {
1466
- const key = ref.value.trim().toLowerCase();
1467
- if (key.length === 0 || key.length > MAX_VALUE_LENGTH) continue;
1468
- const bucket = byKey.get(key) ?? /* @__PURE__ */ new Map();
1469
- bucket.set(`${ref.type}\u0000${ref.field}`, ref);
1470
- byKey.set(key, bucket);
1471
- }
1472
- const out = {};
1473
- for (const key of [...byKey.keys()].sort()) {
1474
- const bucket = byKey.get(key);
1475
- out[key] = [...bucket.keys()].sort().map((k) => bucket.get(k));
1476
- }
1477
- return out;
1478
- }
1479
- function sortKeys(obj) {
1480
- return Object.fromEntries(Object.keys(obj).sort().map((k) => [k, obj[k]]));
1481
- }
1482
-
1483
- //#endregion
1484
- //#region src/pack/profile.ts
1485
- /**
1486
- * Distinct values of every indexed string field (and indexed list-of-string
1487
- * field) in the namespace, reading up to `maxRows` rows per type. A field that
1488
- * passes `maxDistinct` is marked truncated and stops growing.
1489
- */
1490
- async function profileNamespace(input) {
1491
- const maxDistinct = input.maxDistinct ?? 1e3;
1492
- const maxRows = input.maxRows ?? 1e4;
1493
- const types = {};
1494
- for (const typeName of Object.keys(input.schema.types).sort()) {
1495
- const declared = input.schema.types[typeName]?.fields ?? {};
1496
- const fields = Object.keys(declared).filter((f) => profiled(declared[f]));
1497
- if (fields.length === 0) continue;
1498
- const seen = new Map(fields.map((f) => [f, /* @__PURE__ */ new Set()]));
1499
- const truncated = /* @__PURE__ */ new Set();
1500
- let cursor;
1501
- let rowsRead = 0;
1502
- do {
1503
- const page = await input.read(typeName, fields, cursor);
1504
- rowsRead += page.rows.length;
1505
- for (const row of page.rows) for (const f of fields) {
1506
- if (truncated.has(f)) continue;
1507
- const raw = row[f];
1508
- const values = Array.isArray(raw) ? raw : [raw];
1509
- const set = seen.get(f);
1510
- for (const v of values) {
1511
- if (typeof v !== "string" || v.length === 0) continue;
1512
- set.add(v);
1513
- if (set.size > maxDistinct) {
1514
- truncated.add(f);
1515
- break;
1516
- }
1517
- }
1518
- }
1519
- cursor = page.nextCursor;
1520
- } while (cursor !== void 0 && truncated.size < fields.length && rowsRead < maxRows);
1521
- const out = {};
1522
- for (const f of [...fields].sort()) {
1523
- const values = [...seen.get(f)].sort();
1524
- const isTruncated = truncated.has(f);
1525
- if (values.length === 0 && !isTruncated) continue;
1526
- out[f] = {
1527
- values: isTruncated ? values.slice(0, maxDistinct) : values,
1528
- truncated: isTruncated
1529
- };
1530
- }
1531
- types[typeName] = out;
1532
- }
1533
- return { types };
1534
- }
1535
- function profiled(def) {
1536
- if (def.kind === "scalar") return def.type === "string" && def.indexed === true;
1537
- return def.kind === "list" && def.indexed === true && def.of.kind === "scalar" && def.of.type === "string";
1538
- }
1539
-
1540
- //#endregion
1541
- //#region src/pack/service.ts
1542
- /**
1543
- * Packs are built under the CALLER's request: the profile reads distinct
1544
- * values through `engine.query(frame, req)`, so row policy applies and a
1545
- * pack can never disclose a value its caller could not read. Hence the
1546
- * principal is part of the cache key.
1547
- */
1548
- var PackService = class {
1549
- #opts;
1550
- #cache = /* @__PURE__ */ new Map();
1551
- #inflight = /* @__PURE__ */ new Map();
1552
- #warned = /* @__PURE__ */ new Set();
1553
- constructor(opts) {
1554
- this.#opts = opts;
1555
- }
1556
- async get(ns, req) {
1557
- const schemas = this.#opts.engine.federatedSchema();
1558
- const schema = Object.hasOwn(schemas, ns) ? schemas[ns] : void 0;
1559
- if (schema === void 0) return void 0;
1560
- const now = (this.#opts.now ?? Date.now)();
1561
- const ttl = this.#opts.ttlMs ?? 3e5;
1562
- const key = `${ns}\u0000${schema.schemaVersion}\u0000${principalKey(req)}`;
1563
- const hit = this.#cache.get(key);
1564
- if (hit !== void 0 && now - hit.at < ttl) {
1565
- this.#cache.delete(key);
1566
- this.#cache.set(key, hit);
1567
- return {
1568
- pack: hit.pack,
1569
- etag: hit.etag
1570
- };
1571
- }
1572
- let pending = this.#inflight.get(key);
1573
- if (pending === void 0) {
1574
- pending = this.#build(ns, schema, req, now).finally(() => this.#inflight.delete(key));
1575
- this.#inflight.set(key, pending);
1576
- }
1577
- const entry = await pending;
1578
- this.#cache.delete(key);
1579
- this.#cache.set(key, entry);
1580
- const max = this.#opts.maxEntries ?? 256;
1581
- while (this.#cache.size > max) {
1582
- const oldest = this.#cache.keys().next().value;
1583
- if (oldest === void 0) break;
1584
- this.#cache.delete(oldest);
1585
- }
1586
- return {
1587
- pack: entry.pack,
1588
- etag: entry.etag
1589
- };
1590
- }
1591
- async #build(ns, schema, req, now) {
1592
- const { rulings, warnings } = readRulings(schema, own(this.#opts.rulings, ns));
1593
- const warnKey = `${ns}\u0000${schema.schemaVersion}`;
1594
- if (warnings.length > 0 && !this.#warned.has(warnKey)) {
1595
- this.#warned.add(warnKey);
1596
- (this.#opts.log ?? console.warn)(`substrate-nl: ${ns}: ${warnings.join("; ")}`);
1597
- }
1598
- const read = async (type, fields, cursor) => {
1599
- const frameKey = `${ns}/${type}`;
1600
- const env = await this.#opts.engine.query({ [frameKey]: {
1601
- params: cursor !== void 0 ? { cursor } : {},
1602
- fields: Object.fromEntries(fields.map((f) => [f, true]))
1603
- } }, req);
1604
- const rows = env.data?.[frameKey];
1605
- const page = env._pagination?.[frameKey];
1606
- return {
1607
- rows: Array.isArray(rows) ? rows : [],
1608
- nextCursor: page?.hasMore === true ? page.nextCursor : void 0
1609
- };
1610
- };
1611
- const profile = await profileNamespace({
1612
- schema,
1613
- read
1614
- });
1615
- const pack = {
1616
- ...buildNamespacePack({
1617
- namespace: ns,
1618
- schema,
1619
- operators: this.#opts.engine.operators(ns) ?? {},
1620
- profile
1621
- }),
1622
- rulings,
1623
- warnings
1624
- };
1625
- return {
1626
- pack,
1627
- etag: `"${createHash("sha256").update(JSON.stringify(pack)).digest("hex").slice(0, 16)}"`,
1628
- at: now
1629
- };
1630
- }
1631
- };
1632
- /**
1633
- * The Identity canonicalised, less `expiresAt`: a custom row policy may key on
1634
- * any claim (a tenant, say), so no other subset is safe to share a cached pack
1635
- * across, while a token's expiry changes with every refresh.
1636
- */
1637
- function principalKey(req) {
1638
- const id = req.identity;
1639
- if (id === void 0) return "\0anon";
1640
- const { expiresAt: _expiresAt, ...stable } = id;
1641
- return JSON.stringify(canonical(stable));
1642
- }
1643
- function canonical(v) {
1644
- if (Array.isArray(v)) return v.map(canonical);
1645
- if (v !== null && typeof v === "object") return Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, x]) => [k, canonical(x)]));
1646
- return v;
1647
- }
1648
-
1649
- //#endregion
1650
- //#region src/ask/encode.ts
1651
- /** Same headers as substrate-compose's SSE routes (not exported from its entry). */
1652
- const SSE_HEADERS = {
1653
- "content-type": "text/event-stream",
1654
- "cache-control": "no-store",
1655
- "x-accel-buffering": "no"
1656
- };
1657
- /** One named SSE event. JSON.stringify emits no raw newline, so one data line is safe. */
1658
- function sseEvent(name, data) {
1659
- return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
1660
- }
1661
- function wireName(ev) {
1662
- if (ev.event === "outcome") return [ev.outcome.kind, ev.outcome];
1663
- const { event, ...rest } = ev;
1664
- return [event, rest];
1665
- }
1666
- function toSseStream(events, onCancel, onError) {
1667
- const enc = new TextEncoder();
1668
- return new ReadableStream({
1669
- async pull(controller) {
1670
- try {
1671
- const next = await events.next();
1672
- if (next.done === true) return controller.close();
1673
- const [name, data] = wireName(next.value);
1674
- controller.enqueue(enc.encode(sseEvent(name, data)));
1675
- } catch (err) {
1676
- onError?.(err);
1677
- controller.enqueue(enc.encode(sseEvent("error", {
1678
- code: "nl_engine_error",
1679
- message: "NL query failed"
1680
- })));
1681
- controller.close();
1682
- }
1683
- },
1684
- async cancel() {
1685
- onCancel?.();
1686
- await events.return(void 0);
1687
- }
1688
- });
1689
- }
1690
- async function toJson(events) {
1691
- const trail = [];
1692
- let outcome = null;
1693
- for await (const ev of events) {
1694
- trail.push(ev);
1695
- if (ev.event === "outcome") outcome = ev.outcome;
1696
- }
1697
- return {
1698
- outcome,
1699
- trail
1700
- };
1701
- }
1702
-
1703
- //#endregion
1704
- //#region src/routes.ts
1705
- const VARY = { vary: "authorization" };
1706
- const engineFailure = (req, err, log) => {
1707
- if (req.signal?.aborted === true) return { status: 499 };
1708
- log(err);
1709
- return jsonResponse(502, {
1710
- error: "NL query failed",
1711
- code: "nl_engine_error"
1712
- });
1713
- };
1714
- const str = (v) => typeof v === "string" && v.length > 0;
1715
- /** Longest question parsed; the same bound recall puts on its query text. */
1716
- const MAX_QUESTION_CHARS = 8192;
1717
- function askHandler(deps) {
1718
- const log = deps.log ?? ((err) => console.error("substrate-nl:", err));
1719
- return async (req) => {
1720
- const parsed = parseJsonBody(req);
1721
- if (!parsed.ok) return parsed.response;
1722
- const body = parsed.value;
1723
- if (body === null || typeof body !== "object" || Array.isArray(body)) return error400("body must be a JSON object: { namespace, question, project?, type? }");
1724
- if (!str(body.namespace)) return error400("body.namespace must be a non-empty string");
1725
- if (!str(body.question)) return error400("body.question must be a non-empty string");
1726
- if (body.question.length > MAX_QUESTION_CHARS) return error400(`body.question is longer than ${MAX_QUESTION_CHARS} characters`);
1727
- for (const k of ["project", "type"]) if (body[k] !== void 0 && !str(body[k])) return error400(`body.${k} must be a non-empty string when given`);
1728
- const ask = {
1729
- namespace: body.namespace,
1730
- question: body.question,
1731
- ...str(body.project) ? { project: body.project } : {},
1732
- ...str(body.type) ? { type: body.type } : {}
1733
- };
1734
- let served;
1735
- try {
1736
- served = await deps.packs.get(ask.namespace, req);
1737
- } catch (err) {
1738
- return engineFailure(req, err, log);
1739
- }
1740
- if (served === void 0) return jsonResponse(404, {
1741
- error: `unknown namespace '${ask.namespace}'`,
1742
- code: "nl_unknown_namespace"
1743
- });
1744
- if (ask.type !== void 0 && !Object.hasOwn(served.pack.types, ask.type)) return error400(`unknown type '${ask.type}'`);
1745
- const events = runAsk(ask, req, {
1746
- pack: served.pack,
1747
- engine: deps.engine,
1748
- ...deps.judge !== void 0 ? { judge: deps.judge } : {},
1749
- ...deps.judgeTimeoutMs !== void 0 ? { judgeTimeoutMs: deps.judgeTimeoutMs } : {},
1750
- ...deps.now !== void 0 ? { now: deps.now } : {}
1751
- });
1752
- if ((req.headers.accept ?? "").toLowerCase().includes("text/event-stream")) return {
1753
- status: 200,
1754
- headers: SSE_HEADERS,
1755
- body: toSseStream(events, void 0, log)
1756
- };
1757
- try {
1758
- return jsonResponse(200, await toJson(events));
1759
- } catch (err) {
1760
- return engineFailure(req, err, log);
1761
- }
1762
- };
1763
- }
1764
- function packHandler(deps) {
1765
- const log = deps.log ?? ((err) => console.error("substrate-nl:", err));
1766
- return async (req) => {
1767
- const ns = req.params.ns ?? "";
1768
- let served;
1769
- try {
1770
- served = await deps.packs.get(ns, req);
1771
- } catch (err) {
1772
- return engineFailure(req, err, log);
1773
- }
1774
- if (served === void 0) return jsonResponse(404, {
1775
- error: `unknown namespace '${ns}'`,
1776
- code: "nl_unknown_namespace"
1777
- });
1778
- if (req.headers["if-none-match"] === served.etag) return {
1779
- status: 304,
1780
- headers: {
1781
- etag: served.etag,
1782
- ...VARY
1783
- }
1784
- };
1785
- return jsonResponse(200, served.pack, {
1786
- etag: served.etag,
1787
- "cache-control": "private, no-cache",
1788
- ...VARY
1789
- });
1790
- };
1791
- }
1792
-
1793
- //#endregion
1794
- //#region src/plugin.ts
1795
- /** The routes rely on `KernelRouteClaim.capability`, which every 1.x host honours. */
1796
- const CONTRACT_VERSION = ">=1.0.0-alpha.0 <2.0.0";
1797
- function createNlPlugin(cfg) {
1798
- const packs = new PackService({
1799
- engine: cfg.engine,
1800
- ...cfg.rulings !== void 0 ? { rulings: cfg.rulings } : {},
1801
- ...cfg.packTtlMs !== void 0 ? { ttlMs: cfg.packTtlMs } : {}
1802
- });
1803
- const deps = {
1804
- engine: cfg.engine,
1805
- packs,
1806
- ...cfg.judge !== void 0 ? { judge: cfg.judge } : {},
1807
- ...cfg.judgeTimeoutMs !== void 0 ? { judgeTimeoutMs: cfg.judgeTimeoutMs } : {}
1808
- };
1809
- return {
1810
- name: "substrate-nl",
1811
- contractVersion: CONTRACT_VERSION,
1812
- kernelRoutes: [{
1813
- path: "nl",
1814
- method: "POST",
1815
- handler: askHandler(deps),
1816
- capability: "read"
1817
- }, {
1818
- path: "nl/pack/:ns",
1819
- method: "GET",
1820
- handler: packHandler(deps),
1821
- capability: "read"
1822
- }]
1823
- };
1824
- }
1825
-
1826
- //#endregion
1827
- //#region src/bootstrap.ts
1828
- /**
1829
- * Structured-config bootstrap for `@mnmal-ai/substrate-nl`.
1830
- *
1831
- * Operator-overridable (`<pluginDir>/substrate-nl.config.json`):
1832
- * - `judge` optional; Ollama for the constrained judge. Absent = parser-only:
1833
- * every escalation is an honest hand-off.
1834
- * - `rulings` optional; per-namespace override merged over declared rulings.
1835
- * - `packTtlMs` how long a served pack is reused. Default 300000.
1836
- * Host-supplied (`hostDeps.nlEngine`): schema, operators and query access.
1837
- */
1838
- const JudgeSchema = z.object({
1839
- baseUrl: z.url(),
1840
- model: z.string().min(1),
1841
- timeoutMs: z.number().int().positive().default(2e4)
1842
- }).strict();
1843
- const NlBootstrapConfigSchema = z.object({
1844
- judge: JudgeSchema.optional(),
1845
- rulings: z.record(z.string(), NamespaceRulingsSchema).optional(),
1846
- packTtlMs: z.number().int().positive().default(3e5)
1847
- }).strict();
1848
- const bootstrap = defineBootstrap.kernel({
1849
- schema: NlBootstrapConfigSchema,
1850
- build: (config, deps) => createNlPlugin({
1851
- engine: deps.nlEngine,
1852
- packTtlMs: config.packTtlMs,
1853
- ...config.judge !== void 0 ? {
1854
- judge: new OllamaJudge(config.judge),
1855
- judgeTimeoutMs: config.judge.timeoutMs
1856
- } : {},
1857
- ...config.rulings !== void 0 ? { rulings: config.rulings } : {}
1858
- })
1859
- });
1860
-
1861
- //#endregion
1862
- export { askHandler as a, profileNamespace as c, mergeRulings as d, readRulings as f, parseQuestion as g, parseWithJudge as h, createNlPlugin as i, buildNamespacePack as l, runAsk as m, bootstrap as n, packHandler as o, OllamaJudge as p, CONTRACT_VERSION as r, PackService as s, NlBootstrapConfigSchema as t, NamespaceRulingsSchema as u };