@swissspidy/belay-core 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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,48 @@
1
- # Temporary Holding Version
1
+ # @swissspidy/belay-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Answer AI tasks with a small on-device model, and call a cloud model only for the inputs it is
4
+ unsure about. `@swissspidy/belay-core` has the task, the cascade, confidence handling, calibration files,
5
+ cloud adapters and savings telemetry. It has no runtime dependencies.
6
+
7
+ Pair it with [`@swissspidy/belay-web`](https://www.npmjs.com/package/@swissspidy/belay-web) for the on-device runners
8
+ (Chrome's Classifier and Prompt APIs), and calibrate the threshold on your own data with
9
+ [`@swissspidy/belay-calibrate`](https://www.npmjs.com/package/@swissspidy/belay-calibrate).
10
+
11
+ > **Status:** experimental (0.x). The API may change between minor versions.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ npm install @swissspidy/belay-core @swissspidy/belay-web
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ```ts
22
+ import { task, fetchAdapter } from '@swissspidy/belay-core';
23
+ import { classifierApi } from '@swissspidy/belay-web';
24
+
25
+ const triage = task({
26
+ name: 'ticket-triage',
27
+ schema: { type: 'categorical', options: ['bug', 'billing', 'feature', 'other'] as const },
28
+ local: classifierApi(),
29
+ cloud: fetchAdapter({ url: '/api/belay' }), // your backend calls the LLM
30
+ threshold: 0.8, // or: calibration: '/belay.calibration.json'
31
+ });
32
+
33
+ const result = await triage.run(ticketText, { signal });
34
+ // { value: 'billing', confidence: 0.93, source: 'local', escalationReason: null, ... }
35
+ ```
36
+
37
+ The local answer is accepted if and only if `confidence >= threshold`. Otherwise the task
38
+ escalates to the cloud, subject to your privacy policy (`redact`, `consent`, or `never`).
39
+
40
+ ## Documentation
41
+
42
+ See the [project README](https://github.com/swissspidy/belay#readme) for schemas, confidence,
43
+ privacy, cloud adapters, calibration and telemetry, and the
44
+ [ADRs](https://github.com/swissspidy/belay/tree/main/docs/adr) for the design decisions.
45
+
46
+ ## License
47
+
48
+ Apache-2.0
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@swissspidy/belay-core",
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": "Confidence-based escalation from on-device to cloud AI: tasks, cascade logic, confidence, calibration types.",
5
+ "license": "Apache-2.0",
6
+ "author": "Pascal Birchler",
7
+ "homepage": "https://github.com/swissspidy/belay/tree/main/packages/core#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/swissspidy/belay.git",
11
+ "directory": "packages/core"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/swissspidy/belay/issues"
15
+ },
16
+ "keywords": [
17
+ "ai",
18
+ "on-device",
19
+ "cascade",
20
+ "llm",
21
+ "classification",
22
+ "calibration",
23
+ "confidence",
24
+ "escalation"
25
+ ],
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "src"
37
+ ],
38
+ "scripts": {
39
+ "build": "tsc -b"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ }
44
+ }
@@ -0,0 +1,65 @@
1
+ import { BelayError } from './errors.js';
2
+ import type { CalibrationFile } from './types.js';
3
+
4
+ export const CALIBRATION_VERSION = 1;
5
+
6
+ const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
7
+ const isProb = (v: unknown): v is number => isNum(v) && v >= 0 && v <= 1;
8
+ /** A threshold above 1 keeps nothing local: every run escalates. */
9
+ const isThreshold = (v: unknown): v is number => isNum(v) && v >= 0;
10
+
11
+ /**
12
+ * Validates an unknown value as a v1 calibration file. When `task` is given, also checks
13
+ * that the file belongs to that task. Throws `BelayError('invalid-calibration')`.
14
+ */
15
+ export function parseCalibration(data: unknown, task?: string): CalibrationFile {
16
+ const fail = (msg: string): never => {
17
+ throw new BelayError('invalid-calibration', `Invalid calibration file: ${msg}`);
18
+ };
19
+ if (!data || typeof data !== 'object') fail('not an object');
20
+ const c = data as Partial<CalibrationFile>;
21
+ if (c.version !== CALIBRATION_VERSION) fail(`unsupported version ${String(c.version)}`);
22
+ if (typeof c.task !== 'string') fail('missing task');
23
+ if (task !== undefined && c.task !== task) fail(`file is for task "${c.task}", not "${task}"`);
24
+ if (typeof c.schemaFingerprint !== 'string') fail('missing schemaFingerprint');
25
+ if (!isThreshold(c.threshold)) fail('threshold must be a number ≥ 0');
26
+ if (c.thresholds !== undefined) {
27
+ if (typeof c.thresholds !== 'object' || c.thresholds === null) fail('thresholds must be an object');
28
+ for (const [label, t] of Object.entries(c.thresholds as object)) {
29
+ if (!isThreshold(t)) fail(`thresholds["${label}"] must be a number ≥ 0`);
30
+ }
31
+ }
32
+ if (!c.expected || !isProb(c.expected.localShare) || !isProb(c.expected.accuracy)) {
33
+ fail('expected.accuracy and expected.localShare must be numbers in [0, 1]');
34
+ }
35
+ if (!Array.isArray(c.curve)) fail('curve must be an array');
36
+ if (!c.confidenceHistogram || !Array.isArray(c.confidenceHistogram.edges) || !Array.isArray(c.confidenceHistogram.counts)) {
37
+ fail('confidenceHistogram must have edges and counts');
38
+ } else if (c.confidenceHistogram.edges.length !== c.confidenceHistogram.counts.length + 1) {
39
+ fail('confidenceHistogram.edges must have one more entry than counts');
40
+ }
41
+ return c as CalibrationFile;
42
+ }
43
+
44
+ /** Threshold for a local top label: the per-label override if present, else the global one. */
45
+ export function thresholdFor(calibration: Pick<CalibrationFile, 'threshold' | 'thresholds'>, label?: string): number {
46
+ if (label !== undefined && calibration.thresholds && Object.hasOwn(calibration.thresholds, label)) {
47
+ return calibration.thresholds[label]!;
48
+ }
49
+ return calibration.threshold;
50
+ }
51
+
52
+ export async function loadCalibration(
53
+ source: CalibrationFile | string | URL | (() => Promise<CalibrationFile>),
54
+ task?: string,
55
+ ): Promise<CalibrationFile> {
56
+ if (typeof source === 'function') return parseCalibration(await source(), task);
57
+ if (typeof source === 'string' || source instanceof URL) {
58
+ const res = await fetch(source);
59
+ if (!res.ok) {
60
+ throw new BelayError('invalid-calibration', `Failed to fetch calibration ${String(source)}: HTTP ${res.status}`);
61
+ }
62
+ return parseCalibration(await res.json(), task);
63
+ }
64
+ return parseCalibration(source, task);
65
+ }
package/src/cloud.ts ADDED
@@ -0,0 +1,72 @@
1
+ import type { CloudOutput, CloudRequest, CloudRunner, CloudUsage, TaskSchema } from './types.js';
2
+
3
+ export type CloudFn<S extends TaskSchema = TaskSchema> = (
4
+ request: CloudRequest<S>,
5
+ options: {
6
+ signal?: AbortSignal;
7
+ /** Report the call's token usage, so calibration and `savingsMeter()` can measure its cost. */
8
+ reportUsage: (usage: CloudUsage | CloudUsage[]) => void;
9
+ },
10
+ ) => Promise<unknown>;
11
+
12
+ /**
13
+ * Wraps a plain async function as a cloud runner. The function returns the raw output:
14
+ * the bare value, the `{ value }` wrapper, or a JSON string of either. The task validates it.
15
+ * Token usage goes through `reportUsage`, since the output itself may be a `{ value }` object.
16
+ *
17
+ * ```ts
18
+ * cloudAdapter(async ({ instruction, input, jsonSchema }, { signal }) => {
19
+ * const res = await fetch('/api/classify', { method: 'POST', body: JSON.stringify({ instruction, input, jsonSchema }), signal });
20
+ * return res.json();
21
+ * });
22
+ * ```
23
+ */
24
+ export function cloudAdapter<S extends TaskSchema = TaskSchema>(
25
+ fn: CloudFn<S>,
26
+ options: { id?: string } = {},
27
+ ): CloudRunner<S> {
28
+ return {
29
+ id: options.id ?? 'cloud',
30
+ async run(request, opts): Promise<CloudOutput> {
31
+ let usage: CloudUsage | CloudUsage[] | undefined;
32
+ const value = await fn(request, { ...opts, reportUsage: (u) => void (usage = u) });
33
+ return usage ? { value, usage } : { value };
34
+ },
35
+ };
36
+ }
37
+
38
+ export interface FetchAdapterOptions<S extends TaskSchema = TaskSchema> {
39
+ /** Your backend endpoint. Never put provider API keys in the browser. */
40
+ url: string | URL;
41
+ headers?: Record<string, string>;
42
+ /** Builds the request body. Defaults to the JSON-serialized request (functions dropped). */
43
+ body?: (request: CloudRequest<S>) => unknown;
44
+ /** Extracts the output from the parsed JSON response. Defaults to the whole response. */
45
+ select?: (json: unknown) => unknown;
46
+ /** Extracts token usage from the parsed JSON response, if your backend passes it through. */
47
+ usage?: (json: unknown) => CloudUsage | CloudUsage[] | undefined;
48
+ id?: string;
49
+ fetch?: typeof fetch;
50
+ }
51
+
52
+ /** A cloud runner that POSTs the request as JSON to your endpoint. */
53
+ export function fetchAdapter<S extends TaskSchema = TaskSchema>(options: FetchAdapterOptions<S>): CloudRunner<S> {
54
+ const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
55
+ return cloudAdapter<S>(
56
+ async (request, { signal, reportUsage }) => {
57
+ const body = options.body ? options.body(request) : request;
58
+ const res = await doFetch(options.url, {
59
+ method: 'POST',
60
+ headers: { 'content-type': 'application/json', ...options.headers },
61
+ body: JSON.stringify(body),
62
+ ...(signal ? { signal } : {}),
63
+ });
64
+ if (!res.ok) throw new Error(`Cloud endpoint responded with HTTP ${res.status}`);
65
+ const json: unknown = await res.json();
66
+ const usage = options.usage?.(json);
67
+ if (usage) reportUsage(usage);
68
+ return options.select ? options.select(json) : json;
69
+ },
70
+ { id: options.id ?? 'fetch' },
71
+ );
72
+ }
@@ -0,0 +1,37 @@
1
+ import type { ProbabilityEntry } from './types.js';
2
+
3
+ /** Probability of the top option: the confidence signal for classifier tasks. */
4
+ export function topProbability(probabilities: readonly ProbabilityEntry[]): number {
5
+ let top = 0;
6
+ for (const p of probabilities) if (p.probability > top) top = p.probability;
7
+ return clamp01(top);
8
+ }
9
+
10
+ export interface ConfidenceSignals {
11
+ /** Whether the output passed schema validation. */
12
+ valid: boolean;
13
+ /** Confidence reported by the local runner itself, if any. */
14
+ runner?: number | undefined;
15
+ /** P(correct) from the classifier-as-judge, if any. */
16
+ judge?: number | undefined;
17
+ }
18
+
19
+ /**
20
+ * Combines the signals into one confidence (ADR 0001, "Confidence signal"):
21
+ *
22
+ * - schema validation is a hard gate: an invalid output has confidence 0;
23
+ * - with only one of `runner` / `judge`, that value is the confidence;
24
+ * - with both, the minimum (the more pessimistic signal wins);
25
+ * - with neither, `undefined`: the task cannot decide and reports a configuration error.
26
+ */
27
+ export function combineConfidence(signals: ConfidenceSignals): number | undefined {
28
+ if (!signals.valid) return 0;
29
+ const values = [signals.runner, signals.judge].filter((v): v is number => typeof v === 'number');
30
+ if (values.length === 0) return undefined;
31
+ return clamp01(Math.min(...values));
32
+ }
33
+
34
+ export function clamp01(n: number): number {
35
+ if (Number.isNaN(n)) return 0;
36
+ return n < 0 ? 0 : n > 1 ? 1 : n;
37
+ }
package/src/cost.ts ADDED
@@ -0,0 +1,148 @@
1
+ import type { BelayEvent, CloudUsage, PriceTable, TokenPrices } from './types.js';
2
+
3
+ /** Normalizes a runner's usage report to a list of per-model parts. */
4
+ export function usageParts(usage: CloudUsage | readonly CloudUsage[] | undefined): CloudUsage[] {
5
+ if (!usage) return [];
6
+ return Array.isArray(usage) ? [...usage] : [usage as CloudUsage];
7
+ }
8
+
9
+ function pricesFor(prices: PriceTable | TokenPrices, model: string | undefined): TokenPrices {
10
+ if (typeof (prices as TokenPrices).input === 'number') return prices as TokenPrices;
11
+ const table = prices as PriceTable;
12
+ if (model !== undefined && Object.hasOwn(table, model)) return table[model]!;
13
+ const known = Object.keys(table).join(', ') || 'none';
14
+ throw new Error(model === undefined ? `usage names no model and the price table has several (${known})` : `no price for model "${model}" (prices for: ${known})`);
15
+ }
16
+
17
+ /**
18
+ * Cost of one cloud call from its token usage. Prices are per million tokens. A price table is
19
+ * keyed by the model id the provider reports, so a call that a fallback model served is priced
20
+ * at that model's rates. Throws when a model has no price: guessing would make every saving wrong.
21
+ */
22
+ export function costOf(usage: CloudUsage | readonly CloudUsage[], prices: PriceTable | TokenPrices): number {
23
+ let total = 0;
24
+ for (const part of usageParts(usage)) {
25
+ const p = pricesFor(prices, part.model);
26
+ total +=
27
+ part.inputTokens * p.input +
28
+ part.outputTokens * p.output +
29
+ (part.cacheReadInputTokens ?? 0) * (p.cacheRead ?? p.input) +
30
+ (part.cacheWriteInputTokens ?? 0) * (p.cacheWrite ?? p.input);
31
+ }
32
+ return total / 1e6;
33
+ }
34
+
35
+ export interface SavingsMeterOptions {
36
+ /** Per-token prices, to measure the cost of each cloud call from the usage its runner reports. */
37
+ prices?: PriceTable | TokenPrices;
38
+ /**
39
+ * Cost of one cloud call, used when calls report no usage, and to value the calls the cascade
40
+ * avoided before any cloud call has been measured. A calibration file's `cost.cloudPerRun` fits.
41
+ */
42
+ cloudPerRun?: number;
43
+ currency?: string;
44
+ }
45
+
46
+ export interface SavingsSummary {
47
+ currency: string | null;
48
+ runs: number;
49
+ /** Answered on device because the local confidence met the threshold. */
50
+ local: number;
51
+ /** Answered by the cloud runner. */
52
+ cloud: number;
53
+ /** Answered on device only because escalation was blocked (policy, consent, cloud error). */
54
+ blocked: number;
55
+ /** Spent on cloud calls: measured where usage was reported, otherwise `cloudPerRun` each. */
56
+ cloudSpend: number | null;
57
+ /** Mean cost of one cloud call (measured when possible). */
58
+ costPerCloudRun: number | null;
59
+ /** What the `local` runs would have cost in the cloud: `local × costPerCloudRun`. */
60
+ saved: number | null;
61
+ /** `saved / (saved + cloudSpend)`: the share of the cloud-only bill the cascade avoided. */
62
+ savedShare: number | null;
63
+ /** How many cloud calls were priced from reported usage. */
64
+ measuredCalls: number;
65
+ }
66
+
67
+ export interface SavingsMeter {
68
+ /** Pass as the task's `onEvent` (or call it from yours). */
69
+ readonly onEvent: (event: BelayEvent) => void;
70
+ /** Totals so far, for all tasks or one. */
71
+ summary(task?: string): SavingsSummary;
72
+ reset(): void;
73
+ }
74
+
75
+ interface Tally {
76
+ runs: number;
77
+ local: number;
78
+ cloud: number;
79
+ blocked: number;
80
+ measuredCalls: number;
81
+ measuredSpend: number;
82
+ }
83
+
84
+ /**
85
+ * Counts what the cascade saves in production. Only runs that stayed on device because the
86
+ * local answer was confident count as saved; runs kept local because escalation was blocked
87
+ * are reported separately. Unmeasured calls, and the value of avoided ones, use the mean
88
+ * measured cost per call, falling back to `cloudPerRun`.
89
+ *
90
+ * ```ts
91
+ * const meter = savingsMeter({ prices, cloudPerRun: calibration.cost?.cloudPerRun });
92
+ * const triage = task({ ..., onEvent: meter.onEvent });
93
+ * meter.summary(); // { runs, local, cloud, cloudSpend, saved, savedShare, ... }
94
+ * ```
95
+ */
96
+ export function savingsMeter(options: SavingsMeterOptions = {}): SavingsMeter {
97
+ const tallies = new Map<string, Tally>();
98
+ const tallyFor = (task: string): Tally => {
99
+ let t = tallies.get(task);
100
+ if (!t) tallies.set(task, (t = { runs: 0, local: 0, cloud: 0, blocked: 0, measuredCalls: 0, measuredSpend: 0 }));
101
+ return t;
102
+ };
103
+
104
+ const onEvent = (event: BelayEvent): void => {
105
+ if (event.type !== 'run') return;
106
+ const t = tallyFor(event.task);
107
+ t.runs++;
108
+ if (event.source === 'cloud') {
109
+ t.cloud++;
110
+ if (options.prices && event.cloudUsage?.length) {
111
+ t.measuredSpend += costOf(event.cloudUsage, options.prices);
112
+ t.measuredCalls++;
113
+ }
114
+ } else if (event.escalationBlocked) {
115
+ t.blocked++;
116
+ } else if (event.escalationReason === null) {
117
+ t.local++;
118
+ }
119
+ };
120
+
121
+ const summary = (task?: string): SavingsSummary => {
122
+ const parts = task === undefined ? [...tallies.values()] : tallies.has(task) ? [tallies.get(task)!] : [];
123
+ const sum = (key: keyof Tally) => parts.reduce((a, t) => a + t[key], 0);
124
+ const runs = sum('runs');
125
+ const local = sum('local');
126
+ const cloud = sum('cloud');
127
+ const measuredCalls = sum('measuredCalls');
128
+ const measuredSpend = sum('measuredSpend');
129
+ const costPerCloudRun = measuredCalls ? measuredSpend / measuredCalls : (options.cloudPerRun ?? null);
130
+ const cloudSpend = costPerCloudRun === null ? null : measuredSpend + (cloud - measuredCalls) * costPerCloudRun;
131
+ const saved = costPerCloudRun === null ? null : local * costPerCloudRun;
132
+ const denominator = saved === null || cloudSpend === null ? 0 : saved + cloudSpend;
133
+ return {
134
+ currency: options.currency ?? null,
135
+ runs,
136
+ local,
137
+ cloud,
138
+ blocked: sum('blocked'),
139
+ cloudSpend,
140
+ costPerCloudRun,
141
+ saved,
142
+ savedShare: denominator > 0 ? saved! / denominator : null,
143
+ measuredCalls,
144
+ };
145
+ };
146
+
147
+ return { onEvent, summary, reset: () => tallies.clear() };
148
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,28 @@
1
+ export type BelayErrorCode =
2
+ /** No local output and escalation was not possible or not permitted. */
3
+ | 'no-result'
4
+ /** The cloud runner threw or returned an output that does not match the schema. */
5
+ | 'cloud-error'
6
+ | 'cloud-invalid-output'
7
+ /** The task definition is invalid. */
8
+ | 'invalid-task'
9
+ /** The calibration file is malformed or does not belong to this task. */
10
+ | 'invalid-calibration';
11
+
12
+ export class BelayError extends Error {
13
+ override readonly name = 'BelayError';
14
+ readonly code: BelayErrorCode;
15
+
16
+ constructor(code: BelayErrorCode, message: string, options?: { cause?: unknown }) {
17
+ super(message, options);
18
+ this.code = code;
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Thrown by a local runner from `run()` when the model is not usable (e.g. it would need
24
+ * a download). The cascade treats it as escalation reason `local-unavailable`.
25
+ */
26
+ export class LocalUnavailableError extends Error {
27
+ override readonly name = 'LocalUnavailableError';
28
+ }