@orkestrel/interpret 0.0.3 → 0.0.5
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 +1 -1
- package/dist/src/core/index.cjs +2673 -0
- package/dist/src/core/index.cjs.map +1 -0
- package/dist/src/core/index.d.cts +2110 -0
- package/dist/src/core/index.d.ts +2110 -0
- package/dist/src/core/index.js +2605 -0
- package/dist/src/core/index.js.map +1 -0
- package/package.json +4 -2
|
@@ -0,0 +1,2673 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _orkestrel_contract = require("@orkestrel/contract");
|
|
3
|
+
let _orkestrel_reason = require("@orkestrel/reason");
|
|
4
|
+
let _orkestrel_emitter = require("@orkestrel/emitter");
|
|
5
|
+
let _orkestrel_template = require("@orkestrel/template");
|
|
6
|
+
//#region src/core/constants.ts
|
|
7
|
+
/**
|
|
8
|
+
* Default `similarity` for `createInterpret` / `matchAlias` — the fuzzy
|
|
9
|
+
* alias-match score threshold (0..1).
|
|
10
|
+
*
|
|
11
|
+
* @remarks
|
|
12
|
+
* Domain-qualified (not a bare `DEFAULT_SIMILARITY`) so the name stays free
|
|
13
|
+
* of collision on the shared `@src/core` barrel, mirroring the
|
|
14
|
+
* `DEFAULT_REASON_BAIL` precedent.
|
|
15
|
+
*/
|
|
16
|
+
var DEFAULT_INTERPRET_SIMILARITY = .8;
|
|
17
|
+
/**
|
|
18
|
+
* Default `floor` for `createInterpret` / `matchTemplate` — the minimum
|
|
19
|
+
* intent confidence a template match (or the classified intent itself) must
|
|
20
|
+
* clear.
|
|
21
|
+
*/
|
|
22
|
+
var DEFAULT_INTERPRET_FLOOR = .3;
|
|
23
|
+
/** Default `history` cap for an `InterpretContext`'s `previous()` ring buffer. */
|
|
24
|
+
var DEFAULT_INTERPRET_HISTORY = 16;
|
|
25
|
+
/** Default `id` for an `Interpret` orchestrator. */
|
|
26
|
+
var INTERPRET_ID = "interpret";
|
|
27
|
+
/** Confidence assigned to an exact keyword-proximity entity match. */
|
|
28
|
+
var CONFIDENCE_EXACT = 1;
|
|
29
|
+
/** Confidence assigned to an exact alias-phrase entity match. */
|
|
30
|
+
var CONFIDENCE_ALIAS = .9;
|
|
31
|
+
/** Confidence assigned when a single entity mapping collects every extracted number. */
|
|
32
|
+
var CONFIDENCE_COLLECT = .9;
|
|
33
|
+
/** Confidence assigned to a positional (order-based) entity match fallback. */
|
|
34
|
+
var CONFIDENCE_POSITIONAL = .7;
|
|
35
|
+
/** Confidence assigned to a same-domain carried-over field. */
|
|
36
|
+
var CONFIDENCE_CARRIED = .7;
|
|
37
|
+
/** Confidence assigned to a template default fill. */
|
|
38
|
+
var CONFIDENCE_DEFAULT = 1;
|
|
39
|
+
/** Confidence assigned to a successfully resolved computed field. */
|
|
40
|
+
var CONFIDENCE_COMPUTED = .9;
|
|
41
|
+
/**
|
|
42
|
+
* The numeric-entity extraction pattern shared by `extractNumbers` and
|
|
43
|
+
* `assignEntities` — an optional leading `$`, thousands-comma-grouped digits,
|
|
44
|
+
* an optional decimal fraction, and an optional trailing `%`.
|
|
45
|
+
*
|
|
46
|
+
* @remarks
|
|
47
|
+
* Carries the global flag, so every call site builds a fresh `RegExp` from
|
|
48
|
+
* `.source` / `.flags` (mirrors the core-root `PLACEHOLDER_PATTERN` pattern)
|
|
49
|
+
* rather than sharing this instance's mutable `lastIndex` across scans.
|
|
50
|
+
*/
|
|
51
|
+
var NUMBER_PATTERN = /(?:\$\s*)?(\d+(?:,\d{3})*(?:\.\d+)?)\s*%?/g;
|
|
52
|
+
/**
|
|
53
|
+
* Prototype-pollution-unsafe field-path segments — `setField` refuses to
|
|
54
|
+
* write ANY path containing one, returning its input unchanged.
|
|
55
|
+
*/
|
|
56
|
+
var UNSAFE_FIELD_SEGMENTS = Object.freeze([
|
|
57
|
+
"__proto__",
|
|
58
|
+
"prototype",
|
|
59
|
+
"constructor"
|
|
60
|
+
]);
|
|
61
|
+
/**
|
|
62
|
+
* Neutral built-in contraction expansions for `Normalizer` — small on
|
|
63
|
+
* purpose; callers merge their own map over this one.
|
|
64
|
+
*/
|
|
65
|
+
var DEFAULT_CONTRACTIONS = Object.freeze({
|
|
66
|
+
"can't": "cannot",
|
|
67
|
+
"won't": "will not",
|
|
68
|
+
"it's": "it is",
|
|
69
|
+
"don't": "do not"
|
|
70
|
+
});
|
|
71
|
+
/** Neutral built-in abbreviation expansions for `Normalizer` — empty by default. */
|
|
72
|
+
var DEFAULT_ABBREVIATIONS = Object.freeze({});
|
|
73
|
+
/** Neutral built-in misspelling corrections for `Normalizer` — empty by default. */
|
|
74
|
+
var DEFAULT_CORRECTIONS = Object.freeze({});
|
|
75
|
+
/** Neutral built-in action-verb vocabulary for `Extractor#extract`'s intent classification — empty by default. */
|
|
76
|
+
var DEFAULT_ACTIONS = Object.freeze({});
|
|
77
|
+
/** Neutral built-in domain-keyword vocabulary for `Extractor#extract`'s intent classification — empty by default. */
|
|
78
|
+
var DEFAULT_DOMAINS = Object.freeze({});
|
|
79
|
+
/** Neutral built-in intent-verb phrasing for `Formatter#format` — empty by default. */
|
|
80
|
+
var DEFAULT_VERBS = Object.freeze({});
|
|
81
|
+
/**
|
|
82
|
+
* The neutral default `Lexicon` a `Narrator` merges caller data over.
|
|
83
|
+
*
|
|
84
|
+
* @remarks
|
|
85
|
+
* `phrases` and `labels` are empty — there is no built-in vocabulary or
|
|
86
|
+
* label overrides (AGENTS §21 mechanism-never-policy). `templates` carries
|
|
87
|
+
* the structural, display-neutral strings the reverse helpers formerly
|
|
88
|
+
* hardcoded, keyed by
|
|
89
|
+
* `{table}.{reasoning}` for the four reasons kinds, `result.quantitative.failed`
|
|
90
|
+
* for the quantitative-result failure suffix, and `subject.fields` /
|
|
91
|
+
* `subject.empty` for `describeSubject`. Every string is a plain
|
|
92
|
+
* @orkestrel/template `fillTemplate` template — `{{name}}`-style placeholders
|
|
93
|
+
* resolved against the caller-supplied `values` record.
|
|
94
|
+
*/
|
|
95
|
+
var DEFAULT_LEXICON = Object.freeze({
|
|
96
|
+
phrases: Object.freeze({}),
|
|
97
|
+
labels: Object.freeze({}),
|
|
98
|
+
templates: Object.freeze({
|
|
99
|
+
"definition.quantitative": "{{name}}: {{count}} factor group(s)",
|
|
100
|
+
"definition.logical": "{{name}}: {{count}} rule(s), strategy {{strategy}}",
|
|
101
|
+
"definition.symbolic": "{{name}}: solve {{count}} equation(s)",
|
|
102
|
+
"definition.inferential": "{{name}}: {{facts}} fact(s)/{{inferences}} inference(s), {{strategy}}",
|
|
103
|
+
"result.quantitative": "scored {{value}} across {{count}} group(s)",
|
|
104
|
+
"result.quantitative.failed": "; failed: {{errors}}",
|
|
105
|
+
"result.logical": "{{status}}: {{count}} rule(s)",
|
|
106
|
+
"result.symbolic": "solved {{solved}}",
|
|
107
|
+
"result.inferential": "derived {{count}} fact(s)",
|
|
108
|
+
"subject.fields": "with {{fields}}",
|
|
109
|
+
"subject.empty": "with no fields"
|
|
110
|
+
})
|
|
111
|
+
});
|
|
112
|
+
//#endregion
|
|
113
|
+
//#region src/core/errors.ts
|
|
114
|
+
/**
|
|
115
|
+
* An error thrown by the interprets layer.
|
|
116
|
+
*
|
|
117
|
+
* @remarks
|
|
118
|
+
* Thrown for: an injected stage implementation throwing during its phase
|
|
119
|
+
* (`NORMALIZE_FAILED` / `EXTRACT_FAILED` / `CLARIFY_FAILED` /
|
|
120
|
+
* `FORMAT_FAILED` / `GENERATE_FAILED`), `createTemplate` handed data that
|
|
121
|
+
* fails `isTemplate` (`INVALID_TEMPLATE`), and any use of a destroyed
|
|
122
|
+
* `Interpret` / manager / context (`DESTROYED`). `NO_TEMPLATE` and
|
|
123
|
+
* `LOW_CONFIDENCE` never throw — they surface as a visible incomplete
|
|
124
|
+
* {@link Interpretation} instead (never an arbitrary fallback template).
|
|
125
|
+
* `context`, when present, carries the offending stage / template id.
|
|
126
|
+
*/
|
|
127
|
+
var InterpretError = class extends Error {
|
|
128
|
+
code;
|
|
129
|
+
context;
|
|
130
|
+
constructor(code, message, context) {
|
|
131
|
+
super(message);
|
|
132
|
+
this.name = "InterpretError";
|
|
133
|
+
this.code = code;
|
|
134
|
+
this.context = context;
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* Narrow an unknown caught value to an {@link InterpretError}.
|
|
139
|
+
*
|
|
140
|
+
* @param value - The value to test (typically a `catch` binding)
|
|
141
|
+
* @returns `true` when `value` is an {@link InterpretError}
|
|
142
|
+
*
|
|
143
|
+
* @example
|
|
144
|
+
* ```ts
|
|
145
|
+
* import { isInterpretError } from '@src/core'
|
|
146
|
+
*
|
|
147
|
+
* try {
|
|
148
|
+
* interpret.template('missing')
|
|
149
|
+
* } catch (error) {
|
|
150
|
+
* if (isInterpretError(error) && error.code === 'DESTROYED') return
|
|
151
|
+
* }
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
function isInterpretError(value) {
|
|
155
|
+
return value instanceof InterpretError;
|
|
156
|
+
}
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region src/core/validators.ts
|
|
159
|
+
/**
|
|
160
|
+
* Determine whether a value is an {@link EntityMapping} — a literal
|
|
161
|
+
* alias-phrase extraction rule pointing at a subject field.
|
|
162
|
+
*
|
|
163
|
+
* @param value - The value to test
|
|
164
|
+
* @returns `true` when `value` is a well-formed entity mapping
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* ```ts
|
|
168
|
+
* import { isEntityMapping } from '@src/core'
|
|
169
|
+
*
|
|
170
|
+
* isEntityMapping({ entity: 'age', aliases: ['years old'], field: 'age' }) // true
|
|
171
|
+
* isEntityMapping({ entity: 'age', aliases: [/\d+/], field: 'age' }) // false — RegExp alias
|
|
172
|
+
* ```
|
|
173
|
+
*/
|
|
174
|
+
function isEntityMapping(value) {
|
|
175
|
+
return (0, _orkestrel_contract.recordOf)({
|
|
176
|
+
entity: _orkestrel_contract.isString,
|
|
177
|
+
aliases: (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isString),
|
|
178
|
+
field: _orkestrel_reason.isFieldPath,
|
|
179
|
+
required: _orkestrel_contract.isBoolean
|
|
180
|
+
}, ["required"])(value);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Determine whether a value is a {@link FieldDefault} — a fallback value a
|
|
184
|
+
* {@link Template} fills onto an unresolved field.
|
|
185
|
+
*
|
|
186
|
+
* @remarks
|
|
187
|
+
* `value` is unconstrained (any value, including `null` or `undefined`) as
|
|
188
|
+
* long as the key is present — the trivially-true guard `notOf(unionOf())`
|
|
189
|
+
* mirrors the reasons `Check.value` precedent.
|
|
190
|
+
*
|
|
191
|
+
* @param value - The value to test
|
|
192
|
+
* @returns `true` when `value` is a well-formed field default
|
|
193
|
+
*
|
|
194
|
+
* @example
|
|
195
|
+
* ```ts
|
|
196
|
+
* import { isFieldDefault } from '@src/core'
|
|
197
|
+
*
|
|
198
|
+
* isFieldDefault({ field: 'term', value: 12 }) // true
|
|
199
|
+
* isFieldDefault({ field: 'term' }) // false — value missing
|
|
200
|
+
* ```
|
|
201
|
+
*/
|
|
202
|
+
function isFieldDefault(value) {
|
|
203
|
+
return (0, _orkestrel_contract.recordOf)({
|
|
204
|
+
field: _orkestrel_reason.isFieldPath,
|
|
205
|
+
value: (0, _orkestrel_contract.notOf)((0, _orkestrel_contract.unionOf)())
|
|
206
|
+
})(value);
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Determine whether a value is a {@link ComputedField} — a declaratively
|
|
210
|
+
* computed field carrying a reasons {@link SymbolicExpression} tree.
|
|
211
|
+
*
|
|
212
|
+
* @param value - The value to test
|
|
213
|
+
* @returns `true` when `value` is a well-formed computed field
|
|
214
|
+
*
|
|
215
|
+
* @example
|
|
216
|
+
* ```ts
|
|
217
|
+
* import { constant, operation, variable } from '@orkestrel/reason'
|
|
218
|
+
* import { isComputedField } from '@src/core'
|
|
219
|
+
*
|
|
220
|
+
* isComputedField({
|
|
221
|
+
* field: 'monthly',
|
|
222
|
+
* expression: operation('divide', variable('deductible'), constant(12)),
|
|
223
|
+
* }) // true
|
|
224
|
+
* isComputedField({ field: 'monthly', expression: { form: 'variable' } }) // false — name missing
|
|
225
|
+
* ```
|
|
226
|
+
*/
|
|
227
|
+
function isComputedField(value) {
|
|
228
|
+
return (0, _orkestrel_contract.recordOf)({
|
|
229
|
+
field: _orkestrel_reason.isFieldPath,
|
|
230
|
+
expression: _orkestrel_reason.isSymbolicExpression
|
|
231
|
+
})(value);
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Determine whether a value is a {@link Template} — a named, versionable
|
|
235
|
+
* interpretation template.
|
|
236
|
+
*
|
|
237
|
+
* @remarks
|
|
238
|
+
* `definition` is validated with reasons' `isDefinition` — a `Template`'s
|
|
239
|
+
* definition is already expressed in terrain reasons vocabulary, so no
|
|
240
|
+
* parallel interprets-owned definition guard exists.
|
|
241
|
+
*
|
|
242
|
+
* @param value - The value to test
|
|
243
|
+
* @returns `true` when `value` is a well-formed template
|
|
244
|
+
*
|
|
245
|
+
* @example
|
|
246
|
+
* ```ts
|
|
247
|
+
* import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
|
|
248
|
+
* import { isTemplate } from '@src/core'
|
|
249
|
+
*
|
|
250
|
+
* isTemplate({
|
|
251
|
+
* id: 't1',
|
|
252
|
+
* name: 'Arithmetic',
|
|
253
|
+
* domain: 'arithmetic',
|
|
254
|
+
* intents: ['calculate'],
|
|
255
|
+
* mappings: [],
|
|
256
|
+
* defaults: [],
|
|
257
|
+
* computations: [],
|
|
258
|
+
* definition: quantitativeDefinition('t1', 'Arithmetic', [
|
|
259
|
+
* factorGroup('total', 'sum', [fieldFactor('value', 'value')]),
|
|
260
|
+
* ]),
|
|
261
|
+
* }) // true
|
|
262
|
+
* isTemplate({ id: 't1' }) // false — most fields missing
|
|
263
|
+
* ```
|
|
264
|
+
*/
|
|
265
|
+
function isTemplate(value) {
|
|
266
|
+
return (0, _orkestrel_contract.recordOf)({
|
|
267
|
+
id: _orkestrel_contract.isString,
|
|
268
|
+
name: _orkestrel_contract.isString,
|
|
269
|
+
domain: _orkestrel_contract.isString,
|
|
270
|
+
intents: (0, _orkestrel_contract.arrayOf)(_orkestrel_contract.isString),
|
|
271
|
+
mappings: (0, _orkestrel_contract.arrayOf)(isEntityMapping),
|
|
272
|
+
defaults: (0, _orkestrel_contract.arrayOf)(isFieldDefault),
|
|
273
|
+
computations: (0, _orkestrel_contract.arrayOf)(isComputedField),
|
|
274
|
+
definition: _orkestrel_reason.isDefinition
|
|
275
|
+
})(value);
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/core/helpers.ts
|
|
279
|
+
/**
|
|
280
|
+
* Escape every regex metacharacter in `text` so it matches literally when
|
|
281
|
+
* compiled into a `RegExp`.
|
|
282
|
+
*
|
|
283
|
+
* @param text - The literal text to escape
|
|
284
|
+
* @returns `text` with every regex metacharacter backslash-escaped
|
|
285
|
+
*
|
|
286
|
+
* @example
|
|
287
|
+
* ```ts
|
|
288
|
+
* import { escapeRegExp } from '@src/core'
|
|
289
|
+
*
|
|
290
|
+
* escapeRegExp('a.b*c') // 'a\\.b\\*c'
|
|
291
|
+
* new RegExp(escapeRegExp('a.b*c')).test('a.b*c') // true
|
|
292
|
+
* ```
|
|
293
|
+
*/
|
|
294
|
+
function escapeRegExp(text) {
|
|
295
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Copy-on-write write a value at a (possibly nested) field path on a subject.
|
|
299
|
+
*
|
|
300
|
+
* @remarks
|
|
301
|
+
* Never mutates `subject` — every level a `field` array descends through is
|
|
302
|
+
* freshly copied, so the input and every intermediate record stay untouched
|
|
303
|
+
* (AGENTS §11). Prototype-pollution-safe: a `field` containing `__proto__`,
|
|
304
|
+
* `prototype`, or `constructor` at ANY segment (checked against
|
|
305
|
+
* `UNSAFE_FIELD_SEGMENTS`) is refused as a no-op, returning `subject`
|
|
306
|
+
* unchanged. A non-record value already sitting at an intermediate segment is
|
|
307
|
+
* replaced by a fresh record rather than descended into.
|
|
308
|
+
*
|
|
309
|
+
* @param subject - The subject to derive from
|
|
310
|
+
* @param field - The (possibly nested) field path to write
|
|
311
|
+
* @param value - The value to write
|
|
312
|
+
* @returns A fresh subject with `value` written at `field`, or `subject`
|
|
313
|
+
* unchanged when `field` carries an unsafe segment
|
|
314
|
+
*
|
|
315
|
+
* @example
|
|
316
|
+
* ```ts
|
|
317
|
+
* import { setField } from '@src/core'
|
|
318
|
+
*
|
|
319
|
+
* setField({ age: 25 }, 'age', 30) // { age: 30 }
|
|
320
|
+
* setField({}, ['address', 'city'], 'Reno') // { address: { city: 'Reno' } }
|
|
321
|
+
* setField({}, ['__proto__', 'polluted'], true) // {} — refused, unchanged
|
|
322
|
+
* ```
|
|
323
|
+
*/
|
|
324
|
+
/**
|
|
325
|
+
* Derive the sibling field path for a computed aggregate of `field` — the
|
|
326
|
+
* suffix is appended to `field`'s OWN last segment, so the aggregate nests
|
|
327
|
+
* beside the source field rather than flattening past it.
|
|
328
|
+
*
|
|
329
|
+
* @remarks
|
|
330
|
+
* For an array {@link FieldPath} (e.g. `['address', 'amounts']`) with suffix
|
|
331
|
+
* `'Sum'` the result is `['address', 'amountsSum']` — nested beside
|
|
332
|
+
* `address.amounts`. For a plain string field the result stays a flat string
|
|
333
|
+
* (`'amounts'` → `'amountsSum'`), matching the existing single-key behavior.
|
|
334
|
+
*
|
|
335
|
+
* @param field - The source field path
|
|
336
|
+
* @param suffix - The aggregate suffix (`'Sum'`, `'Count'`, `'Average'`, `'Minimum'`, `'Maximum'`)
|
|
337
|
+
* @returns The sibling field path for the aggregate
|
|
338
|
+
*
|
|
339
|
+
* @example
|
|
340
|
+
* ```ts
|
|
341
|
+
* import { deriveAggregateField } from '@src/core'
|
|
342
|
+
*
|
|
343
|
+
* deriveAggregateField(['address', 'amounts'], 'Sum') // ['address', 'amountsSum']
|
|
344
|
+
* deriveAggregateField('amounts', 'Sum') // 'amountsSum'
|
|
345
|
+
* ```
|
|
346
|
+
*/
|
|
347
|
+
function deriveAggregateField(field, suffix) {
|
|
348
|
+
if (Array.isArray(field)) {
|
|
349
|
+
const last = field[field.length - 1];
|
|
350
|
+
return [...field.slice(0, -1), `${last}${suffix}`];
|
|
351
|
+
}
|
|
352
|
+
return `${field}${suffix}`;
|
|
353
|
+
}
|
|
354
|
+
function setField(subject, field, value) {
|
|
355
|
+
const path = Array.isArray(field) ? field : [field];
|
|
356
|
+
if (path.length === 0) return subject;
|
|
357
|
+
if (path.some((segment) => UNSAFE_FIELD_SEGMENTS.includes(segment))) return subject;
|
|
358
|
+
const [key, ...rest] = path;
|
|
359
|
+
if (key === void 0) return subject;
|
|
360
|
+
if (rest.length === 0) return {
|
|
361
|
+
...subject,
|
|
362
|
+
[key]: value
|
|
363
|
+
};
|
|
364
|
+
const child = subject[key];
|
|
365
|
+
const nested = (0, _orkestrel_contract.isRecord)(child) ? child : {};
|
|
366
|
+
return {
|
|
367
|
+
...subject,
|
|
368
|
+
[key]: setField(nested, rest, value)
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Replace every whole-word occurrence of a map's keys with their values.
|
|
373
|
+
*
|
|
374
|
+
* @remarks
|
|
375
|
+
* Word-boundary safe (`in` never matches inside `information`) and
|
|
376
|
+
* case-insensitive; each key is regex-escaped via the core-root
|
|
377
|
+
* `escapeRegExp` before compiling, so a caller-supplied phrase containing
|
|
378
|
+
* regex metacharacters is matched literally. Multiple keys apply in
|
|
379
|
+
* `Object.entries` order — the `Normalizer` stage sequences its three maps
|
|
380
|
+
* (contractions, abbreviations, corrections) with three separate calls.
|
|
381
|
+
*
|
|
382
|
+
* @param text - The text to substitute within
|
|
383
|
+
* @param map - The `{ from: to }` substitution map
|
|
384
|
+
* @returns `text` with every whole-word match replaced
|
|
385
|
+
*
|
|
386
|
+
* @example
|
|
387
|
+
* ```ts
|
|
388
|
+
* import { applyReplacements } from '@src/core'
|
|
389
|
+
*
|
|
390
|
+
* applyReplacements("can't stop", { "can't": 'cannot' }) // 'cannot stop'
|
|
391
|
+
* applyReplacements('information', { in: 'IN' }) // 'information' — word-boundary safe
|
|
392
|
+
* ```
|
|
393
|
+
*/
|
|
394
|
+
function applyReplacements(text, map) {
|
|
395
|
+
let result = text;
|
|
396
|
+
for (const [from, to] of Object.entries(map)) {
|
|
397
|
+
const pattern = new RegExp(`\\b${escapeRegExp(from)}\\b`, "gi");
|
|
398
|
+
result = result.replace(pattern, to);
|
|
399
|
+
}
|
|
400
|
+
return result;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Collapse every run of whitespace to a single space and trim the ends.
|
|
404
|
+
*
|
|
405
|
+
* @param text - The text to collapse
|
|
406
|
+
* @returns The collapsed text
|
|
407
|
+
*
|
|
408
|
+
* @example
|
|
409
|
+
* ```ts
|
|
410
|
+
* import { collapseWhitespace } from '@src/core'
|
|
411
|
+
*
|
|
412
|
+
* collapseWhitespace(' a b\t c ') // 'a b c'
|
|
413
|
+
* ```
|
|
414
|
+
*/
|
|
415
|
+
function collapseWhitespace(text) {
|
|
416
|
+
return text.replace(/\s+/g, " ").trim();
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Split text into lowercase tokens, stripping punctuation outside a small
|
|
420
|
+
* numeric/currency-safe allowlist.
|
|
421
|
+
*
|
|
422
|
+
* @remarks
|
|
423
|
+
* Shared by `classifyIntent` and `assignEntities` — pure ECMAScript
|
|
424
|
+
* (no locale-aware `Intl` segmentation), so multi-byte / astral text tokenizes
|
|
425
|
+
* on ASCII word boundaries only.
|
|
426
|
+
*
|
|
427
|
+
* @param text - The text to tokenize
|
|
428
|
+
* @returns The lowercase tokens, punctuation-stripped, empty tokens dropped
|
|
429
|
+
*
|
|
430
|
+
* @example
|
|
431
|
+
* ```ts
|
|
432
|
+
* import { tokenize } from '@src/core'
|
|
433
|
+
*
|
|
434
|
+
* tokenize('The rate is 85%.') // ['the', 'rate', 'is', '85%']
|
|
435
|
+
* ```
|
|
436
|
+
*/
|
|
437
|
+
function tokenize(text) {
|
|
438
|
+
return text.toLowerCase().replace(/[^a-z0-9\s./%$'-]/g, " ").split(/\s+/).filter((token) => token.length > 0);
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Mine every numeric literal from text — optional leading `$`, thousands
|
|
442
|
+
* commas, an optional decimal fraction, an optional trailing `%`.
|
|
443
|
+
*
|
|
444
|
+
* @remarks
|
|
445
|
+
* Numbers-only: this is the module's entire extraction contract (AGENTS
|
|
446
|
+
* §21 mechanism-never-policy) — no date, text-entity, or negation parsing.
|
|
447
|
+
*
|
|
448
|
+
* @param text - The text to scan
|
|
449
|
+
* @returns Every extracted number, in left-to-right order
|
|
450
|
+
*
|
|
451
|
+
* @example
|
|
452
|
+
* ```ts
|
|
453
|
+
* import { extractNumbers } from '@src/core'
|
|
454
|
+
*
|
|
455
|
+
* extractNumbers('income was $50,000, age 25') // [50000, 25]
|
|
456
|
+
* ```
|
|
457
|
+
*/
|
|
458
|
+
function extractNumbers(text) {
|
|
459
|
+
const pattern = new RegExp(NUMBER_PATTERN.source, NUMBER_PATTERN.flags);
|
|
460
|
+
const numbers = [];
|
|
461
|
+
let match = pattern.exec(text);
|
|
462
|
+
while (match !== null) {
|
|
463
|
+
const raw = match[1];
|
|
464
|
+
if (raw !== void 0) {
|
|
465
|
+
const value = Number(raw.replace(/,/g, ""));
|
|
466
|
+
if (Number.isFinite(value)) numbers.push(value);
|
|
467
|
+
}
|
|
468
|
+
match = pattern.exec(text);
|
|
469
|
+
}
|
|
470
|
+
return numbers;
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Assign already-extracted numbers to a matched template's entity mappings.
|
|
474
|
+
*
|
|
475
|
+
* @remarks
|
|
476
|
+
* Strategy, in order: (1) a SINGLE mapping collects every number (an array
|
|
477
|
+
* when more than one, a scalar otherwise) at `CONFIDENCE_COLLECT`. Otherwise,
|
|
478
|
+
* per mapping, the rightmost token in the text that equals the entity name
|
|
479
|
+
* (`CONFIDENCE_EXACT`), an alias exactly (`CONFIDENCE_ALIAS`), or an alias
|
|
480
|
+
* fuzzily (via `matchAlias`, confidence = its returned score) becomes a
|
|
481
|
+
* keyword anchor; anchors sort left-to-right and each claims its nearest
|
|
482
|
+
* unused number by text position. (3) Any mapping still unfilled claims the
|
|
483
|
+
* next unused number positionally, at `CONFIDENCE_POSITIONAL`. Every entity
|
|
484
|
+
* carries provenance `category: 'extracted'` with `detail` naming the
|
|
485
|
+
* strategy that filled it (`'collect' | 'keyword' | 'alias' | 'positional'`).
|
|
486
|
+
* Runs ONLY after a template has matched (an orchestrator-owned step, never
|
|
487
|
+
* inside `Extractor`, which stays template-agnostic).
|
|
488
|
+
*
|
|
489
|
+
* @param numbers - The numbers already extracted from `text` via `extractNumbers`
|
|
490
|
+
* @param mappings - The matched template's entity mappings
|
|
491
|
+
* @param text - The same text `numbers` was extracted from (for keyword proximity)
|
|
492
|
+
* @param similarity - The fuzzy alias-match score threshold (0..1)
|
|
493
|
+
* @returns The assigned entities, one per filled mapping
|
|
494
|
+
*
|
|
495
|
+
* @example
|
|
496
|
+
* ```ts
|
|
497
|
+
* import { assignEntities } from '@src/core'
|
|
498
|
+
*
|
|
499
|
+
* const mappings = [
|
|
500
|
+
* { entity: 'age', aliases: ['years old'], field: 'age' },
|
|
501
|
+
* { entity: 'score', aliases: ['credit score'], field: 'score' },
|
|
502
|
+
* ]
|
|
503
|
+
* assignEntities([25, 720], mappings, '25 year old with score 720', 0.8)
|
|
504
|
+
* // [{ name: 'age', value: 25, ... }, { name: 'score', value: 720, ... }]
|
|
505
|
+
* ```
|
|
506
|
+
*/
|
|
507
|
+
function assignEntities(numbers, mappings, text, similarity) {
|
|
508
|
+
if (mappings.length === 0 || numbers.length === 0) return [];
|
|
509
|
+
if (mappings.length === 1) {
|
|
510
|
+
const mapping = mappings[0];
|
|
511
|
+
if (mapping === void 0) return [];
|
|
512
|
+
return [{
|
|
513
|
+
name: mapping.entity,
|
|
514
|
+
value: numbers.length === 1 ? numbers[0] : numbers,
|
|
515
|
+
provenance: {
|
|
516
|
+
category: "extracted",
|
|
517
|
+
detail: "collect"
|
|
518
|
+
},
|
|
519
|
+
confidence: CONFIDENCE_COLLECT
|
|
520
|
+
}];
|
|
521
|
+
}
|
|
522
|
+
const tokens = tokenize(text);
|
|
523
|
+
const lowerText = text.toLowerCase();
|
|
524
|
+
const positions = [];
|
|
525
|
+
const positionPattern = new RegExp(NUMBER_PATTERN.source, NUMBER_PATTERN.flags);
|
|
526
|
+
let positionMatch = positionPattern.exec(text);
|
|
527
|
+
while (positionMatch !== null) {
|
|
528
|
+
positions.push(positionMatch.index);
|
|
529
|
+
positionMatch = positionPattern.exec(text);
|
|
530
|
+
}
|
|
531
|
+
const keywordMatches = [];
|
|
532
|
+
for (const mapping of mappings) {
|
|
533
|
+
let matchedPosition = -1;
|
|
534
|
+
let matchedConfidence = 0;
|
|
535
|
+
let matchedDetail = "keyword";
|
|
536
|
+
const entityToken = mapping.entity.toLowerCase();
|
|
537
|
+
for (const token of tokens) {
|
|
538
|
+
const tokenPosition = lowerText.indexOf(token);
|
|
539
|
+
if (token === entityToken) {
|
|
540
|
+
if (tokenPosition > matchedPosition) {
|
|
541
|
+
matchedPosition = tokenPosition;
|
|
542
|
+
matchedConfidence = 1;
|
|
543
|
+
matchedDetail = "keyword";
|
|
544
|
+
}
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
if (mapping.aliases.some((alias) => alias.toLowerCase() === token)) {
|
|
548
|
+
if (tokenPosition > matchedPosition) {
|
|
549
|
+
matchedPosition = tokenPosition;
|
|
550
|
+
matchedConfidence = CONFIDENCE_ALIAS;
|
|
551
|
+
matchedDetail = "alias";
|
|
552
|
+
}
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
const fuzzy = matchAlias(token, mapping.aliases, similarity);
|
|
556
|
+
if (fuzzy > 0 && tokenPosition > matchedPosition) {
|
|
557
|
+
matchedPosition = tokenPosition;
|
|
558
|
+
matchedConfidence = fuzzy;
|
|
559
|
+
matchedDetail = "alias";
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
if (matchedPosition >= 0) keywordMatches.push({
|
|
563
|
+
mapping,
|
|
564
|
+
position: matchedPosition,
|
|
565
|
+
confidence: matchedConfidence,
|
|
566
|
+
detail: matchedDetail
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
keywordMatches.sort((a, b) => a.position - b.position);
|
|
570
|
+
const used = /* @__PURE__ */ new Set();
|
|
571
|
+
const filled = /* @__PURE__ */ new Set();
|
|
572
|
+
const entities = [];
|
|
573
|
+
for (const match of keywordMatches) {
|
|
574
|
+
let bestIndex = -1;
|
|
575
|
+
let bestDistance = Number.POSITIVE_INFINITY;
|
|
576
|
+
for (let index = 0; index < numbers.length; index += 1) {
|
|
577
|
+
if (used.has(index)) continue;
|
|
578
|
+
const position = positions[index];
|
|
579
|
+
if (position === void 0) continue;
|
|
580
|
+
const distance = Math.abs(position - match.position);
|
|
581
|
+
if (distance < bestDistance) {
|
|
582
|
+
bestDistance = distance;
|
|
583
|
+
bestIndex = index;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
if (bestIndex >= 0) {
|
|
587
|
+
const value = numbers[bestIndex];
|
|
588
|
+
if (value !== void 0) {
|
|
589
|
+
used.add(bestIndex);
|
|
590
|
+
filled.add(match.mapping.entity);
|
|
591
|
+
entities.push({
|
|
592
|
+
name: match.mapping.entity,
|
|
593
|
+
value,
|
|
594
|
+
provenance: {
|
|
595
|
+
category: "extracted",
|
|
596
|
+
detail: match.detail
|
|
597
|
+
},
|
|
598
|
+
confidence: match.confidence
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
let numberIndex = 0;
|
|
604
|
+
for (const mapping of mappings) {
|
|
605
|
+
if (filled.has(mapping.entity)) continue;
|
|
606
|
+
while (numberIndex < numbers.length && used.has(numberIndex)) numberIndex += 1;
|
|
607
|
+
if (numberIndex >= numbers.length) break;
|
|
608
|
+
const value = numbers[numberIndex];
|
|
609
|
+
if (value !== void 0) {
|
|
610
|
+
used.add(numberIndex);
|
|
611
|
+
filled.add(mapping.entity);
|
|
612
|
+
entities.push({
|
|
613
|
+
name: mapping.entity,
|
|
614
|
+
value,
|
|
615
|
+
provenance: {
|
|
616
|
+
category: "extracted",
|
|
617
|
+
detail: "positional"
|
|
618
|
+
},
|
|
619
|
+
confidence: CONFIDENCE_POSITIONAL
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
numberIndex += 1;
|
|
623
|
+
}
|
|
624
|
+
return entities;
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Classify the action + domain intent of a text against caller-supplied
|
|
628
|
+
* vocabularies.
|
|
629
|
+
*
|
|
630
|
+
* @remarks
|
|
631
|
+
* `actions` maps a token to an action name — the first matching token in
|
|
632
|
+
* `text` (left to right) wins, at `CONFIDENCE_EXACT`. `domains` maps a domain
|
|
633
|
+
* name to its keyword list — the domain with the most matching tokens wins
|
|
634
|
+
* (ties keep the earliest-declared domain), also at `CONFIDENCE_EXACT`.
|
|
635
|
+
* Combined confidence (PINNED): both fire → their average; exactly one fires
|
|
636
|
+
* → its value times `0.5`; neither → `0`. There is no built-in worldview and
|
|
637
|
+
* no auto-classification from a registered template's own `domain` name — a
|
|
638
|
+
* caller MUST list a template's domain among `domains` for it to classify.
|
|
639
|
+
* No `floor` parameter: the confidence floor gate lives at the orchestrator's
|
|
640
|
+
* `matchTemplate` step, never inside classification itself.
|
|
641
|
+
*
|
|
642
|
+
* @param text - The (normalized) text to classify
|
|
643
|
+
* @param actions - The caller's token → action-name vocabulary
|
|
644
|
+
* @param domains - The caller's domain-name → keyword-list vocabulary
|
|
645
|
+
* @returns The classified intent
|
|
646
|
+
*
|
|
647
|
+
* @example
|
|
648
|
+
* ```ts
|
|
649
|
+
* import { classifyIntent } from '@src/core'
|
|
650
|
+
*
|
|
651
|
+
* classifyIntent('calculate my rate', { calculate: 'compute' }, { rating: ['rate'] })
|
|
652
|
+
* // { action: 'compute', domain: 'rating', confidence: 1 }
|
|
653
|
+
* classifyIntent('hello', {}, {}) // { action: '', domain: '', confidence: 0 }
|
|
654
|
+
* ```
|
|
655
|
+
*/
|
|
656
|
+
function classifyIntent(text, actions, domains) {
|
|
657
|
+
const tokens = tokenize(text);
|
|
658
|
+
let action = "";
|
|
659
|
+
let actionConfidence = 0;
|
|
660
|
+
for (const token of tokens) {
|
|
661
|
+
const mapped = actions[token];
|
|
662
|
+
if (mapped !== void 0) {
|
|
663
|
+
action = mapped;
|
|
664
|
+
actionConfidence = 1;
|
|
665
|
+
break;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
let domain = "";
|
|
669
|
+
let domainConfidence = 0;
|
|
670
|
+
let bestMatches = 0;
|
|
671
|
+
for (const [name, keywords] of Object.entries(domains)) {
|
|
672
|
+
const lowerKeywords = keywords.map((keyword) => keyword.toLowerCase());
|
|
673
|
+
let matches = 0;
|
|
674
|
+
for (const token of tokens) if (lowerKeywords.includes(token)) matches += 1;
|
|
675
|
+
if (matches > bestMatches) {
|
|
676
|
+
bestMatches = matches;
|
|
677
|
+
domain = name;
|
|
678
|
+
domainConfidence = 1;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
const confidence = actionConfidence > 0 && domainConfidence > 0 ? (actionConfidence + domainConfidence) / 2 : Math.max(actionConfidence, domainConfidence) * .5;
|
|
682
|
+
return {
|
|
683
|
+
action,
|
|
684
|
+
domain,
|
|
685
|
+
confidence
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Bigram (Dice coefficient) string similarity, case-insensitive.
|
|
690
|
+
*
|
|
691
|
+
* @param a - The first string
|
|
692
|
+
* @param b - The second string
|
|
693
|
+
* @returns A score in `[0, 1]` — `1` for an exact (case-insensitive) match,
|
|
694
|
+
* `0` when either string is shorter than 2 characters and they are not equal
|
|
695
|
+
*
|
|
696
|
+
* @example
|
|
697
|
+
* ```ts
|
|
698
|
+
* import { scoreSimilarity } from '@src/core'
|
|
699
|
+
*
|
|
700
|
+
* scoreSimilarity('rate', 'rate') // 1
|
|
701
|
+
* scoreSimilarity('rate', 'value') // 0 — no shared bigrams
|
|
702
|
+
* ```
|
|
703
|
+
*/
|
|
704
|
+
function scoreSimilarity(a, b) {
|
|
705
|
+
const left = a.toLowerCase();
|
|
706
|
+
const right = b.toLowerCase();
|
|
707
|
+
if (left === right) return 1;
|
|
708
|
+
if (left.length < 2 || right.length < 2) return 0;
|
|
709
|
+
const bigrams = /* @__PURE__ */ new Map();
|
|
710
|
+
for (let index = 0; index < left.length - 1; index += 1) {
|
|
711
|
+
const bigram = left.slice(index, index + 2);
|
|
712
|
+
bigrams.set(bigram, (bigrams.get(bigram) ?? 0) + 1);
|
|
713
|
+
}
|
|
714
|
+
let matches = 0;
|
|
715
|
+
for (let index = 0; index < right.length - 1; index += 1) {
|
|
716
|
+
const bigram = right.slice(index, index + 2);
|
|
717
|
+
const count = bigrams.get(bigram);
|
|
718
|
+
if (count !== void 0 && count > 0) {
|
|
719
|
+
bigrams.set(bigram, count - 1);
|
|
720
|
+
matches += 1;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
return 2 * matches / (left.length - 1 + (right.length - 1));
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* The best `scoreSimilarity` a token achieves against a list of aliases,
|
|
727
|
+
* gated by a threshold.
|
|
728
|
+
*
|
|
729
|
+
* @param token - The token to score
|
|
730
|
+
* @param aliases - The alias phrases to score against
|
|
731
|
+
* @param threshold - The minimum score to report (an explicit no-match below it)
|
|
732
|
+
* @returns The best score when it meets `threshold`, else `0`
|
|
733
|
+
*
|
|
734
|
+
* @example
|
|
735
|
+
* ```ts
|
|
736
|
+
* import { matchAlias } from '@src/core'
|
|
737
|
+
*
|
|
738
|
+
* matchAlias('valu', ['value', 'amount'], 0.6) // ~0.86 — fuzzy hit on 'value'
|
|
739
|
+
* matchAlias('xyz', ['value', 'amount'], 0.6) // 0 — no alias clears the threshold
|
|
740
|
+
* ```
|
|
741
|
+
*/
|
|
742
|
+
function matchAlias(token, aliases, threshold) {
|
|
743
|
+
let best = 0;
|
|
744
|
+
for (const alias of aliases) {
|
|
745
|
+
const score = scoreSimilarity(token, alias);
|
|
746
|
+
if (score > best) best = score;
|
|
747
|
+
}
|
|
748
|
+
return best >= threshold ? best : 0;
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Render a value into a canonical, key-order-stable string — the pre-image
|
|
752
|
+
* of `digestValue`.
|
|
753
|
+
*
|
|
754
|
+
* @remarks
|
|
755
|
+
* Ported from the app's `raters` digest machinery (`app/core/raters/helpers.ts`)
|
|
756
|
+
* — record keys sort before serialization so a re-ordered object canonicalizes
|
|
757
|
+
* identically; arrays keep position order (position is meaningful).
|
|
758
|
+
* Cycle-safe and total (AGENTS §14): `visited` tracks the object ancestors
|
|
759
|
+
* along the CURRENT recursion path (not a global "seen" set, so the same
|
|
760
|
+
* object reachable twice via non-cyclic sibling branches still canonicalizes
|
|
761
|
+
* normally); revisiting an ancestor renders that node as the literal string
|
|
762
|
+
* `'[cycle]'` instead of recursing — deterministic, never throws, never
|
|
763
|
+
* overflows the call stack.
|
|
764
|
+
*
|
|
765
|
+
* @param value - The value to canonicalize
|
|
766
|
+
* @param visited - The object ancestors along the current recursion path (internal; omit at the call site)
|
|
767
|
+
* @returns The canonical string form
|
|
768
|
+
*
|
|
769
|
+
* @example
|
|
770
|
+
* ```ts
|
|
771
|
+
* import { canonicalize } from '@src/core'
|
|
772
|
+
*
|
|
773
|
+
* canonicalize({ b: 1, a: 2 }) === canonicalize({ a: 2, b: 1 }) // true
|
|
774
|
+
* ```
|
|
775
|
+
*/
|
|
776
|
+
function canonicalize(value, visited = /* @__PURE__ */ new Set()) {
|
|
777
|
+
if (Array.isArray(value)) {
|
|
778
|
+
if (visited.has(value)) return JSON.stringify("[cycle]");
|
|
779
|
+
const nextVisited = new Set(visited);
|
|
780
|
+
nextVisited.add(value);
|
|
781
|
+
return `[${value.map((entry) => canonicalize(entry, nextVisited)).join(",")}]`;
|
|
782
|
+
}
|
|
783
|
+
if ((0, _orkestrel_contract.isRecord)(value)) {
|
|
784
|
+
if (visited.has(value)) return JSON.stringify("[cycle]");
|
|
785
|
+
const nextVisited = new Set(visited);
|
|
786
|
+
nextVisited.add(value);
|
|
787
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalize(value[key], nextVisited)}`).join(",")}}`;
|
|
788
|
+
}
|
|
789
|
+
return JSON.stringify(value) ?? "null";
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Compute a canonical structural digest of a pure-JSON value — a key-order-
|
|
793
|
+
* stable FNV-1a hash rendered as an 8-hex-digit string.
|
|
794
|
+
*
|
|
795
|
+
* @remarks
|
|
796
|
+
* Pure ECMAScript, no host crypto (AGENTS §17.7) — the same algorithm as the
|
|
797
|
+
* app's `digest`, ported into core so `Interpretation.digest` and the
|
|
798
|
+
* versioned managers can hash without leaving strict core.
|
|
799
|
+
*
|
|
800
|
+
* @param value - The value to digest
|
|
801
|
+
* @returns The 8-character hex digest
|
|
802
|
+
*
|
|
803
|
+
* @example
|
|
804
|
+
* ```ts
|
|
805
|
+
* import { digestValue } from '@src/core'
|
|
806
|
+
*
|
|
807
|
+
* digestValue({ a: 1 }) === digestValue({ a: 1 }) // true — deterministic
|
|
808
|
+
* ```
|
|
809
|
+
*/
|
|
810
|
+
function digestValue(value) {
|
|
811
|
+
const canonical = canonicalize(value);
|
|
812
|
+
let hash = 2166136261;
|
|
813
|
+
for (let index = 0; index < canonical.length; index += 1) {
|
|
814
|
+
hash ^= canonical.charCodeAt(index);
|
|
815
|
+
hash = Math.imul(hash, 16777619);
|
|
816
|
+
}
|
|
817
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Score how well a classified intent matches one template's domain + action.
|
|
821
|
+
*
|
|
822
|
+
* @param intent - The classified intent
|
|
823
|
+
* @param template - The candidate template
|
|
824
|
+
* @returns A score in `[0, 1]` — the mean of the domain match (`1`/`0`) and
|
|
825
|
+
* the action match (`1`/`0`, `template.intents` containing `intent.action`)
|
|
826
|
+
*
|
|
827
|
+
* @example
|
|
828
|
+
* ```ts
|
|
829
|
+
* import { scoreTemplate } from '@src/core'
|
|
830
|
+
*
|
|
831
|
+
* scoreTemplate(
|
|
832
|
+
* { action: 'compute', domain: 'rating', confidence: 1 },
|
|
833
|
+
* { id: 't1', name: 'T', domain: 'rating', intents: ['compute'], mappings: [], defaults: [], computations: [], definition: { reasoning: 'symbolic', id: 't1', name: 'T', equations: [], variables: {} } },
|
|
834
|
+
* ) // 1
|
|
835
|
+
* ```
|
|
836
|
+
*/
|
|
837
|
+
function scoreTemplate(intent, template) {
|
|
838
|
+
return ((template.domain.toLowerCase() === intent.domain.toLowerCase() ? 1 : 0) + (template.intents.some((candidate) => candidate.toLowerCase() === intent.action.toLowerCase()) ? 1 : 0)) / 2;
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Find the best-scoring registered template for a classified intent, gated
|
|
842
|
+
* by a confidence floor.
|
|
843
|
+
*
|
|
844
|
+
* @remarks
|
|
845
|
+
* Explicit no-match (AGENTS-flagged scsr defect 2 — never an arbitrary
|
|
846
|
+
* `templates[0]` fallback): an empty registry, or a best score strictly below
|
|
847
|
+
* `floor`, both return `undefined`.
|
|
848
|
+
*
|
|
849
|
+
* @param intent - The classified intent
|
|
850
|
+
* @param templates - The registered templates to score
|
|
851
|
+
* @param floor - The minimum score a match must clear
|
|
852
|
+
* @returns The best-scoring template, or `undefined` on no qualifying match
|
|
853
|
+
*
|
|
854
|
+
* @example
|
|
855
|
+
* ```ts
|
|
856
|
+
* import { matchTemplate } from '@src/core'
|
|
857
|
+
*
|
|
858
|
+
* matchTemplate({ action: '', domain: '', confidence: 0 }, [], 0.3) // undefined — empty registry
|
|
859
|
+
* ```
|
|
860
|
+
*/
|
|
861
|
+
function matchTemplate(intent, templates, floor) {
|
|
862
|
+
let best;
|
|
863
|
+
let bestScore = -1;
|
|
864
|
+
for (const template of templates) {
|
|
865
|
+
const score = scoreTemplate(intent, template);
|
|
866
|
+
if (score > bestScore) {
|
|
867
|
+
bestScore = score;
|
|
868
|
+
best = template;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
return best !== void 0 && bestScore >= floor ? best : void 0;
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Collect every variable name referenced by a symbolic expression tree, in
|
|
875
|
+
* first-occurrence order.
|
|
876
|
+
*
|
|
877
|
+
* @param expression - The expression tree to scan
|
|
878
|
+
* @returns The referenced variable names, deduplicated
|
|
879
|
+
*
|
|
880
|
+
* @example
|
|
881
|
+
* ```ts
|
|
882
|
+
* import { constant, operation, variable } from '@orkestrel/reason'
|
|
883
|
+
* import { variablesOf } from '@src/core'
|
|
884
|
+
*
|
|
885
|
+
* variablesOf(operation('divide', variable('deductible'), constant(12))) // ['deductible']
|
|
886
|
+
* ```
|
|
887
|
+
*/
|
|
888
|
+
function variablesOf(expression) {
|
|
889
|
+
const names = [];
|
|
890
|
+
const seen = /* @__PURE__ */ new Set();
|
|
891
|
+
function collect(node) {
|
|
892
|
+
if (node.form === "variable") {
|
|
893
|
+
if (!seen.has(node.name)) {
|
|
894
|
+
seen.add(node.name);
|
|
895
|
+
names.push(node.name);
|
|
896
|
+
}
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
if (node.form === "operation") {
|
|
900
|
+
collect(node.left);
|
|
901
|
+
if (node.right !== void 0) collect(node.right);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
collect(expression);
|
|
905
|
+
return names;
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Evaluate a symbolic expression tree against resolved bindings.
|
|
909
|
+
*
|
|
910
|
+
* @remarks
|
|
911
|
+
* THE critical leaf (design-pinned, engine-parity semantics): an absent
|
|
912
|
+
* `right` operand on a binary operation defaults to `0` — matching
|
|
913
|
+
* `SymbolicReasoner`'s internal `#evaluate` — and is always passed as an
|
|
914
|
+
* EXPLICIT numeric operand, so the same tree evaluates identically here and
|
|
915
|
+
* inside the engine. Each arithmetic step delegates to the reasons
|
|
916
|
+
* `applyOperation` pure function, mapping the node's `.operator` field onto
|
|
917
|
+
* its `operator` parameter. An unresolved input variable, or a non-finite
|
|
918
|
+
* result (`NaN` from a divide-by-zero, or an overflowing `±Infinity`),
|
|
919
|
+
* becomes a gap — `undefined`, never landing on a subject.
|
|
920
|
+
*
|
|
921
|
+
* @param expression - The expression tree to evaluate
|
|
922
|
+
* @param bindings - The resolved variable bindings
|
|
923
|
+
* @returns The evaluated number, or `undefined` on an unresolved input or a
|
|
924
|
+
* non-finite result
|
|
925
|
+
*
|
|
926
|
+
* @example
|
|
927
|
+
* ```ts
|
|
928
|
+
* import { constant, operation, variable } from '@orkestrel/reason'
|
|
929
|
+
* import { resolveExpression } from '@src/core'
|
|
930
|
+
*
|
|
931
|
+
* resolveExpression(operation('divide', variable('deductible'), constant(12)), { deductible: 6000 }) // 500
|
|
932
|
+
* resolveExpression(operation('divide', constant(1), constant(0)), {}) // undefined — NaN gap
|
|
933
|
+
* resolveExpression(variable('missing'), {}) // undefined — unresolved input
|
|
934
|
+
* ```
|
|
935
|
+
*/
|
|
936
|
+
function resolveExpression(expression, bindings) {
|
|
937
|
+
if (expression.form === "constant") return expression.value;
|
|
938
|
+
if (expression.form === "variable") return bindings[expression.name];
|
|
939
|
+
const left = resolveExpression(expression.left, bindings);
|
|
940
|
+
if (left === void 0) return void 0;
|
|
941
|
+
const right = expression.right === void 0 ? 0 : resolveExpression(expression.right, bindings);
|
|
942
|
+
if (right === void 0) return void 0;
|
|
943
|
+
const result = (0, _orkestrel_reason.applyOperation)(expression.operator, left, right);
|
|
944
|
+
return (0, _orkestrel_contract.isFiniteNumber)(result) ? result : void 0;
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Render a one-line, display-neutral description of a reasons `Subject`,
|
|
948
|
+
* through an injected `Narrator`.
|
|
949
|
+
*
|
|
950
|
+
* @remarks
|
|
951
|
+
* Complements — never duplicates — the raters `describe*` family (which
|
|
952
|
+
* describes RATERS artifacts); this describes REASONS artifacts. Every field
|
|
953
|
+
* renders via `narrator.label` + `narrator.value` (looked up under the
|
|
954
|
+
* `'units'` phrase table, falling back to `'plain'`) — the wording is fully
|
|
955
|
+
* lexicon-driven (AGENTS §21 mechanism-never-policy); `Definition` /
|
|
956
|
+
* `ReasonResult` narration lives on `Narrator#describe` / `Narrator#narrate`
|
|
957
|
+
* directly.
|
|
958
|
+
*
|
|
959
|
+
* @param subject - The subject to describe
|
|
960
|
+
* @param narrator - The lexicon-driven renderer to render field labels/values/lines through
|
|
961
|
+
* @returns A one-line description, the lexicon's `'subject.empty'` line when empty
|
|
962
|
+
*
|
|
963
|
+
* @example
|
|
964
|
+
* ```ts
|
|
965
|
+
* import { createNarrator, describeSubject } from '@src/core'
|
|
966
|
+
*
|
|
967
|
+
* describeSubject({ age: 25, income: 50000 }, createNarrator()) // 'with age: 25, income: 50000'
|
|
968
|
+
* ```
|
|
969
|
+
*/
|
|
970
|
+
function describeSubject(subject, narrator) {
|
|
971
|
+
const keys = Object.keys(subject).sort();
|
|
972
|
+
if (keys.length === 0) return narrator.line("subject.empty", {});
|
|
973
|
+
const parts = keys.map((key) => {
|
|
974
|
+
const unit = narrator.phrase("units", key, "plain");
|
|
975
|
+
return `${narrator.label(key)}: ${narrator.value(unit, subject[key])}`;
|
|
976
|
+
});
|
|
977
|
+
return narrator.line("subject.fields", { fields: parts.join(", ") });
|
|
978
|
+
}
|
|
979
|
+
/**
|
|
980
|
+
* Parse a JSON string into a `Template`, or `undefined` on invalid JSON or a
|
|
981
|
+
* shape that fails `isTemplate`.
|
|
982
|
+
*
|
|
983
|
+
* @remarks
|
|
984
|
+
* The module's sole JSON boundary (design §4) — an `Interpretation` and the
|
|
985
|
+
* versioned records are produced internally, never deserialized from
|
|
986
|
+
* untrusted JSON; replay re-runs `interpret`, it does not deserialize a
|
|
987
|
+
* stored result.
|
|
988
|
+
*
|
|
989
|
+
* @param value - The JSON text to parse
|
|
990
|
+
* @returns The parsed template, or `undefined`
|
|
991
|
+
*
|
|
992
|
+
* @example
|
|
993
|
+
* ```ts
|
|
994
|
+
* import { parseTemplate } from '@src/core'
|
|
995
|
+
*
|
|
996
|
+
* parseTemplate('not json') // undefined
|
|
997
|
+
* ```
|
|
998
|
+
*/
|
|
999
|
+
function parseTemplate(value) {
|
|
1000
|
+
return (0, _orkestrel_contract.parseJSONAs)(value, isTemplate);
|
|
1001
|
+
}
|
|
1002
|
+
//#endregion
|
|
1003
|
+
//#region src/core/managers/DefinitionManager.ts
|
|
1004
|
+
/**
|
|
1005
|
+
* The definition registry — a self-owning, versioned and content-hashed
|
|
1006
|
+
* record-holder for the reasons {@link Definition}s an interpretation produces.
|
|
1007
|
+
*
|
|
1008
|
+
* @remarks
|
|
1009
|
+
* Mirrors {@link TemplateManager}: `add` defaults each record id to the
|
|
1010
|
+
* definition's own `id`, derives `hash` from the definition CONTENT
|
|
1011
|
+
* (id-independent), and bumps `version` ONLY when that hash changes at a reused
|
|
1012
|
+
* id — an identical re-add keeps its version. The batch `remove(ids)` form is
|
|
1013
|
+
* all-or-nothing; `destroy()` is idempotent and every method afterwards throws
|
|
1014
|
+
* `InterpretError('DESTROYED', …)`.
|
|
1015
|
+
*
|
|
1016
|
+
* @example
|
|
1017
|
+
* ```ts
|
|
1018
|
+
* import { symbolicDefinition } from '@orkestrel/reason'
|
|
1019
|
+
* import { DefinitionManager } from '@src/core'
|
|
1020
|
+
*
|
|
1021
|
+
* const manager = new DefinitionManager()
|
|
1022
|
+
* const record = manager.add(symbolicDefinition('rate', 'Rate', []))
|
|
1023
|
+
* record.id // 'rate'
|
|
1024
|
+
* manager.add(symbolicDefinition('rate', 'Rate', [])).version // 1 — identical re-add, no bump
|
|
1025
|
+
* ```
|
|
1026
|
+
*/
|
|
1027
|
+
var DefinitionManager = class {
|
|
1028
|
+
#records = /* @__PURE__ */ new Map();
|
|
1029
|
+
#emitter;
|
|
1030
|
+
#destroyed = false;
|
|
1031
|
+
constructor(options) {
|
|
1032
|
+
this.#emitter = new _orkestrel_emitter.Emitter({
|
|
1033
|
+
on: options?.on,
|
|
1034
|
+
error: options?.error
|
|
1035
|
+
});
|
|
1036
|
+
for (const definition of options?.definitions ?? []) this.add(definition);
|
|
1037
|
+
}
|
|
1038
|
+
get emitter() {
|
|
1039
|
+
return this.#emitter;
|
|
1040
|
+
}
|
|
1041
|
+
get size() {
|
|
1042
|
+
this.#ensureAlive();
|
|
1043
|
+
return this.#records.size;
|
|
1044
|
+
}
|
|
1045
|
+
has(id) {
|
|
1046
|
+
this.#ensureAlive();
|
|
1047
|
+
return this.#records.has(id);
|
|
1048
|
+
}
|
|
1049
|
+
definition(id) {
|
|
1050
|
+
this.#ensureAlive();
|
|
1051
|
+
return this.#records.get(id);
|
|
1052
|
+
}
|
|
1053
|
+
definitions() {
|
|
1054
|
+
this.#ensureAlive();
|
|
1055
|
+
return [...this.#records.values()];
|
|
1056
|
+
}
|
|
1057
|
+
add(definition, options) {
|
|
1058
|
+
this.#ensureAlive();
|
|
1059
|
+
const id = options?.id ?? definition.id;
|
|
1060
|
+
const hash = digestValue(definition);
|
|
1061
|
+
const existing = this.#records.get(id);
|
|
1062
|
+
const record = {
|
|
1063
|
+
id,
|
|
1064
|
+
definition,
|
|
1065
|
+
version: existing === void 0 ? 1 : existing.hash === hash ? existing.version : existing.version + 1,
|
|
1066
|
+
hash
|
|
1067
|
+
};
|
|
1068
|
+
this.#records.set(id, record);
|
|
1069
|
+
this.#emitter.emit("add", id);
|
|
1070
|
+
return record;
|
|
1071
|
+
}
|
|
1072
|
+
remove(target) {
|
|
1073
|
+
this.#ensureAlive();
|
|
1074
|
+
if (target === void 0) {
|
|
1075
|
+
for (const id of this.#records.keys()) this.#emitter.emit("remove", id);
|
|
1076
|
+
this.#records.clear();
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
if (typeof target === "string") {
|
|
1080
|
+
const removed = this.#records.delete(target);
|
|
1081
|
+
if (removed) this.#emitter.emit("remove", target);
|
|
1082
|
+
return removed;
|
|
1083
|
+
}
|
|
1084
|
+
for (const id of target) if (!this.#records.has(id)) return false;
|
|
1085
|
+
for (const id of target) {
|
|
1086
|
+
this.#records.delete(id);
|
|
1087
|
+
this.#emitter.emit("remove", id);
|
|
1088
|
+
}
|
|
1089
|
+
return true;
|
|
1090
|
+
}
|
|
1091
|
+
destroy() {
|
|
1092
|
+
if (this.#destroyed) return;
|
|
1093
|
+
this.#records.clear();
|
|
1094
|
+
this.#destroyed = true;
|
|
1095
|
+
this.#emitter.emit("destroy");
|
|
1096
|
+
this.#emitter.destroy();
|
|
1097
|
+
}
|
|
1098
|
+
#ensureAlive() {
|
|
1099
|
+
if (this.#destroyed) throw new InterpretError("DESTROYED", "Definition manager has been destroyed");
|
|
1100
|
+
}
|
|
1101
|
+
};
|
|
1102
|
+
//#endregion
|
|
1103
|
+
//#region src/core/managers/SubjectManager.ts
|
|
1104
|
+
/**
|
|
1105
|
+
* The subject registry — a self-owning, versioned and content-hashed
|
|
1106
|
+
* record-holder that mints its OWN record identity for every {@link Subject}
|
|
1107
|
+
* (a `Subject` carries no `id` field of its own).
|
|
1108
|
+
*
|
|
1109
|
+
* @remarks
|
|
1110
|
+
* The defect-7 fix: scsr keyed stored subjects by their definition's id, so
|
|
1111
|
+
* successive same-domain turns silently overwrote one shared subject. Here each
|
|
1112
|
+
* `add` mints a fresh `subject-{n}` id (deterministic per instance, no host
|
|
1113
|
+
* randomness — AGENTS §17.7) unless the caller overrides it via
|
|
1114
|
+
* `ManagerAddOptions.id`. `hash` is content-derived (id-independent) and
|
|
1115
|
+
* `version` bumps ONLY when the hash changes at a reused id. The batch
|
|
1116
|
+
* `remove(ids)` form is all-or-nothing; `destroy()` is idempotent and every
|
|
1117
|
+
* method afterwards throws `InterpretError('DESTROYED', …)`.
|
|
1118
|
+
*
|
|
1119
|
+
* @example
|
|
1120
|
+
* ```ts
|
|
1121
|
+
* import { SubjectManager } from '@src/core'
|
|
1122
|
+
*
|
|
1123
|
+
* const manager = new SubjectManager()
|
|
1124
|
+
* const first = manager.add({ age: 25 })
|
|
1125
|
+
* const second = manager.add({ age: 30 })
|
|
1126
|
+
* first.id !== second.id // true — each subject gets its own identity
|
|
1127
|
+
* ```
|
|
1128
|
+
*/
|
|
1129
|
+
var SubjectManager = class {
|
|
1130
|
+
#records = /* @__PURE__ */ new Map();
|
|
1131
|
+
#emitter;
|
|
1132
|
+
#counter = 0;
|
|
1133
|
+
#destroyed = false;
|
|
1134
|
+
constructor(options) {
|
|
1135
|
+
this.#emitter = new _orkestrel_emitter.Emitter({
|
|
1136
|
+
on: options?.on,
|
|
1137
|
+
error: options?.error
|
|
1138
|
+
});
|
|
1139
|
+
for (const subject of options?.subjects ?? []) this.add(subject);
|
|
1140
|
+
}
|
|
1141
|
+
get emitter() {
|
|
1142
|
+
return this.#emitter;
|
|
1143
|
+
}
|
|
1144
|
+
get size() {
|
|
1145
|
+
this.#ensureAlive();
|
|
1146
|
+
return this.#records.size;
|
|
1147
|
+
}
|
|
1148
|
+
has(id) {
|
|
1149
|
+
this.#ensureAlive();
|
|
1150
|
+
return this.#records.has(id);
|
|
1151
|
+
}
|
|
1152
|
+
subject(id) {
|
|
1153
|
+
this.#ensureAlive();
|
|
1154
|
+
return this.#records.get(id);
|
|
1155
|
+
}
|
|
1156
|
+
subjects() {
|
|
1157
|
+
this.#ensureAlive();
|
|
1158
|
+
return [...this.#records.values()];
|
|
1159
|
+
}
|
|
1160
|
+
add(subject, options) {
|
|
1161
|
+
this.#ensureAlive();
|
|
1162
|
+
let id = options?.id;
|
|
1163
|
+
if (id === void 0) {
|
|
1164
|
+
id = `subject-${this.#counter}`;
|
|
1165
|
+
this.#counter += 1;
|
|
1166
|
+
}
|
|
1167
|
+
const hash = digestValue(subject);
|
|
1168
|
+
const existing = this.#records.get(id);
|
|
1169
|
+
const version = existing === void 0 ? 1 : existing.hash === hash ? existing.version : existing.version + 1;
|
|
1170
|
+
const record = {
|
|
1171
|
+
id,
|
|
1172
|
+
subject,
|
|
1173
|
+
version,
|
|
1174
|
+
hash
|
|
1175
|
+
};
|
|
1176
|
+
this.#records.set(id, record);
|
|
1177
|
+
this.#emitter.emit("add", id);
|
|
1178
|
+
return record;
|
|
1179
|
+
}
|
|
1180
|
+
remove(target) {
|
|
1181
|
+
this.#ensureAlive();
|
|
1182
|
+
if (target === void 0) {
|
|
1183
|
+
for (const id of this.#records.keys()) this.#emitter.emit("remove", id);
|
|
1184
|
+
this.#records.clear();
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
if (typeof target === "string") {
|
|
1188
|
+
const removed = this.#records.delete(target);
|
|
1189
|
+
if (removed) this.#emitter.emit("remove", target);
|
|
1190
|
+
return removed;
|
|
1191
|
+
}
|
|
1192
|
+
for (const id of target) if (!this.#records.has(id)) return false;
|
|
1193
|
+
for (const id of target) {
|
|
1194
|
+
this.#records.delete(id);
|
|
1195
|
+
this.#emitter.emit("remove", id);
|
|
1196
|
+
}
|
|
1197
|
+
return true;
|
|
1198
|
+
}
|
|
1199
|
+
destroy() {
|
|
1200
|
+
if (this.#destroyed) return;
|
|
1201
|
+
this.#records.clear();
|
|
1202
|
+
this.#destroyed = true;
|
|
1203
|
+
this.#emitter.emit("destroy");
|
|
1204
|
+
this.#emitter.destroy();
|
|
1205
|
+
}
|
|
1206
|
+
#ensureAlive() {
|
|
1207
|
+
if (this.#destroyed) throw new InterpretError("DESTROYED", "Subject manager has been destroyed");
|
|
1208
|
+
}
|
|
1209
|
+
};
|
|
1210
|
+
//#endregion
|
|
1211
|
+
//#region src/core/managers/InterpretContext.ts
|
|
1212
|
+
/**
|
|
1213
|
+
* Cross-turn interpretation context — a capped, replayable history of
|
|
1214
|
+
* completed {@link Interpretation}s plus the subject and definition registries
|
|
1215
|
+
* carry-over reads from.
|
|
1216
|
+
*
|
|
1217
|
+
* @remarks
|
|
1218
|
+
* `previous()` is a capped ring buffer (newest-last, oldest dropped once the
|
|
1219
|
+
* `history` cap is reached — `DEFAULT_INTERPRET_HISTORY` by default, ≥ 3
|
|
1220
|
+
* preserves the carry-over pin) rather than scsr's unbounded `previous` array.
|
|
1221
|
+
* `entities()` flattens every entity across the buffered history, most recent
|
|
1222
|
+
* last — the read a `Clarifier`'s same-domain carry-over consults. `add` pushes
|
|
1223
|
+
* one result and trims to the cap; `clear` resets the history and both
|
|
1224
|
+
* registries WITHOUT tearing the context down; `destroy()` is idempotent and
|
|
1225
|
+
* every method afterwards throws `InterpretError('DESTROYED', …)`.
|
|
1226
|
+
*
|
|
1227
|
+
* @example
|
|
1228
|
+
* ```ts
|
|
1229
|
+
* import { InterpretContext } from '@src/core'
|
|
1230
|
+
*
|
|
1231
|
+
* const context = new InterpretContext({ session: 's1', history: 8 })
|
|
1232
|
+
* context.session // 's1'
|
|
1233
|
+
* context.previous() // []
|
|
1234
|
+
* ```
|
|
1235
|
+
*/
|
|
1236
|
+
var InterpretContext = class {
|
|
1237
|
+
#session;
|
|
1238
|
+
#subjects;
|
|
1239
|
+
#definitions;
|
|
1240
|
+
#history;
|
|
1241
|
+
#previous = [];
|
|
1242
|
+
#emitter;
|
|
1243
|
+
#destroyed = false;
|
|
1244
|
+
constructor(options) {
|
|
1245
|
+
this.#session = options?.session;
|
|
1246
|
+
this.#history = Math.max(0, options?.history ?? 16);
|
|
1247
|
+
this.#subjects = new SubjectManager();
|
|
1248
|
+
this.#definitions = new DefinitionManager();
|
|
1249
|
+
this.#emitter = new _orkestrel_emitter.Emitter({
|
|
1250
|
+
on: options?.on,
|
|
1251
|
+
error: options?.error
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
get emitter() {
|
|
1255
|
+
return this.#emitter;
|
|
1256
|
+
}
|
|
1257
|
+
get session() {
|
|
1258
|
+
this.#ensureAlive();
|
|
1259
|
+
return this.#session;
|
|
1260
|
+
}
|
|
1261
|
+
get subjects() {
|
|
1262
|
+
this.#ensureAlive();
|
|
1263
|
+
return this.#subjects;
|
|
1264
|
+
}
|
|
1265
|
+
get definitions() {
|
|
1266
|
+
this.#ensureAlive();
|
|
1267
|
+
return this.#definitions;
|
|
1268
|
+
}
|
|
1269
|
+
previous() {
|
|
1270
|
+
this.#ensureAlive();
|
|
1271
|
+
return [...this.#previous];
|
|
1272
|
+
}
|
|
1273
|
+
entities() {
|
|
1274
|
+
this.#ensureAlive();
|
|
1275
|
+
return this.#previous.flatMap((result) => [...result.entities]);
|
|
1276
|
+
}
|
|
1277
|
+
add(result) {
|
|
1278
|
+
this.#ensureAlive();
|
|
1279
|
+
this.#previous.push(result);
|
|
1280
|
+
while (this.#previous.length > this.#history) this.#previous.shift();
|
|
1281
|
+
this.#emitter.emit("add", result.digest);
|
|
1282
|
+
}
|
|
1283
|
+
clear() {
|
|
1284
|
+
this.#ensureAlive();
|
|
1285
|
+
this.#previous.length = 0;
|
|
1286
|
+
this.#subjects.remove();
|
|
1287
|
+
this.#definitions.remove();
|
|
1288
|
+
this.#emitter.emit("clear");
|
|
1289
|
+
}
|
|
1290
|
+
destroy() {
|
|
1291
|
+
if (this.#destroyed) return;
|
|
1292
|
+
this.#previous.length = 0;
|
|
1293
|
+
this.#subjects.destroy();
|
|
1294
|
+
this.#definitions.destroy();
|
|
1295
|
+
this.#destroyed = true;
|
|
1296
|
+
this.#emitter.emit("destroy");
|
|
1297
|
+
this.#emitter.destroy();
|
|
1298
|
+
}
|
|
1299
|
+
#ensureAlive() {
|
|
1300
|
+
if (this.#destroyed) throw new InterpretError("DESTROYED", "Interpret context has been destroyed");
|
|
1301
|
+
}
|
|
1302
|
+
};
|
|
1303
|
+
//#endregion
|
|
1304
|
+
//#region src/core/managers/TemplateManager.ts
|
|
1305
|
+
/**
|
|
1306
|
+
* The template registry — a self-owning, versioned and content-hashed
|
|
1307
|
+
* record-holder for the {@link Template}s an `Interpret` orchestrator matches
|
|
1308
|
+
* against.
|
|
1309
|
+
*
|
|
1310
|
+
* @remarks
|
|
1311
|
+
* `size` (never `count` — the sole tally in scope) plus the AGENTS §9.1
|
|
1312
|
+
* singular/plural accessors (`template` / `templates`) and the §9.2 batch
|
|
1313
|
+
* `remove` overloads. `add` derives each record's `hash` from the template's
|
|
1314
|
+
* CONTENT (id-independent — the same template data hashes identically under
|
|
1315
|
+
* any record id) and bumps `version` ONLY when that hash changes: an identical
|
|
1316
|
+
* re-add keeps its version (unlike scsr, which bumped on every add). The
|
|
1317
|
+
* batch `remove(ids)` form is ALL-OR-NOTHING — any id absent from the registry
|
|
1318
|
+
* leaves the collection untouched and returns `false`. `destroy()` is
|
|
1319
|
+
* idempotent; every method afterwards throws `InterpretError('DESTROYED', …)`.
|
|
1320
|
+
*
|
|
1321
|
+
* @example
|
|
1322
|
+
* ```ts
|
|
1323
|
+
* import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
|
|
1324
|
+
* import { TemplateManager } from '@src/core'
|
|
1325
|
+
*
|
|
1326
|
+
* const manager = new TemplateManager()
|
|
1327
|
+
* const record = manager.add({
|
|
1328
|
+
* id: 't1',
|
|
1329
|
+
* name: 'Arithmetic',
|
|
1330
|
+
* domain: 'arithmetic',
|
|
1331
|
+
* intents: ['calculate'],
|
|
1332
|
+
* mappings: [],
|
|
1333
|
+
* defaults: [],
|
|
1334
|
+
* computations: [],
|
|
1335
|
+
* definition: quantitativeDefinition('t1', 'Arithmetic', [
|
|
1336
|
+
* factorGroup('total', 'sum', [fieldFactor('value', 'value')]),
|
|
1337
|
+
* ]),
|
|
1338
|
+
* })
|
|
1339
|
+
* record.version // 1
|
|
1340
|
+
* manager.size // 1
|
|
1341
|
+
* ```
|
|
1342
|
+
*/
|
|
1343
|
+
var TemplateManager = class {
|
|
1344
|
+
#records = /* @__PURE__ */ new Map();
|
|
1345
|
+
#emitter;
|
|
1346
|
+
#destroyed = false;
|
|
1347
|
+
constructor(options) {
|
|
1348
|
+
this.#emitter = new _orkestrel_emitter.Emitter({
|
|
1349
|
+
on: options?.on,
|
|
1350
|
+
error: options?.error
|
|
1351
|
+
});
|
|
1352
|
+
for (const template of options?.templates ?? []) this.add(template);
|
|
1353
|
+
}
|
|
1354
|
+
get emitter() {
|
|
1355
|
+
return this.#emitter;
|
|
1356
|
+
}
|
|
1357
|
+
get size() {
|
|
1358
|
+
this.#ensureAlive();
|
|
1359
|
+
return this.#records.size;
|
|
1360
|
+
}
|
|
1361
|
+
has(id) {
|
|
1362
|
+
this.#ensureAlive();
|
|
1363
|
+
return this.#records.has(id);
|
|
1364
|
+
}
|
|
1365
|
+
template(id) {
|
|
1366
|
+
this.#ensureAlive();
|
|
1367
|
+
return this.#records.get(id);
|
|
1368
|
+
}
|
|
1369
|
+
templates() {
|
|
1370
|
+
this.#ensureAlive();
|
|
1371
|
+
return [...this.#records.values()];
|
|
1372
|
+
}
|
|
1373
|
+
add(template, options) {
|
|
1374
|
+
this.#ensureAlive();
|
|
1375
|
+
const id = options?.id ?? template.id;
|
|
1376
|
+
const hash = digestValue(template);
|
|
1377
|
+
const existing = this.#records.get(id);
|
|
1378
|
+
const record = {
|
|
1379
|
+
id,
|
|
1380
|
+
template,
|
|
1381
|
+
version: existing === void 0 ? 1 : existing.hash === hash ? existing.version : existing.version + 1,
|
|
1382
|
+
hash
|
|
1383
|
+
};
|
|
1384
|
+
this.#records.set(id, record);
|
|
1385
|
+
this.#emitter.emit("add", id);
|
|
1386
|
+
return record;
|
|
1387
|
+
}
|
|
1388
|
+
remove(target) {
|
|
1389
|
+
this.#ensureAlive();
|
|
1390
|
+
if (target === void 0) {
|
|
1391
|
+
for (const id of this.#records.keys()) this.#emitter.emit("remove", id);
|
|
1392
|
+
this.#records.clear();
|
|
1393
|
+
return;
|
|
1394
|
+
}
|
|
1395
|
+
if (typeof target === "string") {
|
|
1396
|
+
const removed = this.#records.delete(target);
|
|
1397
|
+
if (removed) this.#emitter.emit("remove", target);
|
|
1398
|
+
return removed;
|
|
1399
|
+
}
|
|
1400
|
+
for (const id of target) if (!this.#records.has(id)) return false;
|
|
1401
|
+
for (const id of target) {
|
|
1402
|
+
this.#records.delete(id);
|
|
1403
|
+
this.#emitter.emit("remove", id);
|
|
1404
|
+
}
|
|
1405
|
+
return true;
|
|
1406
|
+
}
|
|
1407
|
+
destroy() {
|
|
1408
|
+
if (this.#destroyed) return;
|
|
1409
|
+
this.#records.clear();
|
|
1410
|
+
this.#destroyed = true;
|
|
1411
|
+
this.#emitter.emit("destroy");
|
|
1412
|
+
this.#emitter.destroy();
|
|
1413
|
+
}
|
|
1414
|
+
#ensureAlive() {
|
|
1415
|
+
if (this.#destroyed) throw new InterpretError("DESTROYED", "Template manager has been destroyed");
|
|
1416
|
+
}
|
|
1417
|
+
};
|
|
1418
|
+
//#endregion
|
|
1419
|
+
//#region src/core/Narrator.ts
|
|
1420
|
+
/**
|
|
1421
|
+
* A stateless, TOTAL, lexicon-driven rendering engine for the reverse
|
|
1422
|
+
* direction — the reverse-direction mirror of the forward `Formatter`'s
|
|
1423
|
+
* `verbs` seam (AGENTS §21 mechanism-never-policy).
|
|
1424
|
+
*
|
|
1425
|
+
* @remarks
|
|
1426
|
+
* Every wording decision is DATA — a caller-supplied `Lexicon` merged, per
|
|
1427
|
+
* sub-record (`phrases` / `labels` / `templates`), OVER `DEFAULT_LEXICON`.
|
|
1428
|
+
* Stateless and holds no resources: no emitter, no `destroy()` (deliberate —
|
|
1429
|
+
* there is nothing to release). Every method is total (never throws); a
|
|
1430
|
+
* lexicon or formatter miss degrades to its documented fallback rather than
|
|
1431
|
+
* a thrown error, and every lookup guards with `Object.hasOwn` so an
|
|
1432
|
+
* adversarial key (`toString`, `constructor`, `__proto__`) misses cleanly
|
|
1433
|
+
* instead of reading an inherited prototype member.
|
|
1434
|
+
*
|
|
1435
|
+
* @example
|
|
1436
|
+
* ```ts
|
|
1437
|
+
* import { Narrator } from '@src/core'
|
|
1438
|
+
*
|
|
1439
|
+
* const narrator = new Narrator({
|
|
1440
|
+
* lexicon: { phrases: { comparison: { equals: 'is' } } },
|
|
1441
|
+
* formatters: { money: (value) => `$${String(value)}` },
|
|
1442
|
+
* })
|
|
1443
|
+
* narrator.phrase('comparison', 'equals', 'equals') // 'is'
|
|
1444
|
+
* narrator.phrase('comparison', 'missing', 'equals') // 'equals' — fallback
|
|
1445
|
+
* narrator.value('money', 5) // '$5'
|
|
1446
|
+
* ```
|
|
1447
|
+
*/
|
|
1448
|
+
var Narrator = class {
|
|
1449
|
+
#lexicon;
|
|
1450
|
+
#formatters;
|
|
1451
|
+
constructor(options) {
|
|
1452
|
+
this.#lexicon = {
|
|
1453
|
+
phrases: {
|
|
1454
|
+
...DEFAULT_LEXICON.phrases,
|
|
1455
|
+
...options?.lexicon?.phrases
|
|
1456
|
+
},
|
|
1457
|
+
labels: {
|
|
1458
|
+
...DEFAULT_LEXICON.labels,
|
|
1459
|
+
...options?.lexicon?.labels
|
|
1460
|
+
},
|
|
1461
|
+
templates: {
|
|
1462
|
+
...DEFAULT_LEXICON.templates,
|
|
1463
|
+
...options?.lexicon?.templates
|
|
1464
|
+
}
|
|
1465
|
+
};
|
|
1466
|
+
this.#formatters = { ...options?.formatters };
|
|
1467
|
+
}
|
|
1468
|
+
phrase(table, key, fallback) {
|
|
1469
|
+
if (Object.hasOwn(this.#lexicon.phrases, table)) {
|
|
1470
|
+
const row = this.#lexicon.phrases[table];
|
|
1471
|
+
if (row !== null && row !== void 0 && Object.hasOwn(row, key)) {
|
|
1472
|
+
const value = row[key];
|
|
1473
|
+
if (typeof value === "string") return value;
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
return fallback ?? key;
|
|
1477
|
+
}
|
|
1478
|
+
label(field) {
|
|
1479
|
+
const key = (0, _orkestrel_reason.formatField)(field);
|
|
1480
|
+
if (Object.hasOwn(this.#lexicon.labels, key)) {
|
|
1481
|
+
const value = this.#lexicon.labels[key];
|
|
1482
|
+
if (typeof value === "string") return value;
|
|
1483
|
+
}
|
|
1484
|
+
return key;
|
|
1485
|
+
}
|
|
1486
|
+
line(id, values) {
|
|
1487
|
+
if (!Object.hasOwn(this.#lexicon.templates, id)) return "";
|
|
1488
|
+
const template = this.#lexicon.templates[id];
|
|
1489
|
+
return typeof template === "string" ? (0, _orkestrel_template.fillTemplate)(template, values, { missing: "empty" }) : "";
|
|
1490
|
+
}
|
|
1491
|
+
value(unit, raw) {
|
|
1492
|
+
if (Object.hasOwn(this.#formatters, unit)) {
|
|
1493
|
+
const formatter = this.#formatters[unit];
|
|
1494
|
+
if (typeof formatter === "function") try {
|
|
1495
|
+
return formatter(raw);
|
|
1496
|
+
} catch {
|
|
1497
|
+
return String(raw);
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
return String(raw);
|
|
1501
|
+
}
|
|
1502
|
+
describe(definition) {
|
|
1503
|
+
switch (definition.reasoning) {
|
|
1504
|
+
case "quantitative": return this.line("definition.quantitative", {
|
|
1505
|
+
name: definition.name,
|
|
1506
|
+
count: definition.groups.length
|
|
1507
|
+
});
|
|
1508
|
+
case "logical": return this.line("definition.logical", {
|
|
1509
|
+
name: definition.name,
|
|
1510
|
+
count: definition.rules.length,
|
|
1511
|
+
strategy: definition.strategy
|
|
1512
|
+
});
|
|
1513
|
+
case "symbolic": return this.line("definition.symbolic", {
|
|
1514
|
+
name: definition.name,
|
|
1515
|
+
count: definition.equations.length
|
|
1516
|
+
});
|
|
1517
|
+
case "inferential": return this.line("definition.inferential", {
|
|
1518
|
+
name: definition.name,
|
|
1519
|
+
facts: definition.facts.length,
|
|
1520
|
+
inferences: definition.inferences.length,
|
|
1521
|
+
strategy: definition.strategy
|
|
1522
|
+
});
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
narrate(result) {
|
|
1526
|
+
switch (result.reasoning) {
|
|
1527
|
+
case "quantitative": {
|
|
1528
|
+
const base = this.line("result.quantitative", {
|
|
1529
|
+
value: result.value,
|
|
1530
|
+
count: result.count
|
|
1531
|
+
});
|
|
1532
|
+
if (result.errors.length === 0) return base;
|
|
1533
|
+
return `${base}${this.line("result.quantitative.failed", { errors: result.errors.join(", ") })}`;
|
|
1534
|
+
}
|
|
1535
|
+
case "logical": return this.line("result.logical", {
|
|
1536
|
+
status: result.conclusion ? "met" : "unmet",
|
|
1537
|
+
count: result.count
|
|
1538
|
+
});
|
|
1539
|
+
case "symbolic": {
|
|
1540
|
+
const solved = Object.entries(result.solutions).map(([key, value]) => `${key}=${value}`).join(", ");
|
|
1541
|
+
return this.line("result.symbolic", { solved });
|
|
1542
|
+
}
|
|
1543
|
+
case "inferential": return this.line("result.inferential", { count: result.derived.length });
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
};
|
|
1547
|
+
//#endregion
|
|
1548
|
+
//#region src/core/stages/Clarifier.ts
|
|
1549
|
+
/**
|
|
1550
|
+
* The `Clarifier` stage: resolves same-domain carry-over, template defaults,
|
|
1551
|
+
* and declaratively computed fields against an already-assigned entity set,
|
|
1552
|
+
* surfacing an {@link Ambiguity} for every required mapping that stays
|
|
1553
|
+
* unresolved.
|
|
1554
|
+
*
|
|
1555
|
+
* @remarks
|
|
1556
|
+
* Resolution order: fresh (already-assigned) entities always win; carry-over
|
|
1557
|
+
* fills a mapping only from the SAME domain's most recent prior turn (a
|
|
1558
|
+
* domain change drops carry-over entirely) and never overwrites a fresh
|
|
1559
|
+
* value; template defaults fill any field still unresolved after carry-over;
|
|
1560
|
+
* computed fields resolve in dependency (topological) order via
|
|
1561
|
+
* `resolveExpression` — an unresolved input, a non-finite result, or a
|
|
1562
|
+
* dependency cycle leaves the field a gap, never landing an entity. `floor`
|
|
1563
|
+
* (from {@link ClarifierOptions}, never hardcoded — AGENTS-flagged scsr
|
|
1564
|
+
* defect 4) gates whether a resolved entity's confidence counts as
|
|
1565
|
+
* "resolved enough" when raising ambiguities — a field with a value below
|
|
1566
|
+
* `floor` still raises its ambiguity.
|
|
1567
|
+
*
|
|
1568
|
+
* @example
|
|
1569
|
+
* ```ts
|
|
1570
|
+
* import { Clarifier } from '@src/core'
|
|
1571
|
+
*
|
|
1572
|
+
* const clarifier = new Clarifier({ floor: 0.3 })
|
|
1573
|
+
* clarifier.clarify(
|
|
1574
|
+
* [],
|
|
1575
|
+
* {
|
|
1576
|
+
* id: 't1',
|
|
1577
|
+
* name: 'Arithmetic',
|
|
1578
|
+
* domain: 'arithmetic',
|
|
1579
|
+
* intents: ['calculate'],
|
|
1580
|
+
* mappings: [{ entity: 'value', aliases: [], field: 'value', required: true }],
|
|
1581
|
+
* defaults: [],
|
|
1582
|
+
* computations: [],
|
|
1583
|
+
* definition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },
|
|
1584
|
+
* },
|
|
1585
|
+
* undefined,
|
|
1586
|
+
* { action: 'calculate', domain: 'arithmetic', confidence: 1 },
|
|
1587
|
+
* ) // { entities: [], ambiguities: [{ field: 'value', ... }], complete: false }
|
|
1588
|
+
* ```
|
|
1589
|
+
*/
|
|
1590
|
+
var Clarifier = class {
|
|
1591
|
+
#floor;
|
|
1592
|
+
constructor(options) {
|
|
1593
|
+
this.#floor = options?.floor ?? .3;
|
|
1594
|
+
}
|
|
1595
|
+
clarify(entities, template, context, intent) {
|
|
1596
|
+
const resolved = [...entities];
|
|
1597
|
+
const filledEntityNames = new Set(resolved.map((entity) => entity.name));
|
|
1598
|
+
const filledFields = new Set(resolved.map((entity) => {
|
|
1599
|
+
const mapping = template.mappings.find((candidate) => candidate.entity === entity.name);
|
|
1600
|
+
return mapping === void 0 ? entity.name : (0, _orkestrel_reason.formatField)(mapping.field);
|
|
1601
|
+
}));
|
|
1602
|
+
this.#carryOver(template, context, intent, filledEntityNames, filledFields, resolved);
|
|
1603
|
+
this.#fillDefaults(template, filledFields, resolved);
|
|
1604
|
+
this.#resolveComputations(template, filledFields, resolved);
|
|
1605
|
+
const ambiguities = this.#collectAmbiguities(template, resolved);
|
|
1606
|
+
return {
|
|
1607
|
+
entities: resolved,
|
|
1608
|
+
ambiguities,
|
|
1609
|
+
complete: ambiguities.length === 0
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
#carryOver(template, context, intent, filledEntityNames, filledFields, resolved) {
|
|
1613
|
+
if (context === void 0) return;
|
|
1614
|
+
const sameDomain = context.previous().filter((prior) => prior.intent.domain === intent.domain);
|
|
1615
|
+
for (const mapping of template.mappings) {
|
|
1616
|
+
if (filledEntityNames.has(mapping.entity)) continue;
|
|
1617
|
+
for (let index = sameDomain.length - 1; index >= 0; index -= 1) {
|
|
1618
|
+
const found = sameDomain[index]?.entities.find((entity) => entity.name === mapping.entity);
|
|
1619
|
+
if (found === void 0) continue;
|
|
1620
|
+
resolved.push({
|
|
1621
|
+
name: mapping.entity,
|
|
1622
|
+
value: found.value,
|
|
1623
|
+
provenance: { category: "carried" },
|
|
1624
|
+
confidence: CONFIDENCE_CARRIED
|
|
1625
|
+
});
|
|
1626
|
+
filledEntityNames.add(mapping.entity);
|
|
1627
|
+
filledFields.add((0, _orkestrel_reason.formatField)(mapping.field));
|
|
1628
|
+
break;
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
#fillDefaults(template, filledFields, resolved) {
|
|
1633
|
+
for (const fieldDefault of template.defaults) {
|
|
1634
|
+
const key = (0, _orkestrel_reason.formatField)(fieldDefault.field);
|
|
1635
|
+
if (filledFields.has(key)) continue;
|
|
1636
|
+
const mapping = template.mappings.find((candidate) => (0, _orkestrel_reason.formatField)(candidate.field) === key);
|
|
1637
|
+
resolved.push({
|
|
1638
|
+
name: mapping?.entity ?? key,
|
|
1639
|
+
value: fieldDefault.value,
|
|
1640
|
+
provenance: { category: "default" },
|
|
1641
|
+
confidence: 1
|
|
1642
|
+
});
|
|
1643
|
+
filledFields.add(key);
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
#resolveComputations(template, filledFields, resolved) {
|
|
1647
|
+
const bindings = {};
|
|
1648
|
+
for (const entity of resolved) {
|
|
1649
|
+
const mapping = template.mappings.find((candidate) => candidate.entity === entity.name);
|
|
1650
|
+
const field = mapping === void 0 ? entity.name : (0, _orkestrel_reason.formatField)(mapping.field);
|
|
1651
|
+
if ((0, _orkestrel_contract.isFiniteNumber)(entity.value)) bindings[field] = entity.value;
|
|
1652
|
+
}
|
|
1653
|
+
for (const computation of this.#orderComputations(template.computations)) {
|
|
1654
|
+
const key = (0, _orkestrel_reason.formatField)(computation.field);
|
|
1655
|
+
if (filledFields.has(key)) continue;
|
|
1656
|
+
const value = resolveExpression(computation.expression, bindings);
|
|
1657
|
+
if (value === void 0) continue;
|
|
1658
|
+
const mapping = template.mappings.find((candidate) => (0, _orkestrel_reason.formatField)(candidate.field) === key);
|
|
1659
|
+
resolved.push({
|
|
1660
|
+
name: mapping?.entity ?? key,
|
|
1661
|
+
value,
|
|
1662
|
+
provenance: { category: "computed" },
|
|
1663
|
+
confidence: CONFIDENCE_COMPUTED
|
|
1664
|
+
});
|
|
1665
|
+
filledFields.add(key);
|
|
1666
|
+
bindings[key] = value;
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
#orderComputations(computations) {
|
|
1670
|
+
const byField = /* @__PURE__ */ new Map();
|
|
1671
|
+
for (const computation of computations) byField.set((0, _orkestrel_reason.formatField)(computation.field), computation);
|
|
1672
|
+
const dependents = /* @__PURE__ */ new Map();
|
|
1673
|
+
const inDegree = /* @__PURE__ */ new Map();
|
|
1674
|
+
for (const key of byField.keys()) inDegree.set(key, 0);
|
|
1675
|
+
for (const [key, computation] of byField) {
|
|
1676
|
+
const dependencies = variablesOf(computation.expression).filter((name) => byField.has(name));
|
|
1677
|
+
inDegree.set(key, dependencies.length);
|
|
1678
|
+
for (const dependency of dependencies) {
|
|
1679
|
+
const list = dependents.get(dependency) ?? [];
|
|
1680
|
+
list.push(key);
|
|
1681
|
+
dependents.set(dependency, list);
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
const queue = [];
|
|
1685
|
+
for (const [key, degree] of inDegree) if (degree === 0) queue.push(key);
|
|
1686
|
+
const ordered = [];
|
|
1687
|
+
let cursor = 0;
|
|
1688
|
+
while (cursor < queue.length) {
|
|
1689
|
+
const key = queue[cursor];
|
|
1690
|
+
cursor += 1;
|
|
1691
|
+
if (key === void 0) continue;
|
|
1692
|
+
const computation = byField.get(key);
|
|
1693
|
+
if (computation !== void 0) ordered.push(computation);
|
|
1694
|
+
for (const dependent of dependents.get(key) ?? []) {
|
|
1695
|
+
const next = (inDegree.get(dependent) ?? 0) - 1;
|
|
1696
|
+
inDegree.set(dependent, next);
|
|
1697
|
+
if (next === 0) queue.push(dependent);
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
return ordered;
|
|
1701
|
+
}
|
|
1702
|
+
#collectAmbiguities(template, resolved) {
|
|
1703
|
+
const ambiguities = [];
|
|
1704
|
+
for (const mapping of template.mappings) {
|
|
1705
|
+
if (mapping.required !== true) continue;
|
|
1706
|
+
const entity = resolved.find((candidate) => candidate.name === mapping.entity);
|
|
1707
|
+
if (entity !== void 0 && entity.confidence >= this.#floor) continue;
|
|
1708
|
+
ambiguities.push({
|
|
1709
|
+
field: mapping.field,
|
|
1710
|
+
question: `What is your ${mapping.entity}?`,
|
|
1711
|
+
candidates: [],
|
|
1712
|
+
required: true
|
|
1713
|
+
});
|
|
1714
|
+
}
|
|
1715
|
+
return ambiguities;
|
|
1716
|
+
}
|
|
1717
|
+
};
|
|
1718
|
+
//#endregion
|
|
1719
|
+
//#region src/core/stages/Extractor.ts
|
|
1720
|
+
/**
|
|
1721
|
+
* The `Extractor` stage: template-agnostic intent classification plus raw
|
|
1722
|
+
* numeric-entity mining.
|
|
1723
|
+
*
|
|
1724
|
+
* @remarks
|
|
1725
|
+
* Deliberately never named `Parser` — the `contracts` module already owns
|
|
1726
|
+
* `Parser<T>`, so a class of that name would collide in type space (AGENTS
|
|
1727
|
+
* §21, design ledger 3). `extract` never sees a `Template`: numbers →
|
|
1728
|
+
* entity ASSIGNMENT is a separate orchestrator-owned step that runs only
|
|
1729
|
+
* after a template has matched (`assignEntities` in `helpers.ts`), not
|
|
1730
|
+
* inside this stage (the defect-3 fix — scsr's parser mined template-shaped
|
|
1731
|
+
* entities directly and only worked via an `instanceof` hack).
|
|
1732
|
+
*
|
|
1733
|
+
* @example
|
|
1734
|
+
* ```ts
|
|
1735
|
+
* import { Extractor } from '@src/core'
|
|
1736
|
+
*
|
|
1737
|
+
* const extractor = new Extractor({
|
|
1738
|
+
* actions: { calculate: 'compute' },
|
|
1739
|
+
* domains: { rating: ['rate'] },
|
|
1740
|
+
* })
|
|
1741
|
+
* extractor.extract('calculate my rate at 85')
|
|
1742
|
+
* // { intent: { action: 'compute', domain: 'rating', confidence: 1 }, numbers: [85], complete: true }
|
|
1743
|
+
* ```
|
|
1744
|
+
*/
|
|
1745
|
+
var Extractor = class {
|
|
1746
|
+
#actions;
|
|
1747
|
+
#domains;
|
|
1748
|
+
constructor(options) {
|
|
1749
|
+
this.#actions = {
|
|
1750
|
+
...DEFAULT_ACTIONS,
|
|
1751
|
+
...options?.actions
|
|
1752
|
+
};
|
|
1753
|
+
this.#domains = {
|
|
1754
|
+
...DEFAULT_DOMAINS,
|
|
1755
|
+
...options?.domains
|
|
1756
|
+
};
|
|
1757
|
+
}
|
|
1758
|
+
extract(text) {
|
|
1759
|
+
const numbers = extractNumbers(text);
|
|
1760
|
+
const intent = classifyIntent(text, this.#actions, this.#domains);
|
|
1761
|
+
return {
|
|
1762
|
+
intent,
|
|
1763
|
+
numbers,
|
|
1764
|
+
complete: numbers.length > 0 && intent.confidence > 0
|
|
1765
|
+
};
|
|
1766
|
+
}
|
|
1767
|
+
};
|
|
1768
|
+
//#endregion
|
|
1769
|
+
//#region src/core/stages/Formatter.ts
|
|
1770
|
+
/**
|
|
1771
|
+
* The `Formatter` stage: renders the refined natural-language prompt for a
|
|
1772
|
+
* matched template.
|
|
1773
|
+
*
|
|
1774
|
+
* @remarks
|
|
1775
|
+
* Shape: `{verb} {template.name}` + ` with {label}: {value}, …` for every
|
|
1776
|
+
* non-default entity (via the core-root `formatField`) + `
|
|
1777
|
+
* (defaults: {label}: {value}, …)` for default-provenance entities + `
|
|
1778
|
+
* needed: {question} …` for every ambiguity. `verbs` maps `intent.action` to
|
|
1779
|
+
* its display verb; an action absent from the map falls back to the action
|
|
1780
|
+
* string itself. Every parameter is read — no ignored `context` argument
|
|
1781
|
+
* (AGENTS-flagged scsr defect 5).
|
|
1782
|
+
*
|
|
1783
|
+
* @example
|
|
1784
|
+
* ```ts
|
|
1785
|
+
* import { Formatter } from '@src/core'
|
|
1786
|
+
*
|
|
1787
|
+
* const formatter = new Formatter({ verbs: { calculate: 'Calculate' } })
|
|
1788
|
+
* formatter.format(
|
|
1789
|
+
* { action: 'calculate', domain: 'arithmetic', confidence: 1 },
|
|
1790
|
+
* {
|
|
1791
|
+
* id: 't1',
|
|
1792
|
+
* name: 'Arithmetic',
|
|
1793
|
+
* domain: 'arithmetic',
|
|
1794
|
+
* intents: ['calculate'],
|
|
1795
|
+
* mappings: [],
|
|
1796
|
+
* defaults: [],
|
|
1797
|
+
* computations: [],
|
|
1798
|
+
* definition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },
|
|
1799
|
+
* },
|
|
1800
|
+
* [],
|
|
1801
|
+
* [],
|
|
1802
|
+
* ) // { prompt: 'Calculate Arithmetic' }
|
|
1803
|
+
* ```
|
|
1804
|
+
*/
|
|
1805
|
+
var Formatter = class {
|
|
1806
|
+
#verbs;
|
|
1807
|
+
constructor(options) {
|
|
1808
|
+
this.#verbs = {
|
|
1809
|
+
...DEFAULT_VERBS,
|
|
1810
|
+
...options?.verbs
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1813
|
+
format(intent, template, entities, ambiguities) {
|
|
1814
|
+
const verb = this.#verbs[intent.action] ?? intent.action;
|
|
1815
|
+
const render = (list) => list.map((entity) => `${(0, _orkestrel_reason.formatField)(entity.name)}: ${String(entity.value)}`).join(", ");
|
|
1816
|
+
let prompt = `${verb} ${template.name}`;
|
|
1817
|
+
const resolved = entities.filter((entity) => entity.provenance.category !== "default");
|
|
1818
|
+
if (resolved.length > 0) prompt += ` with ${render(resolved)}`;
|
|
1819
|
+
const defaults = entities.filter((entity) => entity.provenance.category === "default");
|
|
1820
|
+
if (defaults.length > 0) prompt += ` (defaults: ${render(defaults)})`;
|
|
1821
|
+
if (ambiguities.length > 0) prompt += ` needed: ${ambiguities.map((ambiguity) => ambiguity.question).join(" ")}`;
|
|
1822
|
+
return { prompt };
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
//#endregion
|
|
1826
|
+
//#region src/core/stages/Generator.ts
|
|
1827
|
+
/**
|
|
1828
|
+
* The `Generator` stage: builds the final `Subject` from a fully resolved
|
|
1829
|
+
* entity set, plus its complete field audit.
|
|
1830
|
+
*
|
|
1831
|
+
* @remarks
|
|
1832
|
+
* `entity → field` via `template.mappings` (an `EntityMapping.entity` name
|
|
1833
|
+
* lookup); an entity whose name matches no mapping lands on the field named
|
|
1834
|
+
* by its OWN `name` — the shape `Clarifier` uses for its synthesized
|
|
1835
|
+
* default/computed entities, so one lookup rule serves both extraction-
|
|
1836
|
+
* mapped and template-data-derived fields. A single-element array value
|
|
1837
|
+
* unwraps to its scalar; a multi-element, ALL-numeric array value stays an
|
|
1838
|
+
* array AND additionally emits five aggregate fields (`Sum` / `Count` /
|
|
1839
|
+
* `Average` / `Minimum` / `Maximum`, provenance `computed`), each derived as
|
|
1840
|
+
* a SIBLING path beside the source field via `deriveAggregateField` — for an
|
|
1841
|
+
* array `FieldPath` (e.g. `['address', 'amounts']`) the aggregates nest
|
|
1842
|
+
* (`['address', 'amountsSum']`, ...); for a plain string field they stay
|
|
1843
|
+
* flat (`'amountsSum'`), matching the source field's own shape.
|
|
1844
|
+
* `confidence` is the mean of the input entities' own confidences (`0` for
|
|
1845
|
+
* an empty entity set). A `FieldMapping` is emitted for EVERY field that
|
|
1846
|
+
* lands on the subject, including defaults, computed fields, and aggregates
|
|
1847
|
+
* — scsr silently omitted defaults/computed from its audit trail; this
|
|
1848
|
+
* closes that gap. `GeneratorOptions` is a reserved extension seam — the
|
|
1849
|
+
* stage has no knobs yet, so construction takes no arguments until one
|
|
1850
|
+
* exists.
|
|
1851
|
+
*
|
|
1852
|
+
* @example
|
|
1853
|
+
* ```ts
|
|
1854
|
+
* import { Generator } from '@src/core'
|
|
1855
|
+
*
|
|
1856
|
+
* const generator = new Generator()
|
|
1857
|
+
* generator.generate(
|
|
1858
|
+
* [
|
|
1859
|
+
* {
|
|
1860
|
+
* name: 'value',
|
|
1861
|
+
* value: 42,
|
|
1862
|
+
* provenance: { category: 'extracted', detail: 'collect' },
|
|
1863
|
+
* confidence: 0.9,
|
|
1864
|
+
* },
|
|
1865
|
+
* ],
|
|
1866
|
+
* {
|
|
1867
|
+
* id: 't1',
|
|
1868
|
+
* name: 'Arithmetic',
|
|
1869
|
+
* domain: 'arithmetic',
|
|
1870
|
+
* intents: ['calculate'],
|
|
1871
|
+
* mappings: [{ entity: 'value', aliases: [], field: 'value' }],
|
|
1872
|
+
* defaults: [],
|
|
1873
|
+
* computations: [],
|
|
1874
|
+
* definition: { reasoning: 'symbolic', id: 't1', name: 'Arithmetic', equations: [], variables: {} },
|
|
1875
|
+
* },
|
|
1876
|
+
* ) // { subject: { value: 42 }, mappings: [...], confidence: 0.9, ... }
|
|
1877
|
+
* ```
|
|
1878
|
+
*/
|
|
1879
|
+
var Generator = class {
|
|
1880
|
+
generate(entities, template) {
|
|
1881
|
+
let subject = {};
|
|
1882
|
+
const mappings = [];
|
|
1883
|
+
for (const entity of entities) {
|
|
1884
|
+
const mapping = template.mappings.find((candidate) => candidate.entity === entity.name);
|
|
1885
|
+
const field = mapping === void 0 ? entity.name : mapping.field;
|
|
1886
|
+
const value = entity.value;
|
|
1887
|
+
if (Array.isArray(value) && value.length === 1) {
|
|
1888
|
+
const scalar = value[0];
|
|
1889
|
+
subject = setField(subject, field, scalar);
|
|
1890
|
+
mappings.push({
|
|
1891
|
+
field,
|
|
1892
|
+
entity: entity.name,
|
|
1893
|
+
value: scalar,
|
|
1894
|
+
provenance: entity.provenance,
|
|
1895
|
+
confidence: entity.confidence
|
|
1896
|
+
});
|
|
1897
|
+
continue;
|
|
1898
|
+
}
|
|
1899
|
+
if (Array.isArray(value) && value.length > 1) {
|
|
1900
|
+
const numeric = [];
|
|
1901
|
+
for (const item of value) {
|
|
1902
|
+
if (!(0, _orkestrel_contract.isFiniteNumber)(item)) break;
|
|
1903
|
+
numeric.push(item);
|
|
1904
|
+
}
|
|
1905
|
+
if (numeric.length === value.length) {
|
|
1906
|
+
subject = setField(subject, field, value);
|
|
1907
|
+
mappings.push({
|
|
1908
|
+
field,
|
|
1909
|
+
entity: entity.name,
|
|
1910
|
+
value,
|
|
1911
|
+
provenance: entity.provenance,
|
|
1912
|
+
confidence: entity.confidence
|
|
1913
|
+
});
|
|
1914
|
+
const sum = numeric.reduce((total, item) => total + item, 0);
|
|
1915
|
+
const minimum = numeric.reduce((min, item) => item < min ? item : min, numeric[0]);
|
|
1916
|
+
const maximum = numeric.reduce((max, item) => item > max ? item : max, numeric[0]);
|
|
1917
|
+
const aggregates = [
|
|
1918
|
+
[deriveAggregateField(field, "Sum"), sum],
|
|
1919
|
+
[deriveAggregateField(field, "Count"), numeric.length],
|
|
1920
|
+
[deriveAggregateField(field, "Average"), sum / numeric.length],
|
|
1921
|
+
[deriveAggregateField(field, "Minimum"), minimum],
|
|
1922
|
+
[deriveAggregateField(field, "Maximum"), maximum]
|
|
1923
|
+
];
|
|
1924
|
+
for (const [aggregateField, aggregateValue] of aggregates) {
|
|
1925
|
+
subject = setField(subject, aggregateField, aggregateValue);
|
|
1926
|
+
mappings.push({
|
|
1927
|
+
field: aggregateField,
|
|
1928
|
+
value: aggregateValue,
|
|
1929
|
+
provenance: { category: "computed" },
|
|
1930
|
+
confidence: CONFIDENCE_COMPUTED
|
|
1931
|
+
});
|
|
1932
|
+
}
|
|
1933
|
+
continue;
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
subject = setField(subject, field, value);
|
|
1937
|
+
mappings.push({
|
|
1938
|
+
field,
|
|
1939
|
+
entity: entity.name,
|
|
1940
|
+
value,
|
|
1941
|
+
provenance: entity.provenance,
|
|
1942
|
+
confidence: entity.confidence
|
|
1943
|
+
});
|
|
1944
|
+
}
|
|
1945
|
+
const confidence = entities.length === 0 ? 0 : entities.reduce((total, entity) => total + entity.confidence, 0) / entities.length;
|
|
1946
|
+
return {
|
|
1947
|
+
subject,
|
|
1948
|
+
definition: template.definition,
|
|
1949
|
+
mappings,
|
|
1950
|
+
confidence
|
|
1951
|
+
};
|
|
1952
|
+
}
|
|
1953
|
+
};
|
|
1954
|
+
//#endregion
|
|
1955
|
+
//#region src/core/stages/Normalizer.ts
|
|
1956
|
+
/**
|
|
1957
|
+
* The `Normalizer` stage: applies contraction, abbreviation, and correction
|
|
1958
|
+
* substitutions in order, then collapses whitespace.
|
|
1959
|
+
*
|
|
1960
|
+
* @remarks
|
|
1961
|
+
* Each caller map is merged OVER the neutral built-in default for its slot —
|
|
1962
|
+
* `text` is never mutated (AGENTS §11). Every substitution actually applied
|
|
1963
|
+
* (one entry per matching map KEY, not per occurrence) is recorded on the
|
|
1964
|
+
* result's `changes`, in `contractions → abbreviations → corrections` order,
|
|
1965
|
+
* so the audit trail explains every character difference between `text` and
|
|
1966
|
+
* `NormalizeResult.text` (the final whitespace collapse carries no entry of
|
|
1967
|
+
* its own — it is structural cleanup, not a substitution).
|
|
1968
|
+
*
|
|
1969
|
+
* @example
|
|
1970
|
+
* ```ts
|
|
1971
|
+
* import { Normalizer } from '@src/core'
|
|
1972
|
+
*
|
|
1973
|
+
* const normalizer = new Normalizer({ contractions: { "can't": 'cannot' } })
|
|
1974
|
+
* normalizer.normalize("can't stop")
|
|
1975
|
+
* // { text: 'cannot stop', changes: [{ from: "can't", to: 'cannot' }] }
|
|
1976
|
+
* ```
|
|
1977
|
+
*/
|
|
1978
|
+
var Normalizer = class {
|
|
1979
|
+
#contractions;
|
|
1980
|
+
#abbreviations;
|
|
1981
|
+
#corrections;
|
|
1982
|
+
constructor(options) {
|
|
1983
|
+
this.#contractions = {
|
|
1984
|
+
...DEFAULT_CONTRACTIONS,
|
|
1985
|
+
...options?.contractions
|
|
1986
|
+
};
|
|
1987
|
+
this.#abbreviations = {
|
|
1988
|
+
...DEFAULT_ABBREVIATIONS,
|
|
1989
|
+
...options?.abbreviations
|
|
1990
|
+
};
|
|
1991
|
+
this.#corrections = {
|
|
1992
|
+
...DEFAULT_CORRECTIONS,
|
|
1993
|
+
...options?.corrections
|
|
1994
|
+
};
|
|
1995
|
+
}
|
|
1996
|
+
normalize(text) {
|
|
1997
|
+
const changes = [];
|
|
1998
|
+
let working = text;
|
|
1999
|
+
for (const map of [
|
|
2000
|
+
this.#contractions,
|
|
2001
|
+
this.#abbreviations,
|
|
2002
|
+
this.#corrections
|
|
2003
|
+
]) {
|
|
2004
|
+
const applied = this.#applyStage(working, map);
|
|
2005
|
+
working = applied.text;
|
|
2006
|
+
changes.push(...applied.changes);
|
|
2007
|
+
}
|
|
2008
|
+
return {
|
|
2009
|
+
text: collapseWhitespace(working),
|
|
2010
|
+
changes
|
|
2011
|
+
};
|
|
2012
|
+
}
|
|
2013
|
+
#applyStage(text, map) {
|
|
2014
|
+
let working = text;
|
|
2015
|
+
const changes = [];
|
|
2016
|
+
for (const [from, to] of Object.entries(map)) if (new RegExp(`\\b${escapeRegExp(from)}\\b`, "i").test(working)) {
|
|
2017
|
+
working = applyReplacements(working, { [from]: to });
|
|
2018
|
+
changes.push({
|
|
2019
|
+
from,
|
|
2020
|
+
to
|
|
2021
|
+
});
|
|
2022
|
+
}
|
|
2023
|
+
return {
|
|
2024
|
+
text: working,
|
|
2025
|
+
changes
|
|
2026
|
+
};
|
|
2027
|
+
}
|
|
2028
|
+
};
|
|
2029
|
+
//#endregion
|
|
2030
|
+
//#region src/core/Interpret.ts
|
|
2031
|
+
/**
|
|
2032
|
+
* The interpretation orchestrator — the sole public entry point of the
|
|
2033
|
+
* `interprets` module, mirroring the reasons `Reason` orchestrator shape.
|
|
2034
|
+
*
|
|
2035
|
+
* @remarks
|
|
2036
|
+
* `interpret()` is genuinely SYNCHRONOUS (scsr's was fake-async with zero
|
|
2037
|
+
* `await`s) and runs a fixed five-stage pipeline —
|
|
2038
|
+
* `[normalize, extract, clarify, format, generate]` — each producing one
|
|
2039
|
+
* {@link StageRecord}. Between `extract` and `clarify` the orchestrator matches
|
|
2040
|
+
* the classified {@link Intent} against its registered {@link Template}s and,
|
|
2041
|
+
* on a match, assigns the extracted numbers to that template's mappings
|
|
2042
|
+
* (`assignEntities`) — a template-owned step, not a sixth stage. No match, or a
|
|
2043
|
+
* matched template whose intent confidence falls below the configured `floor`,
|
|
2044
|
+
* yields an explicit, auditable INCOMPLETE result (a `field: 'intent'`
|
|
2045
|
+
* ambiguity, absent subject/definition) rather than scsr's arbitrary
|
|
2046
|
+
* `templates[0]` fallback. A stage THROW is caught, marked on its record AND on
|
|
2047
|
+
* `failures`, emitted as `error`, and still yields a visible incomplete result
|
|
2048
|
+
* — never a silent fallback. Every result carries a `digest` over its original
|
|
2049
|
+
* text plus the matched template id/version and the built subject/definition,
|
|
2050
|
+
* so re-running the same text against the same template version reproduces the
|
|
2051
|
+
* same digest (the replay contract). `describe` / `narrate` are the reverse
|
|
2052
|
+
* direction (structure → prose). `destroy()` is idempotent, tears down the
|
|
2053
|
+
* registry and context, then destroys the emitter LAST (AGENTS §13); every
|
|
2054
|
+
* method afterwards except the {@link emitter} getter throws
|
|
2055
|
+
* `InterpretError('DESTROYED', …)`.
|
|
2056
|
+
*
|
|
2057
|
+
* @example
|
|
2058
|
+
* ```ts
|
|
2059
|
+
* import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
|
|
2060
|
+
* import { Interpret, Extractor } from '@src/core'
|
|
2061
|
+
*
|
|
2062
|
+
* const interpret = new Interpret({
|
|
2063
|
+
* extractor: new Extractor({ actions: { calculate: 'calculate' }, domains: { arithmetic: ['arithmetic'] } }),
|
|
2064
|
+
* templates: [
|
|
2065
|
+
* {
|
|
2066
|
+
* id: 't1',
|
|
2067
|
+
* name: 'Arithmetic',
|
|
2068
|
+
* domain: 'arithmetic',
|
|
2069
|
+
* intents: ['calculate'],
|
|
2070
|
+
* mappings: [{ entity: 'value', aliases: [], field: 'value' }],
|
|
2071
|
+
* defaults: [],
|
|
2072
|
+
* computations: [],
|
|
2073
|
+
* definition: quantitativeDefinition('t1', 'Arithmetic', [
|
|
2074
|
+
* factorGroup('total', 'sum', [fieldFactor('value', 'value')]),
|
|
2075
|
+
* ]),
|
|
2076
|
+
* },
|
|
2077
|
+
* ],
|
|
2078
|
+
* })
|
|
2079
|
+
* interpret.interpret('calculate arithmetic 42').subject // { value: 42 }
|
|
2080
|
+
* ```
|
|
2081
|
+
*/
|
|
2082
|
+
var Interpret = class {
|
|
2083
|
+
#templates;
|
|
2084
|
+
#context;
|
|
2085
|
+
#normalizer;
|
|
2086
|
+
#extractor;
|
|
2087
|
+
#clarifier;
|
|
2088
|
+
#formatter;
|
|
2089
|
+
#generator;
|
|
2090
|
+
#similarity;
|
|
2091
|
+
#floor;
|
|
2092
|
+
#narrator;
|
|
2093
|
+
#emitter;
|
|
2094
|
+
#destroyed = false;
|
|
2095
|
+
constructor(options) {
|
|
2096
|
+
this.#similarity = options?.similarity ?? .8;
|
|
2097
|
+
this.#floor = options?.floor ?? .3;
|
|
2098
|
+
this.#templates = new TemplateManager({ templates: options?.templates });
|
|
2099
|
+
this.#context = options?.context ?? new InterpretContext({ history: options?.history });
|
|
2100
|
+
this.#normalizer = options?.normalizer ?? new Normalizer();
|
|
2101
|
+
this.#extractor = options?.extractor ?? new Extractor();
|
|
2102
|
+
this.#clarifier = options?.clarifier ?? new Clarifier({ floor: this.#floor });
|
|
2103
|
+
this.#formatter = options?.formatter ?? new Formatter();
|
|
2104
|
+
this.#generator = options?.generator ?? new Generator();
|
|
2105
|
+
this.#narrator = new Narrator({
|
|
2106
|
+
lexicon: options?.lexicon,
|
|
2107
|
+
formatters: options?.formatters
|
|
2108
|
+
});
|
|
2109
|
+
this.#emitter = new _orkestrel_emitter.Emitter({
|
|
2110
|
+
on: options?.on,
|
|
2111
|
+
error: options?.error
|
|
2112
|
+
});
|
|
2113
|
+
}
|
|
2114
|
+
get emitter() {
|
|
2115
|
+
return this.#emitter;
|
|
2116
|
+
}
|
|
2117
|
+
interpret(text) {
|
|
2118
|
+
this.#ensureAlive();
|
|
2119
|
+
const stages = [];
|
|
2120
|
+
let normalized;
|
|
2121
|
+
try {
|
|
2122
|
+
normalized = this.#normalizer.normalize(text);
|
|
2123
|
+
} catch (error) {
|
|
2124
|
+
return this.#abort(text, text, {
|
|
2125
|
+
action: "",
|
|
2126
|
+
domain: "",
|
|
2127
|
+
confidence: 0
|
|
2128
|
+
}, [], [], stages, "normalize", "NORMALIZE_FAILED", text, error, [
|
|
2129
|
+
"extract",
|
|
2130
|
+
"clarify",
|
|
2131
|
+
"format",
|
|
2132
|
+
"generate"
|
|
2133
|
+
], void 0, void 0);
|
|
2134
|
+
}
|
|
2135
|
+
stages.push({
|
|
2136
|
+
stage: "normalize",
|
|
2137
|
+
input: text,
|
|
2138
|
+
output: normalized,
|
|
2139
|
+
failed: false
|
|
2140
|
+
});
|
|
2141
|
+
let extract;
|
|
2142
|
+
try {
|
|
2143
|
+
extract = this.#extractor.extract(normalized.text);
|
|
2144
|
+
} catch (error) {
|
|
2145
|
+
return this.#abort(text, normalized.text, {
|
|
2146
|
+
action: "",
|
|
2147
|
+
domain: "",
|
|
2148
|
+
confidence: 0
|
|
2149
|
+
}, [], [], stages, "extract", "EXTRACT_FAILED", normalized.text, error, [
|
|
2150
|
+
"clarify",
|
|
2151
|
+
"format",
|
|
2152
|
+
"generate"
|
|
2153
|
+
], void 0, void 0);
|
|
2154
|
+
}
|
|
2155
|
+
stages.push({
|
|
2156
|
+
stage: "extract",
|
|
2157
|
+
input: normalized.text,
|
|
2158
|
+
output: extract,
|
|
2159
|
+
failed: false
|
|
2160
|
+
});
|
|
2161
|
+
const intent = extract.intent;
|
|
2162
|
+
const matched = matchTemplate(intent, this.#templates.templates().map((record) => record.template), this.#floor);
|
|
2163
|
+
if (matched === void 0) return this.#gate(text, normalized.text, intent, [], stages, "NO_TEMPLATE", void 0, void 0);
|
|
2164
|
+
const assigned = assignEntities(extract.numbers, matched.mappings, normalized.text, this.#similarity);
|
|
2165
|
+
const version = this.#templates.template(matched.id)?.version;
|
|
2166
|
+
if (intent.confidence < this.#floor) return this.#gate(text, normalized.text, intent, assigned, stages, "LOW_CONFIDENCE", matched.id, version);
|
|
2167
|
+
let clarified;
|
|
2168
|
+
try {
|
|
2169
|
+
clarified = this.#clarifier.clarify(assigned, matched, this.#context, intent);
|
|
2170
|
+
} catch (error) {
|
|
2171
|
+
return this.#abort(text, normalized.text, intent, assigned, [], stages, "clarify", "CLARIFY_FAILED", assigned, error, ["format", "generate"], matched.id, version);
|
|
2172
|
+
}
|
|
2173
|
+
stages.push({
|
|
2174
|
+
stage: "clarify",
|
|
2175
|
+
input: assigned,
|
|
2176
|
+
output: clarified,
|
|
2177
|
+
failed: false
|
|
2178
|
+
});
|
|
2179
|
+
const formatInput = {
|
|
2180
|
+
intent,
|
|
2181
|
+
entities: clarified.entities,
|
|
2182
|
+
ambiguities: clarified.ambiguities
|
|
2183
|
+
};
|
|
2184
|
+
let formatted;
|
|
2185
|
+
try {
|
|
2186
|
+
formatted = this.#formatter.format(intent, matched, clarified.entities, clarified.ambiguities);
|
|
2187
|
+
} catch (error) {
|
|
2188
|
+
return this.#abort(text, normalized.text, intent, clarified.entities, clarified.ambiguities, stages, "format", "FORMAT_FAILED", formatInput, error, ["generate"], matched.id, version);
|
|
2189
|
+
}
|
|
2190
|
+
stages.push({
|
|
2191
|
+
stage: "format",
|
|
2192
|
+
input: formatInput,
|
|
2193
|
+
output: formatted,
|
|
2194
|
+
failed: false
|
|
2195
|
+
});
|
|
2196
|
+
let generated;
|
|
2197
|
+
try {
|
|
2198
|
+
generated = this.#generator.generate(clarified.entities, matched);
|
|
2199
|
+
} catch (error) {
|
|
2200
|
+
return this.#abort(text, normalized.text, intent, clarified.entities, clarified.ambiguities, stages, "generate", "GENERATE_FAILED", clarified.entities, error, [], matched.id, version);
|
|
2201
|
+
}
|
|
2202
|
+
stages.push({
|
|
2203
|
+
stage: "generate",
|
|
2204
|
+
input: clarified.entities,
|
|
2205
|
+
output: generated,
|
|
2206
|
+
failed: false
|
|
2207
|
+
});
|
|
2208
|
+
const digest = digestValue({
|
|
2209
|
+
text,
|
|
2210
|
+
templateId: matched.id,
|
|
2211
|
+
templateVersion: version,
|
|
2212
|
+
subject: generated.subject,
|
|
2213
|
+
definition: generated.definition
|
|
2214
|
+
});
|
|
2215
|
+
const result = {
|
|
2216
|
+
text,
|
|
2217
|
+
normalized: normalized.text,
|
|
2218
|
+
intent,
|
|
2219
|
+
entities: clarified.entities,
|
|
2220
|
+
subject: generated.subject,
|
|
2221
|
+
definition: generated.definition,
|
|
2222
|
+
mappings: generated.mappings,
|
|
2223
|
+
ambiguities: clarified.ambiguities,
|
|
2224
|
+
prompt: formatted.prompt,
|
|
2225
|
+
stages,
|
|
2226
|
+
failures: [],
|
|
2227
|
+
complete: clarified.complete,
|
|
2228
|
+
confidence: generated.confidence,
|
|
2229
|
+
digest
|
|
2230
|
+
};
|
|
2231
|
+
this.#context.subjects.add(generated.subject);
|
|
2232
|
+
this.#context.definitions.add(generated.definition, { id: generated.definition.id });
|
|
2233
|
+
this.#context.add(result);
|
|
2234
|
+
this.#emitter.emit("interpret", result);
|
|
2235
|
+
return result;
|
|
2236
|
+
}
|
|
2237
|
+
register(template) {
|
|
2238
|
+
this.#ensureAlive();
|
|
2239
|
+
this.#templates.add(template, { id: template.id });
|
|
2240
|
+
this.#emitter.emit("register", template.id);
|
|
2241
|
+
}
|
|
2242
|
+
unregister(id) {
|
|
2243
|
+
this.#ensureAlive();
|
|
2244
|
+
return this.#templates.remove(id);
|
|
2245
|
+
}
|
|
2246
|
+
template(id) {
|
|
2247
|
+
this.#ensureAlive();
|
|
2248
|
+
return this.#templates.template(id)?.template;
|
|
2249
|
+
}
|
|
2250
|
+
templates() {
|
|
2251
|
+
this.#ensureAlive();
|
|
2252
|
+
return this.#templates.templates().map((record) => record.template);
|
|
2253
|
+
}
|
|
2254
|
+
describe(definition) {
|
|
2255
|
+
this.#ensureAlive();
|
|
2256
|
+
return this.#narrator.describe(definition);
|
|
2257
|
+
}
|
|
2258
|
+
narrate(result) {
|
|
2259
|
+
this.#ensureAlive();
|
|
2260
|
+
return this.#narrator.narrate(result);
|
|
2261
|
+
}
|
|
2262
|
+
destroy() {
|
|
2263
|
+
if (this.#destroyed) return;
|
|
2264
|
+
this.#templates.destroy();
|
|
2265
|
+
this.#context.destroy();
|
|
2266
|
+
this.#destroyed = true;
|
|
2267
|
+
this.#emitter.emit("destroy");
|
|
2268
|
+
this.#emitter.destroy();
|
|
2269
|
+
}
|
|
2270
|
+
#gate(text, normalized, intent, entities, stages, code, templateId, templateVersion) {
|
|
2271
|
+
const domains = [...new Set(this.#templates.templates().map((record) => record.template.domain))];
|
|
2272
|
+
const ambiguity = {
|
|
2273
|
+
field: "intent",
|
|
2274
|
+
question: code === "NO_TEMPLATE" ? "Which domain and action did you mean?" : "Which did you mean? The intent was too weak to act on.",
|
|
2275
|
+
candidates: domains,
|
|
2276
|
+
required: true
|
|
2277
|
+
};
|
|
2278
|
+
const failure = {
|
|
2279
|
+
stage: "clarify",
|
|
2280
|
+
code,
|
|
2281
|
+
message: code === "NO_TEMPLATE" ? "No registered template matched the classified intent" : "Classified intent confidence fell below the configured floor"
|
|
2282
|
+
};
|
|
2283
|
+
return this.#assemble(text, normalized, intent, entities, [ambiguity], stages, [failure], [
|
|
2284
|
+
"clarify",
|
|
2285
|
+
"format",
|
|
2286
|
+
"generate"
|
|
2287
|
+
], templateId, templateVersion);
|
|
2288
|
+
}
|
|
2289
|
+
#abort(text, normalized, intent, entities, ambiguities, stages, stage, code, input, error, remaining, templateId, templateVersion) {
|
|
2290
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2291
|
+
stages.push({
|
|
2292
|
+
stage,
|
|
2293
|
+
input,
|
|
2294
|
+
output: void 0,
|
|
2295
|
+
failed: true,
|
|
2296
|
+
error: message
|
|
2297
|
+
});
|
|
2298
|
+
this.#emitter.emit("error", error);
|
|
2299
|
+
return this.#assemble(text, normalized, intent, entities, ambiguities, stages, [{
|
|
2300
|
+
stage,
|
|
2301
|
+
code,
|
|
2302
|
+
message
|
|
2303
|
+
}], remaining, templateId, templateVersion);
|
|
2304
|
+
}
|
|
2305
|
+
#assemble(text, normalized, intent, entities, ambiguities, stages, failures, remaining, templateId, templateVersion) {
|
|
2306
|
+
for (const stage of remaining) stages.push({
|
|
2307
|
+
stage,
|
|
2308
|
+
input: void 0,
|
|
2309
|
+
output: void 0,
|
|
2310
|
+
failed: false
|
|
2311
|
+
});
|
|
2312
|
+
const digest = digestValue({
|
|
2313
|
+
text,
|
|
2314
|
+
templateId,
|
|
2315
|
+
templateVersion,
|
|
2316
|
+
subject: void 0,
|
|
2317
|
+
definition: void 0
|
|
2318
|
+
});
|
|
2319
|
+
const result = {
|
|
2320
|
+
text,
|
|
2321
|
+
normalized,
|
|
2322
|
+
intent,
|
|
2323
|
+
entities,
|
|
2324
|
+
mappings: [],
|
|
2325
|
+
ambiguities,
|
|
2326
|
+
prompt: "",
|
|
2327
|
+
stages,
|
|
2328
|
+
failures: [...failures],
|
|
2329
|
+
complete: false,
|
|
2330
|
+
confidence: 0,
|
|
2331
|
+
digest
|
|
2332
|
+
};
|
|
2333
|
+
this.#context.add(result);
|
|
2334
|
+
this.#emitter.emit("interpret", result);
|
|
2335
|
+
return result;
|
|
2336
|
+
}
|
|
2337
|
+
#ensureAlive() {
|
|
2338
|
+
if (this.#destroyed) throw new InterpretError("DESTROYED", "Interpret has been destroyed");
|
|
2339
|
+
}
|
|
2340
|
+
};
|
|
2341
|
+
//#endregion
|
|
2342
|
+
//#region src/core/factories.ts
|
|
2343
|
+
/**
|
|
2344
|
+
* Create an interpretation orchestrator.
|
|
2345
|
+
*
|
|
2346
|
+
* @remarks
|
|
2347
|
+
* `interpret()` is genuinely synchronous and runs the fixed five-stage
|
|
2348
|
+
* pipeline `[normalize, extract, clarify, format, generate]`. Every stage
|
|
2349
|
+
* slot (`normalizer` / `extractor` / `clarifier` / `formatter` / `generator`)
|
|
2350
|
+
* is bring-your-own — a supplied implementation is used as-is, else the
|
|
2351
|
+
* built-in stage is constructed from the matching per-stage options.
|
|
2352
|
+
*
|
|
2353
|
+
* @param options - Optional templates, context, stage implementations, the
|
|
2354
|
+
* `similarity` / `floor` axes, and emitter hooks
|
|
2355
|
+
* @returns A working {@link InterpretInterface}
|
|
2356
|
+
*
|
|
2357
|
+
* @example
|
|
2358
|
+
* ```ts
|
|
2359
|
+
* import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
|
|
2360
|
+
* import { createInterpret } from '@src/core'
|
|
2361
|
+
*
|
|
2362
|
+
* const interpret = createInterpret({
|
|
2363
|
+
* extractor: { extract: () => ({ intent: { action: 'calculate', domain: 'arithmetic', confidence: 1 }, numbers: [42], complete: true }) },
|
|
2364
|
+
* templates: [
|
|
2365
|
+
* {
|
|
2366
|
+
* id: 't1',
|
|
2367
|
+
* name: 'Arithmetic',
|
|
2368
|
+
* domain: 'arithmetic',
|
|
2369
|
+
* intents: ['calculate'],
|
|
2370
|
+
* mappings: [{ entity: 'value', aliases: [], field: 'value' }],
|
|
2371
|
+
* defaults: [],
|
|
2372
|
+
* computations: [],
|
|
2373
|
+
* definition: quantitativeDefinition('t1', 'Arithmetic', [
|
|
2374
|
+
* factorGroup('total', 'sum', [fieldFactor('value', 'value')]),
|
|
2375
|
+
* ]),
|
|
2376
|
+
* },
|
|
2377
|
+
* ],
|
|
2378
|
+
* })
|
|
2379
|
+
* interpret.interpret('calculate arithmetic 42').subject // { value: 42 }
|
|
2380
|
+
* ```
|
|
2381
|
+
*/
|
|
2382
|
+
function createInterpret(options) {
|
|
2383
|
+
return new Interpret(options);
|
|
2384
|
+
}
|
|
2385
|
+
/**
|
|
2386
|
+
* Create a text normalizer.
|
|
2387
|
+
*
|
|
2388
|
+
* @param options - Optional contraction / abbreviation / correction maps,
|
|
2389
|
+
* merged over the neutral built-in defaults
|
|
2390
|
+
* @returns A stateless {@link NormalizerInterface}
|
|
2391
|
+
*
|
|
2392
|
+
* @example
|
|
2393
|
+
* ```ts
|
|
2394
|
+
* import { createNormalizer } from '@src/core'
|
|
2395
|
+
*
|
|
2396
|
+
* createNormalizer().normalize("it's cold") // { text: 'it is cold', changes: [{ from: "it's", to: 'it is' }] }
|
|
2397
|
+
* ```
|
|
2398
|
+
*/
|
|
2399
|
+
function createNormalizer(options) {
|
|
2400
|
+
return new Normalizer(options);
|
|
2401
|
+
}
|
|
2402
|
+
/**
|
|
2403
|
+
* Create a template-agnostic intent classifier and number extractor.
|
|
2404
|
+
*
|
|
2405
|
+
* @param options - Optional caller `actions` / `domains` vocabularies
|
|
2406
|
+
* @returns A stateless {@link ExtractorInterface}
|
|
2407
|
+
*
|
|
2408
|
+
* @example
|
|
2409
|
+
* ```ts
|
|
2410
|
+
* import { createExtractor } from '@src/core'
|
|
2411
|
+
*
|
|
2412
|
+
* const extractor = createExtractor({
|
|
2413
|
+
* actions: { calculate: 'calculate' },
|
|
2414
|
+
* domains: { arithmetic: ['arithmetic'] },
|
|
2415
|
+
* })
|
|
2416
|
+
* extractor.extract('calculate arithmetic 42').numbers // [42]
|
|
2417
|
+
* ```
|
|
2418
|
+
*/
|
|
2419
|
+
function createExtractor(options) {
|
|
2420
|
+
return new Extractor(options);
|
|
2421
|
+
}
|
|
2422
|
+
/**
|
|
2423
|
+
* Create a clarifier — carry-over, defaults, and computed-field resolution
|
|
2424
|
+
* against an assigned entity set.
|
|
2425
|
+
*
|
|
2426
|
+
* @param options - Optional confidence `floor` for raised ambiguities
|
|
2427
|
+
* @returns A stateless {@link ClarifierInterface}
|
|
2428
|
+
*
|
|
2429
|
+
* @example
|
|
2430
|
+
* ```ts
|
|
2431
|
+
* import { createClarifier } from '@src/core'
|
|
2432
|
+
*
|
|
2433
|
+
* const clarifier = createClarifier({ floor: 0.5 })
|
|
2434
|
+
* ```
|
|
2435
|
+
*/
|
|
2436
|
+
function createClarifier(options) {
|
|
2437
|
+
return new Clarifier(options);
|
|
2438
|
+
}
|
|
2439
|
+
/**
|
|
2440
|
+
* Create a prompt formatter.
|
|
2441
|
+
*
|
|
2442
|
+
* @param options - Optional caller intent-verb phrasing map
|
|
2443
|
+
* @returns A stateless {@link FormatterInterface}
|
|
2444
|
+
*
|
|
2445
|
+
* @example
|
|
2446
|
+
* ```ts
|
|
2447
|
+
* import { createFormatter } from '@src/core'
|
|
2448
|
+
*
|
|
2449
|
+
* const formatter = createFormatter({ verbs: { calculate: 'Calculate' } })
|
|
2450
|
+
* ```
|
|
2451
|
+
*/
|
|
2452
|
+
function createFormatter(options) {
|
|
2453
|
+
return new Formatter(options);
|
|
2454
|
+
}
|
|
2455
|
+
/**
|
|
2456
|
+
* Create a subject/definition generator.
|
|
2457
|
+
*
|
|
2458
|
+
* @param options - Currently an empty extension seam
|
|
2459
|
+
* @returns A stateless {@link GeneratorInterface}
|
|
2460
|
+
*
|
|
2461
|
+
* @example
|
|
2462
|
+
* ```ts
|
|
2463
|
+
* import { createGenerator } from '@src/core'
|
|
2464
|
+
*
|
|
2465
|
+
* const generator = createGenerator()
|
|
2466
|
+
* ```
|
|
2467
|
+
*/
|
|
2468
|
+
function createGenerator(_options) {
|
|
2469
|
+
return new Generator();
|
|
2470
|
+
}
|
|
2471
|
+
/**
|
|
2472
|
+
* Create a template registry.
|
|
2473
|
+
*
|
|
2474
|
+
* @param options - Optional initial seed collection
|
|
2475
|
+
* @returns A working {@link TemplateManagerInterface}
|
|
2476
|
+
*
|
|
2477
|
+
* @example
|
|
2478
|
+
* ```ts
|
|
2479
|
+
* import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
|
|
2480
|
+
* import { createTemplate, createTemplateManager } from '@src/core'
|
|
2481
|
+
*
|
|
2482
|
+
* const template = createTemplate({
|
|
2483
|
+
* id: 't1', name: 'Arithmetic', domain: 'arithmetic', intents: ['calculate'],
|
|
2484
|
+
* mappings: [{ entity: 'value', aliases: [], field: 'value' }], defaults: [], computations: [],
|
|
2485
|
+
* definition: quantitativeDefinition('t1', 'Arithmetic', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])]),
|
|
2486
|
+
* })
|
|
2487
|
+
* const templates = createTemplateManager({ templates: [template] })
|
|
2488
|
+
* templates.size // 1
|
|
2489
|
+
* ```
|
|
2490
|
+
*/
|
|
2491
|
+
function createTemplateManager(options) {
|
|
2492
|
+
return new TemplateManager(options);
|
|
2493
|
+
}
|
|
2494
|
+
/**
|
|
2495
|
+
* Create a subject registry.
|
|
2496
|
+
*
|
|
2497
|
+
* @remarks
|
|
2498
|
+
* Mints its own record ids on `add` when none is supplied — a `Subject`
|
|
2499
|
+
* carries no `id` field of its own.
|
|
2500
|
+
*
|
|
2501
|
+
* @param options - Optional initial seed collection
|
|
2502
|
+
* @returns A working {@link SubjectManagerInterface}
|
|
2503
|
+
*
|
|
2504
|
+
* @example
|
|
2505
|
+
* ```ts
|
|
2506
|
+
* import { createSubjectManager } from '@src/core'
|
|
2507
|
+
*
|
|
2508
|
+
* const subjects = createSubjectManager({ subjects: [{ value: 1 }] })
|
|
2509
|
+
* subjects.size // 1
|
|
2510
|
+
* ```
|
|
2511
|
+
*/
|
|
2512
|
+
function createSubjectManager(options) {
|
|
2513
|
+
return new SubjectManager(options);
|
|
2514
|
+
}
|
|
2515
|
+
/**
|
|
2516
|
+
* Create a definition registry.
|
|
2517
|
+
*
|
|
2518
|
+
* @param options - Optional initial seed collection
|
|
2519
|
+
* @returns A working {@link DefinitionManagerInterface}
|
|
2520
|
+
*
|
|
2521
|
+
* @example
|
|
2522
|
+
* ```ts
|
|
2523
|
+
* import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
|
|
2524
|
+
* import { createDefinitionManager } from '@src/core'
|
|
2525
|
+
*
|
|
2526
|
+
* const definitions = createDefinitionManager({
|
|
2527
|
+
* definitions: [quantitativeDefinition('d1', 'D1', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])])],
|
|
2528
|
+
* })
|
|
2529
|
+
* definitions.size // 1
|
|
2530
|
+
* ```
|
|
2531
|
+
*/
|
|
2532
|
+
function createDefinitionManager(options) {
|
|
2533
|
+
return new DefinitionManager(options);
|
|
2534
|
+
}
|
|
2535
|
+
/**
|
|
2536
|
+
* Create a cross-turn interpretation context.
|
|
2537
|
+
*
|
|
2538
|
+
* @param options - Optional `session` label and `history` ring-buffer cap
|
|
2539
|
+
* @returns A working {@link InterpretContextInterface}
|
|
2540
|
+
*
|
|
2541
|
+
* @example
|
|
2542
|
+
* ```ts
|
|
2543
|
+
* import { createInterpretContext } from '@src/core'
|
|
2544
|
+
*
|
|
2545
|
+
* const context = createInterpretContext({ session: 'turn-1', history: 4 })
|
|
2546
|
+
* context.previous() // []
|
|
2547
|
+
* ```
|
|
2548
|
+
*/
|
|
2549
|
+
function createInterpretContext(options) {
|
|
2550
|
+
return new InterpretContext(options);
|
|
2551
|
+
}
|
|
2552
|
+
/**
|
|
2553
|
+
* Build and validate one interpretation template from plain data.
|
|
2554
|
+
*
|
|
2555
|
+
* @remarks
|
|
2556
|
+
* The factory/coercer pair for template intake (AGENTS §4.6.1): this throws
|
|
2557
|
+
* on malformed data, while `parseTemplate` returns `undefined`. Data failing
|
|
2558
|
+
* {@link isTemplate} throws `InterpretError('INVALID_TEMPLATE', …)`.
|
|
2559
|
+
*
|
|
2560
|
+
* @param data - The candidate template data
|
|
2561
|
+
* @returns The same data, now known to satisfy {@link Template}
|
|
2562
|
+
* @throws {@link InterpretError} `INVALID_TEMPLATE` when `data` fails validation
|
|
2563
|
+
*
|
|
2564
|
+
* @example
|
|
2565
|
+
* ```ts
|
|
2566
|
+
* import { factorGroup, fieldFactor, quantitativeDefinition } from '@orkestrel/reason'
|
|
2567
|
+
* import { createTemplate } from '@src/core'
|
|
2568
|
+
*
|
|
2569
|
+
* const template = createTemplate({
|
|
2570
|
+
* id: 't1', name: 'Arithmetic', domain: 'arithmetic', intents: ['calculate'],
|
|
2571
|
+
* mappings: [{ entity: 'value', aliases: [], field: 'value' }], defaults: [], computations: [],
|
|
2572
|
+
* definition: quantitativeDefinition('t1', 'Arithmetic', [factorGroup('total', 'sum', [fieldFactor('value', 'value')])]),
|
|
2573
|
+
* })
|
|
2574
|
+
* template.id // 't1'
|
|
2575
|
+
* ```
|
|
2576
|
+
*/
|
|
2577
|
+
function createTemplate(data) {
|
|
2578
|
+
if (!isTemplate(data)) throw new InterpretError("INVALID_TEMPLATE", "Template data failed validation");
|
|
2579
|
+
return data;
|
|
2580
|
+
}
|
|
2581
|
+
/**
|
|
2582
|
+
* Create a lexicon-driven reverse-direction rendering engine.
|
|
2583
|
+
*
|
|
2584
|
+
* @remarks
|
|
2585
|
+
* Stateless — `phrase` / `label` / `line` / `value` are total lookups into a
|
|
2586
|
+
* caller `Lexicon` merged over `DEFAULT_LEXICON`, and `describe` / `narrate`
|
|
2587
|
+
* compose them over a reasons `Definition` / `ReasonResult`.
|
|
2588
|
+
*
|
|
2589
|
+
* @param options - Optional `lexicon` and `formatters` map
|
|
2590
|
+
* @returns A stateless {@link NarratorInterface}
|
|
2591
|
+
*
|
|
2592
|
+
* @example
|
|
2593
|
+
* ```ts
|
|
2594
|
+
* import { createNarrator } from '@src/core'
|
|
2595
|
+
*
|
|
2596
|
+
* const narrator = createNarrator({ lexicon: { templates: { 'subject.empty': 'nothing here' } } })
|
|
2597
|
+
* narrator.line('subject.empty', {}) // 'nothing here'
|
|
2598
|
+
* ```
|
|
2599
|
+
*/
|
|
2600
|
+
function createNarrator(options) {
|
|
2601
|
+
return new Narrator(options);
|
|
2602
|
+
}
|
|
2603
|
+
//#endregion
|
|
2604
|
+
exports.CONFIDENCE_ALIAS = CONFIDENCE_ALIAS;
|
|
2605
|
+
exports.CONFIDENCE_CARRIED = CONFIDENCE_CARRIED;
|
|
2606
|
+
exports.CONFIDENCE_COLLECT = CONFIDENCE_COLLECT;
|
|
2607
|
+
exports.CONFIDENCE_COMPUTED = CONFIDENCE_COMPUTED;
|
|
2608
|
+
exports.CONFIDENCE_DEFAULT = CONFIDENCE_DEFAULT;
|
|
2609
|
+
exports.CONFIDENCE_EXACT = CONFIDENCE_EXACT;
|
|
2610
|
+
exports.CONFIDENCE_POSITIONAL = CONFIDENCE_POSITIONAL;
|
|
2611
|
+
exports.Clarifier = Clarifier;
|
|
2612
|
+
exports.DEFAULT_ABBREVIATIONS = DEFAULT_ABBREVIATIONS;
|
|
2613
|
+
exports.DEFAULT_ACTIONS = DEFAULT_ACTIONS;
|
|
2614
|
+
exports.DEFAULT_CONTRACTIONS = DEFAULT_CONTRACTIONS;
|
|
2615
|
+
exports.DEFAULT_CORRECTIONS = DEFAULT_CORRECTIONS;
|
|
2616
|
+
exports.DEFAULT_DOMAINS = DEFAULT_DOMAINS;
|
|
2617
|
+
exports.DEFAULT_INTERPRET_FLOOR = DEFAULT_INTERPRET_FLOOR;
|
|
2618
|
+
exports.DEFAULT_INTERPRET_HISTORY = DEFAULT_INTERPRET_HISTORY;
|
|
2619
|
+
exports.DEFAULT_INTERPRET_SIMILARITY = DEFAULT_INTERPRET_SIMILARITY;
|
|
2620
|
+
exports.DEFAULT_LEXICON = DEFAULT_LEXICON;
|
|
2621
|
+
exports.DEFAULT_VERBS = DEFAULT_VERBS;
|
|
2622
|
+
exports.DefinitionManager = DefinitionManager;
|
|
2623
|
+
exports.Extractor = Extractor;
|
|
2624
|
+
exports.Formatter = Formatter;
|
|
2625
|
+
exports.Generator = Generator;
|
|
2626
|
+
exports.INTERPRET_ID = INTERPRET_ID;
|
|
2627
|
+
exports.Interpret = Interpret;
|
|
2628
|
+
exports.InterpretContext = InterpretContext;
|
|
2629
|
+
exports.InterpretError = InterpretError;
|
|
2630
|
+
exports.NUMBER_PATTERN = NUMBER_PATTERN;
|
|
2631
|
+
exports.Narrator = Narrator;
|
|
2632
|
+
exports.Normalizer = Normalizer;
|
|
2633
|
+
exports.SubjectManager = SubjectManager;
|
|
2634
|
+
exports.TemplateManager = TemplateManager;
|
|
2635
|
+
exports.UNSAFE_FIELD_SEGMENTS = UNSAFE_FIELD_SEGMENTS;
|
|
2636
|
+
exports.applyReplacements = applyReplacements;
|
|
2637
|
+
exports.assignEntities = assignEntities;
|
|
2638
|
+
exports.canonicalize = canonicalize;
|
|
2639
|
+
exports.classifyIntent = classifyIntent;
|
|
2640
|
+
exports.collapseWhitespace = collapseWhitespace;
|
|
2641
|
+
exports.createClarifier = createClarifier;
|
|
2642
|
+
exports.createDefinitionManager = createDefinitionManager;
|
|
2643
|
+
exports.createExtractor = createExtractor;
|
|
2644
|
+
exports.createFormatter = createFormatter;
|
|
2645
|
+
exports.createGenerator = createGenerator;
|
|
2646
|
+
exports.createInterpret = createInterpret;
|
|
2647
|
+
exports.createInterpretContext = createInterpretContext;
|
|
2648
|
+
exports.createNarrator = createNarrator;
|
|
2649
|
+
exports.createNormalizer = createNormalizer;
|
|
2650
|
+
exports.createSubjectManager = createSubjectManager;
|
|
2651
|
+
exports.createTemplate = createTemplate;
|
|
2652
|
+
exports.createTemplateManager = createTemplateManager;
|
|
2653
|
+
exports.deriveAggregateField = deriveAggregateField;
|
|
2654
|
+
exports.describeSubject = describeSubject;
|
|
2655
|
+
exports.digestValue = digestValue;
|
|
2656
|
+
exports.escapeRegExp = escapeRegExp;
|
|
2657
|
+
exports.extractNumbers = extractNumbers;
|
|
2658
|
+
exports.isComputedField = isComputedField;
|
|
2659
|
+
exports.isEntityMapping = isEntityMapping;
|
|
2660
|
+
exports.isFieldDefault = isFieldDefault;
|
|
2661
|
+
exports.isInterpretError = isInterpretError;
|
|
2662
|
+
exports.isTemplate = isTemplate;
|
|
2663
|
+
exports.matchAlias = matchAlias;
|
|
2664
|
+
exports.matchTemplate = matchTemplate;
|
|
2665
|
+
exports.parseTemplate = parseTemplate;
|
|
2666
|
+
exports.resolveExpression = resolveExpression;
|
|
2667
|
+
exports.scoreSimilarity = scoreSimilarity;
|
|
2668
|
+
exports.scoreTemplate = scoreTemplate;
|
|
2669
|
+
exports.setField = setField;
|
|
2670
|
+
exports.tokenize = tokenize;
|
|
2671
|
+
exports.variablesOf = variablesOf;
|
|
2672
|
+
|
|
2673
|
+
//# sourceMappingURL=index.cjs.map
|