@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,137 @@
1
+ /**
2
+ * The chain walker: try each local step of a verified ticket in order, skip or fail with one reason per step, and
3
+ * stop at the first local success or at the hosted end of the chain.
4
+ *
5
+ * The walker never runs a hosted step. It hands the hosted end back to the caller, who makes the normal hosted call
6
+ * carrying the ticket id, so the server knows why the device fell back (and applies its own prompt gate to that call,
7
+ * whatever the device did).
8
+ *
9
+ * The order of checks per local step:
10
+ * 1. an engine for the class that supports the task and model else `not_applicable`
11
+ * 2. offline: the step and the policy must both allow it else `offline`
12
+ * 3. battery below the floor and not charging → `device_policy_blocked`
13
+ * 4. availability (bounded by the step's timeout) `unavailable` / `timeout`
14
+ * 5. a download is needed: metered + unmetered-only → `device_policy_blocked`
15
+ * size unknown or over the step / budget → `over_budget`
16
+ * no yes from the person → `download_refused`
17
+ * (the person's answer is not timed; only the caller's signal ends it)
18
+ * 6. run (bounded by the step's timeout again) `timeout`, `out_of_memory`, ...
19
+ * 7. output check else `schema_violation`
20
+ * 8. confidence floor else `low_confidence`
21
+ */
22
+ import { type EngineClass, type FallbackReason } from './constants.js';
23
+ import { type EngineInput, type LocalEngine } from './engine.js';
24
+ import { type DevicePolicy, type DeviceState } from './probe.js';
25
+ import { type RoutingTicket, type TicketRefusalCode, type TicketSignatureVerifier } from './ticket.js';
26
+ import { type OutputValidator } from './validate.js';
27
+ /** One step tried (or skipped). Mirrors the host's attempt row; `attested` is always false from a web page. */
28
+ export interface Attempt {
29
+ readonly position: number;
30
+ readonly engineClass: EngineClass;
31
+ readonly modelKey: string;
32
+ /** `skipped`: never ran. `failed`: ran and was not usable. `ok`: the answer. `hosted`: handed to the caller. */
33
+ readonly outcome: 'ok' | 'skipped' | 'failed' | 'hosted';
34
+ readonly reason?: FallbackReason;
35
+ readonly detail?: string;
36
+ readonly latencyMs: number;
37
+ readonly confidence?: number;
38
+ readonly observedVersion?: string;
39
+ readonly weightsSha256?: string;
40
+ readonly attested: false;
41
+ }
42
+ export interface DownloadRequest {
43
+ readonly engineClass: EngineClass;
44
+ readonly modelKey: string;
45
+ readonly downloadMb: number;
46
+ }
47
+ export interface WalkOptions {
48
+ readonly ticket: RoutingTicket;
49
+ readonly engines: readonly LocalEngine[];
50
+ readonly input: EngineInput;
51
+ readonly device: DeviceState;
52
+ /** Defaults to {@link DEFAULT_DEVICE_POLICY} (no downloads). */
53
+ readonly policy?: DevicePolicy;
54
+ /** Ask the person before a download. Absent means every download is refused. */
55
+ readonly confirmDownload?: (req: DownloadRequest) => boolean | Promise<boolean>;
56
+ readonly verifySignature?: TicketSignatureVerifier;
57
+ readonly requireSignature?: boolean;
58
+ /** Longest input text a local engine may be handed. Longer input skips every local step (`not_applicable`). */
59
+ readonly maxInputChars?: number;
60
+ /** Default 4000. */
61
+ readonly maxOutputChars?: number;
62
+ /** Validators for tasks this package does not know, or to override one it does. */
63
+ readonly validators?: Readonly<Record<string, OutputValidator>>;
64
+ readonly onAttempt?: (attempt: Attempt) => void;
65
+ /** The caller gave up (the person left the page). */
66
+ readonly signal?: AbortSignal;
67
+ /** Milliseconds; defaults to `Date.now`. */
68
+ readonly now?: () => number;
69
+ }
70
+ export type WalkResult = {
71
+ readonly kind: 'local';
72
+ readonly ticketId: string;
73
+ readonly position: number;
74
+ readonly engineClass: EngineClass;
75
+ readonly modelKey: string;
76
+ readonly output: unknown;
77
+ readonly confidence?: number;
78
+ readonly attempts: readonly Attempt[];
79
+ } | {
80
+ readonly kind: 'hosted';
81
+ readonly ticketId: string;
82
+ readonly position: number;
83
+ readonly engineClass: EngineClass;
84
+ readonly attempts: readonly Attempt[];
85
+ } | {
86
+ /** A local-only chain where no step worked. */
87
+ readonly kind: 'exhausted';
88
+ readonly ticketId: string;
89
+ readonly message: string;
90
+ readonly attempts: readonly Attempt[];
91
+ } | {
92
+ /** The ticket failed its checks; nothing ran. */
93
+ readonly kind: 'refused';
94
+ readonly ticketId?: string;
95
+ readonly code: TicketRefusalCode;
96
+ readonly message: string;
97
+ readonly attempts: readonly Attempt[];
98
+ } | {
99
+ readonly kind: 'cancelled';
100
+ readonly ticketId: string;
101
+ readonly attempts: readonly Attempt[];
102
+ };
103
+ /** Walk a ticket's chain. Never throws for engine trouble; every failure is an attempt with a reason. */
104
+ export declare function walkChain(opts: WalkOptions): Promise<WalkResult>;
105
+ /** `engineClass:reason` for each step that did not answer, in order (the form the host's event log shows). */
106
+ export declare function fallbackSummary(attempts: readonly Attempt[]): string[];
107
+ /** What a device posts with a local answer. The server checks the ticket again and stores it as a suggestion. */
108
+ export interface LocalResultSubmission {
109
+ readonly ticketId: string;
110
+ readonly step: number;
111
+ readonly output: unknown;
112
+ readonly confidence?: number;
113
+ readonly provenance: {
114
+ readonly engineClass: EngineClass;
115
+ readonly modelKey: string;
116
+ readonly observedVersion?: string;
117
+ readonly weightsSha256?: string;
118
+ readonly attested: false;
119
+ };
120
+ readonly attempts: readonly Attempt[];
121
+ }
122
+ /** What a device attaches to the hosted call when it fell back. */
123
+ export interface HostedFallbackNote {
124
+ readonly ticketId: string;
125
+ readonly step: number;
126
+ readonly fallback: readonly string[];
127
+ readonly attempts: readonly Attempt[];
128
+ }
129
+ /** The local answer as the device posts it. Provenance is what the engine said; it is never attested from a page. */
130
+ export declare function toResultSubmission(result: Extract<WalkResult, {
131
+ kind: 'local';
132
+ }>): LocalResultSubmission;
133
+ /** The note a device attaches to the hosted call, so the server knows which step it reached and why. */
134
+ export declare function toHostedFallback(result: Extract<WalkResult, {
135
+ kind: 'hosted';
136
+ }>): HostedFallbackNote;
137
+ //# sourceMappingURL=walker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"walker.d.ts","sourceRoot":"","sources":["../src/walker.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAyB,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAC9F,OAAO,EAE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IACzB,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,UAAU,EAAE;QACnB,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC;QAClC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;QAC1B,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;QAClC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;QAChC,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC;KAC1B,CAAC;IACF,QAAQ,CAAC,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;CACvC;AAED,mEAAmE;AACnE,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,QAAQ,CAAC,QAAQ,EAAE,SAAS,OAAO,EAAE,CAAC;CACvC;AAED,qHAAqH;AACrH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,OAAO,CAAC,UAAU,EAAE;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC,GAC7C,qBAAqB,CAkBvB;AAED,wGAAwG;AACxG,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,OAAO,CAAC,UAAU,EAAE;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,CAAC,GAC9C,kBAAkB,CAOpB"}
package/dist/walker.js ADDED
@@ -0,0 +1,360 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * The chain walker: try each local step of a verified ticket in order, skip or fail with one reason per step, and
4
+ * stop at the first local success or at the hosted end of the chain.
5
+ *
6
+ * The walker never runs a hosted step. It hands the hosted end back to the caller, who makes the normal hosted call
7
+ * carrying the ticket id, so the server knows why the device fell back (and applies its own prompt gate to that call,
8
+ * whatever the device did).
9
+ *
10
+ * The order of checks per local step:
11
+ * 1. an engine for the class that supports the task and model else `not_applicable`
12
+ * 2. offline: the step and the policy must both allow it else `offline`
13
+ * 3. battery below the floor and not charging → `device_policy_blocked`
14
+ * 4. availability (bounded by the step's timeout) `unavailable` / `timeout`
15
+ * 5. a download is needed: metered + unmetered-only → `device_policy_blocked`
16
+ * size unknown or over the step / budget → `over_budget`
17
+ * no yes from the person → `download_refused`
18
+ * (the person's answer is not timed; only the caller's signal ends it)
19
+ * 6. run (bounded by the step's timeout again) `timeout`, `out_of_memory`, ...
20
+ * 7. output check else `schema_violation`
21
+ * 8. confidence floor else `low_confidence`
22
+ */
23
+ import { HOSTED_ENGINE_CLASSES } from './constants.js';
24
+ import { classifyEngineError, } from './engine.js';
25
+ import { DEFAULT_DEVICE_POLICY } from './probe.js';
26
+ import { verifyTicket, } from './ticket.js';
27
+ import { validateTaskOutput } from './validate.js';
28
+ /** Walk a ticket's chain. Never throws for engine trouble; every failure is an attempt with a reason. */
29
+ export async function walkChain(opts) {
30
+ const now = opts.now ?? Date.now;
31
+ const policy = opts.policy ?? DEFAULT_DEVICE_POLICY;
32
+ const maxOutputChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
33
+ const device = opts.device;
34
+ const raw = opts.ticket;
35
+ const rawId = typeof raw === 'object' && raw !== null ? raw.ticketId : undefined;
36
+ const check = await verifyTicket(raw, {
37
+ shell: device.shell,
38
+ now: now(),
39
+ ...(opts.verifySignature ? { verifySignature: opts.verifySignature } : {}),
40
+ ...(opts.requireSignature ? { requireSignature: true } : {}),
41
+ });
42
+ if (!check.ok) {
43
+ return {
44
+ kind: 'refused',
45
+ ...(typeof rawId === 'string' ? { ticketId: rawId } : {}),
46
+ code: check.code,
47
+ message: check.message,
48
+ attempts: [],
49
+ };
50
+ }
51
+ const ticket = opts.ticket;
52
+ const ticketId = ticket.ticketId;
53
+ const attempts = [];
54
+ const cancelled = () => ({ kind: 'cancelled', ticketId, attempts });
55
+ const input = limitInput(opts.input, ticket.fields);
56
+ const tooLong = opts.maxInputChars !== undefined && inputLength(input) > opts.maxInputChars;
57
+ for (const s of ticket.steps) {
58
+ if (opts.signal?.aborted)
59
+ return cancelled();
60
+ const started = now();
61
+ const record = (a) => {
62
+ const attempt = clean({
63
+ position: s.position,
64
+ engineClass: s.engineClass,
65
+ modelKey: s.modelKey,
66
+ latencyMs: Math.max(0, now() - started),
67
+ attested: false,
68
+ ...a,
69
+ });
70
+ attempts.push(attempt);
71
+ opts.onAttempt?.(attempt);
72
+ };
73
+ const skip = (reason, detail) => record({ outcome: 'skipped', reason, detail });
74
+ const fail = (reason, detail, extra = {}) => record({ outcome: 'failed', reason, detail, ...extra });
75
+ // The hosted end: hand it back. The walker never runs a hosted step, whatever engine claims the class.
76
+ if (HOSTED_ENGINE_CLASSES.has(s.engineClass)) {
77
+ record({ outcome: 'hosted' });
78
+ return {
79
+ kind: 'hosted',
80
+ ticketId,
81
+ position: s.position,
82
+ engineClass: s.engineClass,
83
+ attempts,
84
+ };
85
+ }
86
+ if (tooLong) {
87
+ skip('not_applicable', 'input_too_long');
88
+ continue;
89
+ }
90
+ const sameClass = opts.engines.filter((e) => e.engineClass === s.engineClass);
91
+ const engine = sameClass.find((e) => {
92
+ try {
93
+ return e.supports(ticket.task, s.modelKey);
94
+ }
95
+ catch {
96
+ return false;
97
+ }
98
+ });
99
+ if (!engine) {
100
+ skip('not_applicable', sameClass.length > 0 ? 'task_not_supported' : 'no_engine');
101
+ continue;
102
+ }
103
+ if (!device.online && !(s.offlineOk && policy.allowOffline)) {
104
+ skip('offline');
105
+ continue;
106
+ }
107
+ if (policy.minBatteryPct > 0 &&
108
+ typeof device.batteryPct === 'number' &&
109
+ device.batteryPct < policy.minBatteryPct &&
110
+ device.charging !== true) {
111
+ skip('device_policy_blocked', 'battery_low');
112
+ continue;
113
+ }
114
+ // Availability, bounded by the step's timeout. Never a download.
115
+ const checkScope = stepScope(s.timeoutMs, opts.signal);
116
+ let state;
117
+ let downloadMb;
118
+ try {
119
+ const a = await checkScope.bounded(engine.availability({
120
+ task: ticket.task,
121
+ modelKey: s.modelKey,
122
+ input,
123
+ signal: checkScope.signal,
124
+ }));
125
+ state = a.state;
126
+ downloadMb = a.downloadMb;
127
+ if (a.state === 'unavailable') {
128
+ skip('unavailable', a.detail);
129
+ continue;
130
+ }
131
+ }
132
+ catch (err) {
133
+ if (opts.signal?.aborted)
134
+ return cancelled();
135
+ const r = classifyEngineError(err);
136
+ skip(r.reason, r.detail);
137
+ continue;
138
+ }
139
+ finally {
140
+ checkScope.dispose();
141
+ }
142
+ let allowDownload = false;
143
+ if (state === 'downloading') {
144
+ skip('unavailable', 'downloading');
145
+ continue;
146
+ }
147
+ if (state === 'downloadable') {
148
+ const gate = downloadGate(s, policy, device, downloadMb);
149
+ if (gate) {
150
+ skip(gate.reason, gate.detail);
151
+ continue;
152
+ }
153
+ let yes = false;
154
+ try {
155
+ yes = opts.confirmDownload
156
+ ? (await untilCancelled(Promise.resolve(opts.confirmDownload({
157
+ engineClass: s.engineClass,
158
+ modelKey: s.modelKey,
159
+ downloadMb: downloadMb ?? 0,
160
+ })), opts.signal)) === true
161
+ : false;
162
+ }
163
+ catch {
164
+ if (opts.signal?.aborted)
165
+ return cancelled();
166
+ yes = false;
167
+ }
168
+ if (!yes) {
169
+ skip('download_refused');
170
+ continue;
171
+ }
172
+ allowDownload = true;
173
+ }
174
+ else if (state !== 'available') {
175
+ skip('unavailable', 'unknown_state');
176
+ continue;
177
+ }
178
+ // Run, bounded by the step's timeout.
179
+ const runScope = stepScope(s.timeoutMs, opts.signal);
180
+ let result;
181
+ try {
182
+ result = await runScope.bounded(engine.run({
183
+ task: ticket.task,
184
+ modelKey: s.modelKey,
185
+ input,
186
+ signal: runScope.signal,
187
+ files: s.files,
188
+ maxOutputChars,
189
+ allowDownload,
190
+ }));
191
+ }
192
+ catch (err) {
193
+ if (opts.signal?.aborted)
194
+ return cancelled();
195
+ const r = classifyEngineError(err);
196
+ fail(r.reason, r.detail);
197
+ continue;
198
+ }
199
+ finally {
200
+ runScope.dispose();
201
+ }
202
+ const told = clean({
203
+ observedVersion: result.observedVersion,
204
+ weightsSha256: result.weightsSha256,
205
+ });
206
+ const checked = validateTaskOutput(ticket.task, result.output, { input, maxOutputChars }, opts.validators);
207
+ if (!checked.ok) {
208
+ fail('schema_violation', checked.problem, told);
209
+ continue;
210
+ }
211
+ const confidence = result.confidence;
212
+ if (confidence !== undefined &&
213
+ !(Number.isFinite(confidence) && confidence >= 0 && confidence <= 1)) {
214
+ fail('schema_violation', 'The confidence is not between 0 and 1.', told);
215
+ continue;
216
+ }
217
+ if (s.minConfidence > 0 && (confidence === undefined || confidence < s.minConfidence)) {
218
+ fail('low_confidence', confidence === undefined ? 'no_confidence' : undefined, {
219
+ ...told,
220
+ ...clean({ confidence }),
221
+ });
222
+ continue;
223
+ }
224
+ record({ outcome: 'ok', ...told, ...clean({ confidence }) });
225
+ return clean({
226
+ kind: 'local',
227
+ ticketId,
228
+ position: s.position,
229
+ engineClass: s.engineClass,
230
+ modelKey: s.modelKey,
231
+ output: checked.output,
232
+ confidence,
233
+ attempts,
234
+ });
235
+ }
236
+ // Only a local-only chain gets here: verification refuses any other chain without a hosted end.
237
+ return {
238
+ kind: 'exhausted',
239
+ ticketId,
240
+ message: 'No engine on this device could do this, and this task is set to local only, so nothing was sent to a hosted model.',
241
+ attempts,
242
+ };
243
+ }
244
+ const DEFAULT_MAX_OUTPUT_CHARS = 4000;
245
+ /** Keep only the fields the ticket lists. `text` is the host's assembly of those fields and passes as is. */
246
+ function limitInput(input, allowed) {
247
+ if (!input.fields)
248
+ return input;
249
+ const keep = new Set(allowed);
250
+ const fields = {};
251
+ for (const [k, v] of Object.entries(input.fields))
252
+ if (keep.has(k))
253
+ fields[k] = v;
254
+ return { ...input, fields };
255
+ }
256
+ function inputLength(input) {
257
+ let n = input.text?.length ?? 0;
258
+ for (const v of Object.values(input.fields ?? {}))
259
+ n += v.length;
260
+ return n;
261
+ }
262
+ function downloadGate(s, policy, device, downloadMb) {
263
+ if (policy.requireUnmetered && device.metered === true)
264
+ return { reason: 'device_policy_blocked', detail: 'metered' };
265
+ if (downloadMb === undefined || !Number.isFinite(downloadMb) || downloadMb < 0) {
266
+ return { reason: 'over_budget', detail: 'size_unknown' };
267
+ }
268
+ if (downloadMb > s.maxDownloadMb)
269
+ return { reason: 'over_budget', detail: 'over_step_limit' };
270
+ if (downloadMb > policy.downloadBudgetMb - (device.downloadedMb ?? 0)) {
271
+ return { reason: 'over_budget', detail: 'over_device_budget' };
272
+ }
273
+ return undefined;
274
+ }
275
+ /**
276
+ * An abort signal that fires at the step's timeout (reason `TimeoutError`) or when the caller gives up (reason
277
+ * `AbortError`), and a race against it. The rejection carries that reason, so it classifies as `timeout`.
278
+ */
279
+ function stepScope(timeoutMs, outer) {
280
+ const ctl = new AbortController();
281
+ const timer = setTimeout(() => {
282
+ ctl.abort(new DOMException('The step timed out.', 'TimeoutError'));
283
+ }, timeoutMs);
284
+ const onOuter = () => ctl.abort(new DOMException('The walk was cancelled.', 'AbortError'));
285
+ if (outer?.aborted)
286
+ onOuter();
287
+ else
288
+ outer?.addEventListener('abort', onOuter, { once: true });
289
+ return {
290
+ signal: ctl.signal,
291
+ bounded: (p) => untilCancelled(p, ctl.signal),
292
+ dispose: () => {
293
+ clearTimeout(timer);
294
+ outer?.removeEventListener('abort', onOuter);
295
+ },
296
+ };
297
+ }
298
+ function untilCancelled(p, signal) {
299
+ if (!signal)
300
+ return p;
301
+ return new Promise((resolve, reject) => {
302
+ if (signal.aborted) {
303
+ reject(signal.reason);
304
+ return;
305
+ }
306
+ const onAbort = () => reject(signal.reason);
307
+ signal.addEventListener('abort', onAbort, { once: true });
308
+ p.then((v) => {
309
+ signal.removeEventListener('abort', onAbort);
310
+ resolve(v);
311
+ }, (e) => {
312
+ signal.removeEventListener('abort', onAbort);
313
+ reject(e);
314
+ });
315
+ });
316
+ }
317
+ /** Drop keys whose value is undefined, so records and results carry only what is known. */
318
+ function clean(o) {
319
+ const out = {};
320
+ for (const [k, v] of Object.entries(o))
321
+ if (v !== undefined)
322
+ out[k] = v;
323
+ return out;
324
+ }
325
+ /** `engineClass:reason` for each step that did not answer, in order (the form the host's event log shows). */
326
+ export function fallbackSummary(attempts) {
327
+ return attempts
328
+ .filter((a) => a.outcome === 'skipped' || a.outcome === 'failed')
329
+ .map((a) => `${a.engineClass}:${a.reason ?? 'unavailable'}`);
330
+ }
331
+ /** The local answer as the device posts it. Provenance is what the engine said; it is never attested from a page. */
332
+ export function toResultSubmission(result) {
333
+ const ok = [...result.attempts]
334
+ .reverse()
335
+ .find((a) => a.outcome === 'ok' && a.position === result.position);
336
+ return clean({
337
+ ticketId: result.ticketId,
338
+ step: result.position,
339
+ output: result.output,
340
+ confidence: result.confidence,
341
+ provenance: clean({
342
+ engineClass: result.engineClass,
343
+ modelKey: result.modelKey,
344
+ observedVersion: ok?.observedVersion,
345
+ weightsSha256: ok?.weightsSha256,
346
+ attested: false,
347
+ }),
348
+ attempts: result.attempts,
349
+ });
350
+ }
351
+ /** The note a device attaches to the hosted call, so the server knows which step it reached and why. */
352
+ export function toHostedFallback(result) {
353
+ return {
354
+ ticketId: result.ticketId,
355
+ step: result.position,
356
+ fallback: fallbackSummary(result.attempts),
357
+ attempts: result.attempts,
358
+ };
359
+ }
360
+ //# sourceMappingURL=walker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"walker.js","sourceRoot":"","sources":["../src/walker.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,qBAAqB,EAAyC,MAAM,gBAAgB,CAAC;AAC9F,OAAO,EACL,mBAAmB,GAIpB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,qBAAqB,EAAuC,MAAM,YAAY,CAAC;AACxF,OAAO,EACL,YAAY,GAKb,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,kBAAkB,EAAwB,MAAM,eAAe,CAAC;AAuFzE,yGAAyG;A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,CAAC,CAAC,MAAM,IAAI,aAAa,EAAE,CAAC,CAAC;AACjE,CAAC;AA0BD,qHAAqH;AACrH,MAAM,UAAU,kBAAkB,CAChC,MAA8C;IAE9C,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC,QAAQ,CAAC;SAC5B,OAAO,EAAE;SACT,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,IAAI,IAAI,CAAC,CAAC,QAAQ,KAAK,MAAM,CAAC,QAAQ,CAAC,CAAC;IACrE,OAAO,KAAK,CAAC;QACX,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,IAAI,EAAE,MAAM,CAAC,QAAQ;QACrB,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,UAAU,EAAE,KAAK,CAAC;YAChB,WAAW,EAAE,MAAM,CAAC,WAAW;YAC/B,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,eAAe,EAAE,EAAE,EAAE,eAAe;YACpC,aAAa,EAAE,EAAE,EAAE,aAAa;YAChC,QAAQ,EAAE,KAAc;SACzB,CAAC;QACF,QAAQ,EAAE,MAAM,CAAC,QAAQ;KAC1B,CAAC,CAAC;AACL,CAAC;AAED,wGAAwG;AACxG,MAAM,UAAU,gBAAgB,CAC9B,MAA+C;IAE/C,OAAO;QACL,QAAQ,EAAE,MAAM,CAAC,QAAQ;QACzB,IAAI,EAAE,MAAM,CAAC,QAAQ;QACrB,QAAQ,EAAE,eAAe,CAAC,MAAM,CAAC,QAAQ,CAAC;QAC1C,QAAQ,EAAE,MAAM,CAAC,QAAQ;KAC1B,CAAC;AACJ,CAAC"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Pinned-file checks. A step that loads model files lists each file's size and SHA-256 in the ticket; an engine checks
3
+ * the bytes it fetched before it loads them. The check runs on the device by necessity, so the server records the hash
4
+ * a device reports but never trusts it.
5
+ */
6
+ import type { TicketFile } from './ticket.js';
7
+ export type FileCheck = {
8
+ readonly ok: true;
9
+ } | {
10
+ readonly ok: false;
11
+ readonly reason: 'size_mismatch' | 'hash_mismatch';
12
+ readonly name: string;
13
+ };
14
+ /** Compare bytes against a pinned file: size first, then SHA-256. */
15
+ export declare function verifyFileBytes(file: TicketFile, bytes: ArrayBuffer | ArrayBufferView): Promise<FileCheck>;
16
+ //# sourceMappingURL=weights.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"weights.d.ts","sourceRoot":"","sources":["../src/weights.ts"],"names":[],"mappings":"AACA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9C,MAAM,MAAM,SAAS,GACjB;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAA;CAAE,GACrB;IACE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IACnB,QAAQ,CAAC,MAAM,EAAE,eAAe,GAAG,eAAe,CAAC;IACnD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB,CAAC;AAEN,qEAAqE;AACrE,wBAAsB,eAAe,CACnC,IAAI,EAAE,UAAU,EAChB,KAAK,EAAE,WAAW,GAAG,eAAe,GACnC,OAAO,CAAC,SAAS,CAAC,CAOpB"}
@@ -0,0 +1,18 @@
1
+ // SPDX-License-Identifier: MIT
2
+ /**
3
+ * Pinned-file checks. A step that loads model files lists each file's size and SHA-256 in the ticket; an engine checks
4
+ * the bytes it fetched before it loads them. The check runs on the device by necessity, so the server records the hash
5
+ * a device reports but never trusts it.
6
+ */
7
+ import { sha256Hex } from './canonical.js';
8
+ /** Compare bytes against a pinned file: size first, then SHA-256. */
9
+ export async function verifyFileBytes(file, bytes) {
10
+ const length = bytes.byteLength;
11
+ if (length !== file.bytes)
12
+ return { ok: false, reason: 'size_mismatch', name: file.name };
13
+ const actual = await sha256Hex(bytes);
14
+ if (actual !== file.sha256.toLowerCase())
15
+ return { ok: false, reason: 'hash_mismatch', name: file.name };
16
+ return { ok: true };
17
+ }
18
+ //# sourceMappingURL=weights.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"weights.js","sourceRoot":"","sources":["../src/weights.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B;;;;GAIG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAW3C,qEAAqE;AACrE,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,IAAgB,EAChB,KAAoC;IAEpC,MAAM,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC;IAChC,IAAI,MAAM,KAAK,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC;IAC1F,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,KAAK,CAAC,CAAC;IACtC,IAAI,MAAM,KAAK,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;QACtC,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC;IACjE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;AACtB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@weaveintel/local-engines",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Browser-safe local model engines: the engine contract, a capability probe, a fallback chain walker that ends at a hosted step, routing-ticket hash checks, a deterministic stub engine and a feature-detected Chrome built-in AI adapter.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "import": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "sideEffects": false,
16
+ "scripts": {
17
+ "build": "tsc -b",
18
+ "typecheck": "tsc --noEmit",
19
+ "test": "vitest run",
20
+ "clean": "rm -rf dist"
21
+ },
22
+ "devDependencies": {
23
+ "typescript": "^5.7.0",
24
+ "vitest": "^3.2.6"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "!dist/**/*.test.*",
32
+ "!dist/**/*.spec.*",
33
+ "!dist/test-fixtures.*"
34
+ ],
35
+ "license": "MIT"
36
+ }