@weaveintel/local-engines 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +79 -2
  2. package/dist/canonical.d.ts +21 -0
  3. package/dist/canonical.d.ts.map +1 -0
  4. package/dist/canonical.js +98 -0
  5. package/dist/canonical.js.map +1 -0
  6. package/dist/constants.d.ts +31 -0
  7. package/dist/constants.d.ts.map +1 -0
  8. package/dist/constants.js +68 -0
  9. package/dist/constants.js.map +1 -0
  10. package/dist/engine.d.ts +84 -0
  11. package/dist/engine.d.ts.map +1 -0
  12. package/dist/engine.js +60 -0
  13. package/dist/engine.js.map +1 -0
  14. package/dist/engines/chrome-builtin.d.ts +33 -0
  15. package/dist/engines/chrome-builtin.d.ts.map +1 -0
  16. package/dist/engines/chrome-builtin.js +240 -0
  17. package/dist/engines/chrome-builtin.js.map +1 -0
  18. package/dist/engines/stub.d.ts +32 -0
  19. package/dist/engines/stub.d.ts.map +1 -0
  20. package/dist/engines/stub.js +81 -0
  21. package/dist/engines/stub.js.map +1 -0
  22. package/dist/index.d.ts +11 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +12 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/probe.d.ts +65 -0
  27. package/dist/probe.d.ts.map +1 -0
  28. package/dist/probe.js +89 -0
  29. package/dist/probe.js.map +1 -0
  30. package/dist/ticket.d.ts +116 -0
  31. package/dist/ticket.d.ts.map +1 -0
  32. package/dist/ticket.js +261 -0
  33. package/dist/ticket.js.map +1 -0
  34. package/dist/validate.d.ts +30 -0
  35. package/dist/validate.d.ts.map +1 -0
  36. package/dist/validate.js +134 -0
  37. package/dist/validate.js.map +1 -0
  38. package/dist/walker.d.ts +137 -0
  39. package/dist/walker.d.ts.map +1 -0
  40. package/dist/walker.js +360 -0
  41. package/dist/walker.js.map +1 -0
  42. package/dist/weights.d.ts +16 -0
  43. package/dist/weights.d.ts.map +1 -0
  44. package/dist/weights.js +18 -0
  45. package/dist/weights.js.map +1 -0
  46. package/package.json +34 -4
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Routing tickets: what the issuing server lets one device try, in order, for one task on one record.
3
+ *
4
+ * A ticket carries no record content. It names the fields the device may read, the steps of the chain, and two
5
+ * hashes: one over the field list, one over the chain. The server computes both with the functions below when it
6
+ * issues the ticket (and stores them), and recomputes them when a result comes back. The device recomputes them before
7
+ * it walks the chain and refuses a ticket whose hashes do not match: a ticket altered on the way (an extra step, a
8
+ * lowered confidence floor, another field) is never walked.
9
+ *
10
+ * The server's signature is the authority. The device can check it too when the host hands it a verifier (a public
11
+ * key), but the server never trusts the device to have done so: it checks the ticket again on every result.
12
+ */
13
+ import { type EngineClass, type Shell } from './constants.js';
14
+ /** A file a step must load, pinned by size and hash (empty for built-in and hosted steps). */
15
+ export interface TicketFile {
16
+ readonly name: string;
17
+ /** Lower-case hex SHA-256 of the file's bytes. */
18
+ readonly sha256: string;
19
+ readonly bytes: number;
20
+ }
21
+ /** One step of a chain, as a ticket lists it. */
22
+ export interface ChainStep {
23
+ readonly position: number;
24
+ readonly engineClass: EngineClass;
25
+ /** A catalogue model key or a built-in engine's id. Empty for a hosted step. */
26
+ readonly modelKey: string;
27
+ readonly timeoutMs: number;
28
+ /** 0 means the step needs no confidence score. */
29
+ readonly minConfidence: number;
30
+ /** 0 means the step may not download anything. */
31
+ readonly maxDownloadMb: number;
32
+ /** The step can run with no network. */
33
+ readonly offlineOk: boolean;
34
+ readonly files: readonly TicketFile[];
35
+ }
36
+ /** The ticket without its hashes and signature: what the server builds before sealing. */
37
+ export interface TicketBody {
38
+ readonly ticketId: string;
39
+ readonly tenantId: string;
40
+ readonly person: string;
41
+ readonly task: string;
42
+ readonly record: {
43
+ readonly table: string;
44
+ readonly id: string;
45
+ };
46
+ /** The fields the device may read, already filtered by the person's rights and the task's local ceiling. */
47
+ readonly fields: readonly string[];
48
+ readonly steps: readonly ChainStep[];
49
+ readonly policyVersion: number;
50
+ /** ISO 8601. */
51
+ readonly expiresAt: string;
52
+ /** The administrator chose "local only" (with the acknowledgement): the chain has no hosted end. */
53
+ readonly localOnly?: boolean;
54
+ }
55
+ /** A sealed ticket: the body plus the two hashes, and the server's signature when it signs. */
56
+ export interface RoutingTicket extends TicketBody {
57
+ readonly fieldListHash: string;
58
+ readonly chainHash: string;
59
+ /** Base64url signature over {@link ticketSigningPayload}. */
60
+ readonly signature?: string;
61
+ }
62
+ /** Why a ticket was refused. Nothing in a refused ticket runs. */
63
+ export declare const TICKET_REFUSAL_CODES: readonly ["malformed", "expired", "field_list_hash_mismatch", "chain_hash_mismatch", "no_hosted_end", "hosted_not_last", "engine_not_allowed_on_shell", "signature_missing", "signature_invalid"];
64
+ export type TicketRefusalCode = (typeof TICKET_REFUSAL_CODES)[number];
65
+ export type TicketCheck = {
66
+ readonly ok: true;
67
+ } | {
68
+ readonly ok: false;
69
+ readonly code: TicketRefusalCode;
70
+ readonly message: string;
71
+ };
72
+ /** Checks a signature over the canonical payload. A host builds one from its public key. */
73
+ export type TicketSignatureVerifier = (payload: Uint8Array, signature: string) => Promise<boolean>;
74
+ export interface TicketCheckOptions {
75
+ /** Where the chain will run; engines that shell may never use refuse the ticket. */
76
+ readonly shell: Shell;
77
+ /** Milliseconds since the epoch, or a date. Defaults to `Date.now()`. */
78
+ readonly now?: number | Date;
79
+ readonly verifySignature?: TicketSignatureVerifier;
80
+ /** Refuse a ticket that has no signature (or when no verifier was given). Default false. */
81
+ readonly requireSignature?: boolean;
82
+ }
83
+ /**
84
+ * Hash of the field list: sorted, de-duplicated, canonical JSON, SHA-256. Order and repeats do not change it;
85
+ * adding or removing a field does.
86
+ */
87
+ export declare function hashFieldList(fields: readonly string[]): Promise<string>;
88
+ /**
89
+ * Hash of the chain: every step (ordered by position, files ordered by name) and the local-only flag. Any change to
90
+ * an engine, a model, a timeout, a floor, a download limit or a file hash changes it.
91
+ */
92
+ export declare function hashChain(steps: readonly ChainStep[], localOnly?: boolean): Promise<string>;
93
+ /** Server helper: add both hashes to a ticket body. The server signs the result, then stores the hashes. */
94
+ export declare function sealTicket(body: TicketBody): Promise<RoutingTicket>;
95
+ /** The bytes a server signs and a device verifies: canonical JSON of the sealed ticket without its signature. */
96
+ export declare function ticketSigningPayload(ticket: RoutingTicket | Omit<RoutingTicket, 'signature'>): Uint8Array;
97
+ /**
98
+ * A verifier over WebCrypto for a public key the host already holds (Ed25519 or ECDSA P-256 are the usual choices).
99
+ * The signature is base64url. A malformed signature verifies false; it never throws.
100
+ */
101
+ export declare function createWebCryptoTicketVerifier(key: CryptoKey, algorithm?: AlgorithmIdentifier | EcdsaParams): TicketSignatureVerifier;
102
+ /**
103
+ * Structural rules for a chain, shared by the server (when an administrator saves a task) and the device:
104
+ * positions strictly increasing, known engine classes, hosted steps only at the end, at least one hosted step unless
105
+ * the chain is local only (then none), and no engine the shell may never use.
106
+ */
107
+ export declare function checkChain(steps: readonly ChainStep[], opts?: {
108
+ readonly localOnly?: boolean;
109
+ readonly shell?: Shell;
110
+ }): TicketCheck;
111
+ /**
112
+ * Everything a device checks before it walks a ticket: shape, expiry, the field-list hash, the chain hash, the chain
113
+ * rules, and the signature when a verifier is given. Never throws for bad input; answers with a refusal code.
114
+ */
115
+ export declare function verifyTicket(ticket: unknown, opts: TicketCheckOptions): Promise<TicketCheck>;
116
+ //# sourceMappingURL=ticket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ticket.d.ts","sourceRoot":"","sources":["../src/ticket.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;GAWG;AAGH,OAAO,EAIL,KAAK,WAAW,EAChB,KAAK,KAAK,EACX,MAAM,gBAAgB,CAAC;AAExB,8FAA8F;AAC9F,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,kDAAkD;IAClD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,EAAE,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E;AAED,iHAAiH;AACjH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,aAAa,GAAG,IAAI,CAAC,aAAa,EAAE,WAAW,CAAC,GACvD,UAAU,CAGZ;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,GAAG,EAAE,SAAS,EACd,SAAS,GAAE,mBAAmB,GAAG,WAAiC,GACjE,uBAAuB,CAazB;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CACxB,KAAK,EAAE,SAAS,SAAS,EAAE,EAC3B,IAAI,GAAE;IAAE,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,CAAA;CAAO,GAClE,WAAW,CAuCb;AAED;;;GAGG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,OAAO,EACf,IAAI,EAAE,kBAAkB,GACvB,OAAO,CAAC,WAAW,CAAC,CAiDtB"}
package/dist/ticket.js ADDED
@@ -0,0 +1,261 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * Routing tickets: what the issuing server lets one device try, in order, for one task on one record.
4
+ *
5
+ * A ticket carries no record content. It names the fields the device may read, the steps of the chain, and two
6
+ * hashes: one over the field list, one over the chain. The server computes both with the functions below when it
7
+ * issues the ticket (and stores them), and recomputes them when a result comes back. The device recomputes them before
8
+ * it walks the chain and refuses a ticket whose hashes do not match: a ticket altered on the way (an extra step, a
9
+ * lowered confidence floor, another field) is never walked.
10
+ *
11
+ * The server's signature is the authority. The device can check it too when the host hands it a verifier (a public
12
+ * key), but the server never trusts the device to have done so: it checks the ticket again on every result.
13
+ */
14
+ import { base64UrlDecode, canonicalJson, sha256Hex } from './canonical.js';
15
+ import { ENGINE_CLASSES, ENGINES_NEVER_ON_SHELL, HOSTED_ENGINE_CLASSES, } from './constants.js';
16
+ /** Why a ticket was refused. Nothing in a refused ticket runs. */
17
+ export const TICKET_REFUSAL_CODES = [
18
+ 'malformed',
19
+ 'expired',
20
+ 'field_list_hash_mismatch',
21
+ 'chain_hash_mismatch',
22
+ 'no_hosted_end',
23
+ 'hosted_not_last',
24
+ 'engine_not_allowed_on_shell',
25
+ 'signature_missing',
26
+ 'signature_invalid',
27
+ ];
28
+ /**
29
+ * Hash of the field list: sorted, de-duplicated, canonical JSON, SHA-256. Order and repeats do not change it;
30
+ * adding or removing a field does.
31
+ */
32
+ export async function hashFieldList(fields) {
33
+ const sorted = [...new Set(fields)].sort();
34
+ return sha256Hex(canonicalJson(sorted));
35
+ }
36
+ /**
37
+ * Hash of the chain: every step (ordered by position, files ordered by name) and the local-only flag. Any change to
38
+ * an engine, a model, a timeout, a floor, a download limit or a file hash changes it.
39
+ */
40
+ export async function hashChain(steps, localOnly = false) {
41
+ return sha256Hex(canonicalJson(chainHashInput(steps, localOnly)));
42
+ }
43
+ function chainHashInput(steps, localOnly) {
44
+ return {
45
+ localOnly,
46
+ steps: [...steps]
47
+ .sort((a, b) => a.position - b.position)
48
+ .map((s) => ({
49
+ position: s.position,
50
+ engineClass: s.engineClass,
51
+ modelKey: s.modelKey,
52
+ timeoutMs: s.timeoutMs,
53
+ minConfidence: s.minConfidence,
54
+ maxDownloadMb: s.maxDownloadMb,
55
+ offlineOk: s.offlineOk,
56
+ files: [...s.files]
57
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
58
+ .map((f) => ({ name: f.name, sha256: f.sha256.toLowerCase(), bytes: f.bytes })),
59
+ })),
60
+ };
61
+ }
62
+ /** Server helper: add both hashes to a ticket body. The server signs the result, then stores the hashes. */
63
+ export async function sealTicket(body) {
64
+ const [fieldListHash, chainHash] = await Promise.all([
65
+ hashFieldList(body.fields),
66
+ hashChain(body.steps, body.localOnly === true),
67
+ ]);
68
+ return { ...body, fieldListHash, chainHash };
69
+ }
70
+ /** The bytes a server signs and a device verifies: canonical JSON of the sealed ticket without its signature. */
71
+ export function ticketSigningPayload(ticket) {
72
+ const { signature: _ignored, ...rest } = ticket;
73
+ return new TextEncoder().encode(canonicalJson(rest));
74
+ }
75
+ /**
76
+ * A verifier over WebCrypto for a public key the host already holds (Ed25519 or ECDSA P-256 are the usual choices).
77
+ * The signature is base64url. A malformed signature verifies false; it never throws.
78
+ */
79
+ export function createWebCryptoTicketVerifier(key, algorithm = { name: 'Ed25519' }) {
80
+ return async (payload, signature) => {
81
+ try {
82
+ const subtle = globalThis.crypto?.subtle;
83
+ if (!subtle)
84
+ return false;
85
+ const sig = base64UrlDecode(signature);
86
+ const data = new Uint8Array(new ArrayBuffer(payload.byteLength));
87
+ data.set(payload);
88
+ return await subtle.verify(algorithm, key, sig, data);
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ };
94
+ }
95
+ /**
96
+ * Structural rules for a chain, shared by the server (when an administrator saves a task) and the device:
97
+ * positions strictly increasing, known engine classes, hosted steps only at the end, at least one hosted step unless
98
+ * the chain is local only (then none), and no engine the shell may never use.
99
+ */
100
+ export function checkChain(steps, opts = {}) {
101
+ if (steps.length === 0)
102
+ return refuse('malformed', 'The chain has no steps.');
103
+ let last = -Infinity;
104
+ let hostedSeen = false;
105
+ let hostedCount = 0;
106
+ for (const s of steps) {
107
+ if (!KNOWN_CLASSES.has(s.engineClass)) {
108
+ return refuse('malformed', `Step ${String(s.position)} names an unknown engine class.`);
109
+ }
110
+ if (!(s.position > last)) {
111
+ return refuse('malformed', 'Step positions must be listed in strictly increasing order.');
112
+ }
113
+ last = s.position;
114
+ const hosted = HOSTED_ENGINE_CLASSES.has(s.engineClass);
115
+ if (hosted) {
116
+ hostedSeen = true;
117
+ hostedCount++;
118
+ }
119
+ else if (hostedSeen) {
120
+ return refuse('hosted_not_last', `Local step ${String(s.position)} comes after a hosted step.`);
121
+ }
122
+ if (opts.shell && ENGINES_NEVER_ON_SHELL[opts.shell].has(s.engineClass)) {
123
+ return refuse('engine_not_allowed_on_shell', `A ${opts.shell} shell may never use the ${s.engineClass} engine.`);
124
+ }
125
+ }
126
+ if (opts.localOnly === true) {
127
+ if (hostedCount > 0)
128
+ return refuse('malformed', 'A local-only chain has no hosted step.');
129
+ }
130
+ else if (hostedCount === 0) {
131
+ return refuse('no_hosted_end', 'The chain does not end at a hosted step and was not set local only.');
132
+ }
133
+ return { ok: true };
134
+ }
135
+ /**
136
+ * Everything a device checks before it walks a ticket: shape, expiry, the field-list hash, the chain hash, the chain
137
+ * rules, and the signature when a verifier is given. Never throws for bad input; answers with a refusal code.
138
+ */
139
+ export async function verifyTicket(ticket, opts) {
140
+ const shape = checkShape(ticket);
141
+ if (!shape.ok)
142
+ return shape;
143
+ const t = ticket;
144
+ const expires = Date.parse(t.expiresAt);
145
+ if (Number.isNaN(expires))
146
+ return refuse('malformed', 'The ticket expiry is not a date.');
147
+ const now = opts.now === undefined
148
+ ? Date.now()
149
+ : typeof opts.now === 'number'
150
+ ? opts.now
151
+ : opts.now.getTime();
152
+ if (now >= expires)
153
+ return refuse('expired', 'The ticket has expired.');
154
+ let fieldListHash;
155
+ let chainHash;
156
+ try {
157
+ [fieldListHash, chainHash] = await Promise.all([
158
+ hashFieldList(t.fields),
159
+ hashChain(t.steps, t.localOnly === true),
160
+ ]);
161
+ }
162
+ catch {
163
+ return refuse('malformed', 'The ticket cannot be hashed.');
164
+ }
165
+ if (fieldListHash !== t.fieldListHash.toLowerCase()) {
166
+ return refuse('field_list_hash_mismatch', 'The field list does not match its hash.');
167
+ }
168
+ if (chainHash !== t.chainHash.toLowerCase()) {
169
+ return refuse('chain_hash_mismatch', 'The chain does not match its hash.');
170
+ }
171
+ const chain = checkChain(t.steps, { localOnly: t.localOnly === true, shell: opts.shell });
172
+ if (!chain.ok)
173
+ return chain;
174
+ if (t.signature === undefined || t.signature === '') {
175
+ if (opts.requireSignature)
176
+ return refuse('signature_missing', 'The ticket is not signed.');
177
+ }
178
+ else if (opts.verifySignature) {
179
+ let valid = false;
180
+ try {
181
+ valid = await opts.verifySignature(ticketSigningPayload(t), t.signature);
182
+ }
183
+ catch {
184
+ valid = false;
185
+ }
186
+ if (!valid)
187
+ return refuse('signature_invalid', 'The ticket signature does not verify.');
188
+ }
189
+ else if (opts.requireSignature) {
190
+ return refuse('signature_missing', 'No key was given to check the ticket signature.');
191
+ }
192
+ return { ok: true };
193
+ }
194
+ const KNOWN_CLASSES = new Set(ENGINE_CLASSES);
195
+ function refuse(code, message) {
196
+ return { ok: false, code, message };
197
+ }
198
+ function isRecord(v) {
199
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
200
+ }
201
+ const isString = (v) => typeof v === 'string';
202
+ const isNumber = (v) => typeof v === 'number' && Number.isFinite(v);
203
+ function checkShape(v) {
204
+ const bad = (what) => refuse('malformed', `The ticket is malformed: ${what}.`);
205
+ if (!isRecord(v))
206
+ return bad('not an object');
207
+ for (const k of [
208
+ 'ticketId',
209
+ 'tenantId',
210
+ 'person',
211
+ 'task',
212
+ 'expiresAt',
213
+ 'fieldListHash',
214
+ 'chainHash',
215
+ ]) {
216
+ if (!isString(v[k]) || v[k] === '')
217
+ return bad(k);
218
+ }
219
+ if (!isNumber(v['policyVersion']))
220
+ return bad('policyVersion');
221
+ const record = v['record'];
222
+ if (!isRecord(record) || !isString(record['table']) || !isString(record['id']))
223
+ return bad('record');
224
+ const fields = v['fields'];
225
+ if (!Array.isArray(fields) || !fields.every(isString))
226
+ return bad('fields');
227
+ if (v['localOnly'] !== undefined && typeof v['localOnly'] !== 'boolean')
228
+ return bad('localOnly');
229
+ if (v['signature'] !== undefined && !isString(v['signature']))
230
+ return bad('signature');
231
+ const steps = v['steps'];
232
+ if (!Array.isArray(steps) || steps.length === 0)
233
+ return bad('steps');
234
+ for (const s of steps) {
235
+ if (!isRecord(s))
236
+ return bad('step');
237
+ if (!isNumber(s['position']) || !isString(s['engineClass']) || !isString(s['modelKey']))
238
+ return bad('step');
239
+ if (!KNOWN_CLASSES.has(s['engineClass']))
240
+ return bad(`unknown engine class ${s['engineClass']}`);
241
+ if (!isNumber(s['timeoutMs']) || s['timeoutMs'] <= 0)
242
+ return bad('step timeout');
243
+ if (!isNumber(s['minConfidence']) || s['minConfidence'] < 0 || s['minConfidence'] > 1)
244
+ return bad('step confidence floor');
245
+ if (!isNumber(s['maxDownloadMb']) || s['maxDownloadMb'] < 0)
246
+ return bad('step download limit');
247
+ if (typeof s['offlineOk'] !== 'boolean')
248
+ return bad('step offline flag');
249
+ const files = s['files'];
250
+ if (!Array.isArray(files))
251
+ return bad('step files');
252
+ for (const f of files) {
253
+ if (!isRecord(f) || !isString(f['name']) || !isString(f['sha256']) || !isNumber(f['bytes']))
254
+ return bad('step file');
255
+ if (!/^[0-9a-fA-F]{64}$/.test(f['sha256']))
256
+ return bad('step file hash');
257
+ }
258
+ }
259
+ return { ok: true };
260
+ }
261
+ //# sourceMappingURL=ticket.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ticket.js","sourceRoot":"","sources":["../src/ticket.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,qBAAqB,GAGtB,MAAM,gBAAgB,CAAC;AAmDxB,kEAAkE;AAClE,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,WAAW;IACX,SAAS;IACT,0BAA0B;IAC1B,qBAAqB;IACrB,eAAe;IACf,iBAAiB;IACjB,6BAA6B;IAC7B,mBAAmB;IACnB,mBAAmB;CACX,CAAC;AAoBX;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,MAAyB;IAC3D,MAAM,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3C,OAAO,SAAS,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;AAC1C,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,KAA2B,EAAE,SAAS,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C,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;gBACzF,OAAO,GAAG,CAAC,WAAW,CAAC,CAAC;YAC1B,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;gBAAE,OAAO,GAAG,CAAC,gBAAgB,CAAC,CAAC;QAC3E,CAAC;IACH,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;AACtB,CAAC"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Output checks per task. A local engine's output is checked like text a person typed: shape, length and, where a
3
+ * task has choices, membership. A failed check is a `schema_violation` and the walker moves on.
4
+ */
5
+ import type { EngineInput } from './engine.js';
6
+ export type ValidationResult = {
7
+ readonly ok: true;
8
+ readonly output: unknown;
9
+ } | {
10
+ readonly ok: false;
11
+ readonly problem: string;
12
+ };
13
+ export interface ValidationContext {
14
+ readonly input: EngineInput;
15
+ readonly maxOutputChars: number;
16
+ }
17
+ /** A host-supplied check for a task this package does not know. */
18
+ export type OutputValidator = (output: unknown, ctx: ValidationContext) => ValidationResult;
19
+ /**
20
+ * Check (and normalise) one output. Known tasks:
21
+ * - `text.language` → `{ language }`, a BCP 47 tag;
22
+ * - `text.summary.short` → `{ text }`, at most {@link SHORT_SUMMARY_MAX_WORDS} words;
23
+ * - `field.suggest` → `{ field, value, confidence? }`, the field asked for and a value from the choices;
24
+ * - `record.classify` → `{ label }` from the choices;
25
+ * - `pii.detect` → `{ spans: [{ start, end, kind }] }` inside the input text;
26
+ * - `text.translate`, `speech.text` → `{ text }`.
27
+ * Every text is capped at `maxOutputChars`. An unknown task needs a validator from the host.
28
+ */
29
+ export declare function validateTaskOutput(task: string, output: unknown, ctx: ValidationContext, custom?: Readonly<Record<string, OutputValidator>>): ValidationResult;
30
+ //# sourceMappingURL=validate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.d.ts","sourceRoot":"","sources":["../src/validate.ts"],"names":[],"mappings":"AACA;;;GAGG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,MAAM,MAAM,gBAAgB,GACxB;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAA;CAAE,GAC/C;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAErD,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,KAAK,EAAE,WAAW,CAAC;IAC5B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;CACjC;AAED,mEAAmE;AACnE,MAAM,MAAM,eAAe,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB,KAAK,gBAAgB,CAAC;AAE5F;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,OAAO,EACf,GAAG,EAAE,iBAAiB,EACtB,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC,GACjD,gBAAgB,CAOlB"}
@@ -0,0 +1,134 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * Output checks per task. A local engine's output is checked like text a person typed: shape, length and, where a
4
+ * task has choices, membership. A failed check is a `schema_violation` and the walker moves on.
5
+ */
6
+ import { SHORT_SUMMARY_MAX_WORDS } from './constants.js';
7
+ /**
8
+ * Check (and normalise) one output. Known tasks:
9
+ * - `text.language` → `{ language }`, a BCP 47 tag;
10
+ * - `text.summary.short` → `{ text }`, at most {@link SHORT_SUMMARY_MAX_WORDS} words;
11
+ * - `field.suggest` → `{ field, value, confidence? }`, the field asked for and a value from the choices;
12
+ * - `record.classify` → `{ label }` from the choices;
13
+ * - `pii.detect` → `{ spans: [{ start, end, kind }] }` inside the input text;
14
+ * - `text.translate`, `speech.text` → `{ text }`.
15
+ * Every text is capped at `maxOutputChars`. An unknown task needs a validator from the host.
16
+ */
17
+ export function validateTaskOutput(task, output, ctx, custom) {
18
+ const own = custom && Object.prototype.hasOwnProperty.call(custom, task) ? custom[task] : undefined;
19
+ if (own)
20
+ return own(output, ctx);
21
+ const builtIn = Object.prototype.hasOwnProperty.call(BUILT_IN, task) ? BUILT_IN[task] : undefined;
22
+ if (!builtIn)
23
+ return fail(`No output check is known for the task ${task}.`);
24
+ return builtIn(output, ctx);
25
+ }
26
+ const LANGUAGE_TAG = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
27
+ function fail(problem) {
28
+ return { ok: false, problem };
29
+ }
30
+ function asRecord(v) {
31
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
32
+ ? v
33
+ : undefined;
34
+ }
35
+ function cappedText(v, ctx, what) {
36
+ if (typeof v !== 'string')
37
+ return fail(`${what} is not text.`);
38
+ const text = v.trim();
39
+ if (text === '')
40
+ return fail(`${what} is empty.`);
41
+ if (text.length > ctx.maxOutputChars)
42
+ return fail(`${what} is longer than ${String(ctx.maxOutputChars)} characters.`);
43
+ return text;
44
+ }
45
+ function textTask(output, ctx) {
46
+ const o = asRecord(output);
47
+ if (!o)
48
+ return fail('The output is not an object.');
49
+ const text = cappedText(o['text'], ctx, 'The text');
50
+ return typeof text === 'string' ? { ok: true, output: { text } } : text;
51
+ }
52
+ function confidenceOk(v) {
53
+ return v === undefined || (typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1);
54
+ }
55
+ const BUILT_IN = {
56
+ 'text.language': (output) => {
57
+ const o = asRecord(output);
58
+ const language = o?.['language'];
59
+ if (typeof language !== 'string' || !LANGUAGE_TAG.test(language))
60
+ return fail('The language is not a language tag.');
61
+ return { ok: true, output: { language } };
62
+ },
63
+ 'text.summary.short': (output, ctx) => {
64
+ const r = textTask(output, ctx);
65
+ if (!r.ok)
66
+ return r;
67
+ const text = r.output.text;
68
+ const words = text.split(/\s+/).filter(Boolean).length;
69
+ if (words > SHORT_SUMMARY_MAX_WORDS)
70
+ return fail(`The summary is longer than ${String(SHORT_SUMMARY_MAX_WORDS)} words.`);
71
+ return r;
72
+ },
73
+ 'field.suggest': (output, ctx) => {
74
+ const o = asRecord(output);
75
+ if (!o)
76
+ return fail('The output is not an object.');
77
+ const { field, choices } = ctx.input;
78
+ if (typeof field !== 'string' || o['field'] !== field)
79
+ return fail('The suggestion is for another field.');
80
+ const value = o['value'];
81
+ if (typeof value !== 'string')
82
+ return fail('The suggested value is not text.');
83
+ if (choices && !choices.includes(value))
84
+ return fail("The suggested value is not one of the field's choices.");
85
+ if (value.length > ctx.maxOutputChars)
86
+ return fail('The suggested value is too long.');
87
+ if (!confidenceOk(o['confidence']))
88
+ return fail('The confidence is not between 0 and 1.');
89
+ const out = { field, value };
90
+ if (typeof o['confidence'] === 'number')
91
+ out.confidence = o['confidence'];
92
+ return { ok: true, output: out };
93
+ },
94
+ 'record.classify': (output, ctx) => {
95
+ const o = asRecord(output);
96
+ const label = o?.['label'];
97
+ const choices = ctx.input.choices;
98
+ if (!choices || choices.length === 0)
99
+ return fail('No labels were given to classify into.');
100
+ if (typeof label !== 'string' || !choices.includes(label))
101
+ return fail('The label is not one of the given labels.');
102
+ return { ok: true, output: { label } };
103
+ },
104
+ 'pii.detect': (output, ctx) => {
105
+ const o = asRecord(output);
106
+ const spans = o?.['spans'];
107
+ if (!Array.isArray(spans))
108
+ return fail('The spans are not a list.');
109
+ const length = ctx.input.text?.length ?? 0;
110
+ const out = [];
111
+ for (const span of spans) {
112
+ const s = asRecord(span);
113
+ const start = s?.['start'];
114
+ const end = s?.['end'];
115
+ const kind = s?.['kind'];
116
+ if (!Number.isInteger(start) ||
117
+ !Number.isInteger(end) ||
118
+ typeof kind !== 'string' ||
119
+ kind === '') {
120
+ return fail('A span is not {start, end, kind}.');
121
+ }
122
+ if (start < 0 ||
123
+ end <= start ||
124
+ end > length) {
125
+ return fail('A span lies outside the input.');
126
+ }
127
+ out.push({ start: start, end: end, kind });
128
+ }
129
+ return { ok: true, output: { spans: out } };
130
+ },
131
+ 'text.translate': textTask,
132
+ 'speech.text': textTask,
133
+ };
134
+ //# sourceMappingURL=validate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.js","sourceRoot":"","sources":["../src/validate.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B;;;GAGG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAezD;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAChC,IAAY,EACZ,MAAe,EACf,GAAsB,EACtB,MAAkD;IAElD,MAAM,GAAG,GACP,MAAM,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC1F,IAAI,GAAG;QAAE,OAAO,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACjC,MAAM,OAAO,GAAG,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAClG,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC,yCAAyC,IAAI,GAAG,CAAC,CAAC;IAC5E,OAAO,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAC9B,CAAC;AAED,MAAM,YAAY,GAAG,oCAAoC,CAAC;AAE1D,SAAS,IAAI,CAAC,OAAe;IAC3B,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AACh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