@zanii/sla 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,159 @@
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 Derivative
95
+ 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; and
103
+
104
+ (d) If the Work includes a "NOTICE" text file as part of its
105
+ distribution, then any Derivative Works that You distribute must
106
+ include a readable copy of the attribution notices contained
107
+ within such NOTICE file.
108
+
109
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
110
+ any Contribution intentionally submitted for inclusion in the Work
111
+ by You to the Licensor shall be under the terms and conditions of
112
+ this License, without any additional terms or conditions.
113
+
114
+ 6. Trademarks. This License does not grant permission to use the trade
115
+ names, trademarks, service marks, or product names of the Licensor,
116
+ except as required for reasonable and customary use in describing the
117
+ origin of the Work and reproducing the content of the NOTICE file.
118
+
119
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed
120
+ to in writing, Licensor provides the Work (and each Contributor
121
+ provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
122
+ OR CONDITIONS OF ANY KIND, either express or implied, including,
123
+ without limitation, any warranties or conditions of TITLE,
124
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
125
+
126
+ 8. Limitation of Liability. In no event and under no legal theory,
127
+ whether in tort (including negligence), contract, or otherwise,
128
+ unless required by applicable law (such as deliberate and grossly
129
+ negligent acts) or agreed to in writing, shall any Contributor be
130
+ liable to You for damages, including any direct, indirect, special,
131
+ incidental, or consequential damages of any character arising as a
132
+ result of this License or out of the use or inability to use the
133
+ Work.
134
+
135
+ 9. Accepting Warranty or Additional Liability. While redistributing
136
+ the Work or Derivative Works thereof, You may choose to offer,
137
+ and charge a fee for, acceptance of support, warranty, indemnity,
138
+ or other liability obligations and/or rights consistent with this
139
+ License. However, in accepting such obligations, You may act only
140
+ on Your own behalf and on Your sole responsibility, not on behalf
141
+ of any other Contributor, and only if You agree to indemnify,
142
+ defend, and hold each Contributor harmless for any liability
143
+ incurred by, or claims asserted against, such Contributor.
144
+
145
+ END OF TERMS AND CONDITIONS
146
+
147
+ Copyright 2026 Zanii
148
+
149
+ Licensed under the Apache License, Version 2.0 (the "License");
150
+ you may not use this file except in compliance with the License.
151
+ You may obtain a copy of the License at
152
+
153
+ http://www.apache.org/licenses/LICENSE-2.0
154
+
155
+ Unless required by applicable law or agreed to in writing, software
156
+ distributed under the License is distributed on an "AS IS" BASIS,
157
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
158
+ See the License for the specific language governing permissions and
159
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # @zanii/sla
2
+
3
+ Machine-verifiable service agreements between agents. Provider and client co-sign
4
+ terms — what service (a target scope), over what window, how much (`min`/`max`
5
+ actions), how continuously (`max_gap_ms`, an uptime proxy) — and then **compliance is
6
+ computed from receipts, not argued about**. Same terms + same receipts → same verdict
7
+ for everyone, and every breach cites its evidence. Pair with `@zanii/escrow`: a breach
8
+ verdict is refund evidence.
9
+
10
+ ```sh
11
+ npm install @zanii/sla @zanii/core @zanii/payments
12
+ ```
13
+
14
+ ```ts
15
+ import { buildSlaBody, signSla, assembleSla, assessCompliance } from '@zanii/sla';
16
+
17
+ const body = buildSlaBody({
18
+ provider: worker.did, client: buyer.did, scope: 'feed.*',
19
+ window: { start, end },
20
+ commitments: { min_actions: 100, max_gap_ms: 15 * 60_000 },
21
+ price: { amount: '499.00', currency: 'USD' }, // informational — ties to an escrow
22
+ createdAt: now,
23
+ });
24
+ const sla = assembleSla(body, [signSla(body, worker.did, workerKey), signSla(body, buyer.did, buyerKey)]);
25
+
26
+ // hand in the provider's CONSECUTIVE chain segment covering the window:
27
+ const report = assessCompliance(sla, receipts, { asOf: now }); // asOf: fair mid-window checks
28
+ report.ok; // no breaches
29
+ report.breaches; // [{ kind, detail, receipt? }] — each cites the evidence
30
+ report.metrics; // { actions, max_gap_ms }
31
+ ```
32
+
33
+ Python: `from zanii.sla import build_sla_body, assess_compliance, ...` — byte-identical
34
+ JCS objects and hashes.
35
+
36
+ ## The property that makes the metrics honest
37
+
38
+ Counting receipts is worthless if the provider can omit the bad hour. Zanii receipts
39
+ form a **per-agent hash chain** (`prev` links), so completeness is *provable*:
40
+ `assessCompliance` verifies the slice is consecutive in the provider's chain — a
41
+ broken link is an **`INCOMPLETE_RECORD`** breach, not a silently wrong count. Trimming
42
+ the ends doesn't help either: it shows as fewer actions and bigger edge gaps (gaps are
43
+ measured to the window boundaries, not just between receipts).
44
+
45
+ Breach kinds: `INVALID_RECEIPT` · `INCOMPLETE_RECORD` · `TOO_FEW_ACTIONS` ·
46
+ `TOO_MANY_ACTIONS` · `MAX_GAP_EXCEEDED`.
47
+
48
+ ## The limit, stated up front
49
+
50
+ Receipts prove what was *recorded* — an action taken entirely off the rails is the
51
+ credential-custody problem, not an SLA one. A gap breach proves **silence on the
52
+ ledger**, which the SLA defines as breach; that definition is the parties' agreement,
53
+ not a law of nature.
@@ -0,0 +1,92 @@
1
+ import { type Receipt } from '@zanii/core';
2
+ import { type Money } from '@zanii/payments';
3
+ export interface SlaCommitments {
4
+ /** Fewest matching receipts the window must contain. */
5
+ min_actions?: number;
6
+ /** Most matching receipts the window may contain. */
7
+ max_actions?: number;
8
+ /** Max silence between matching receipts (and to the window edges) — an uptime proxy. */
9
+ max_gap_ms?: number;
10
+ }
11
+ export interface SlaBody {
12
+ v: 1;
13
+ type: 'sla';
14
+ provider: string;
15
+ client: string;
16
+ /** Scope pattern the service's receipts must match, e.g. `feed.sync` or `api.*`. */
17
+ scope: string;
18
+ window: {
19
+ start: string;
20
+ end: string;
21
+ };
22
+ commitments: SlaCommitments;
23
+ /** Informational price — ties to an escrow; not used by compliance math. */
24
+ price?: Money;
25
+ created_at: string;
26
+ ref?: string;
27
+ }
28
+ export interface SlaSignature {
29
+ did: string;
30
+ /** `ed25519:<hex>` over the canonical (JCS) bytes of the body. */
31
+ sig: string;
32
+ }
33
+ export interface Sla {
34
+ body: SlaBody;
35
+ signatures: SlaSignature[];
36
+ }
37
+ export interface SlaInput {
38
+ provider: string;
39
+ client: string;
40
+ scope: string;
41
+ window: {
42
+ start: string;
43
+ end: string;
44
+ };
45
+ commitments: SlaCommitments;
46
+ price?: {
47
+ amount: string;
48
+ currency: string;
49
+ };
50
+ createdAt: string;
51
+ ref?: string;
52
+ }
53
+ export declare function buildSlaBody(input: SlaInput): SlaBody;
54
+ /** One party signs the terms. Collect one from the provider and one from the client. */
55
+ export declare function signSla(body: SlaBody, did: string, privateKey: Uint8Array): SlaSignature;
56
+ export declare function assembleSla(body: SlaBody, signatures: SlaSignature[]): Sla;
57
+ export declare function slaHash(sla: Sla): string;
58
+ export interface SlaCheck {
59
+ ok: boolean;
60
+ reasons: string[];
61
+ }
62
+ /** Verify the agreement: structure sane, BOTH provider and client signed these exact terms. */
63
+ export declare function verifySla(sla: Sla | undefined): SlaCheck;
64
+ export type BreachKind = 'INVALID_RECEIPT' | 'INCOMPLETE_RECORD' | 'TOO_FEW_ACTIONS' | 'TOO_MANY_ACTIONS' | 'MAX_GAP_EXCEEDED';
65
+ export interface Breach {
66
+ kind: BreachKind;
67
+ detail: string;
68
+ /** JCS hash of the receipt at/after which the breach sits, when applicable. */
69
+ receipt?: string;
70
+ }
71
+ export interface ComplianceReport {
72
+ ok: boolean;
73
+ breaches: Breach[];
74
+ metrics: {
75
+ /** In-window, in-scope receipts. */
76
+ actions: number;
77
+ /** Largest observed silence (ms), window edges included. null when nothing matched. */
78
+ max_gap_ms: number | null;
79
+ };
80
+ }
81
+ /**
82
+ * The compliance verdict — pure computation. Pass the provider's **consecutive chain
83
+ * segment** covering the window (its export slice): every receipt is signature-checked,
84
+ * the `prev` links are verified so nothing recorded can be hidden between the endpoints
85
+ * (`INCOMPLETE_RECORD` otherwise), then the commitments are measured on the in-window,
86
+ * in-scope receipts. `asOf` (default: window end) caps the trailing-gap check so a
87
+ * mid-window assessment doesn't count the not-yet-elapsed silence as breach.
88
+ */
89
+ export declare function assessCompliance(sla: Sla, receipts: Receipt[], opts?: {
90
+ asOf?: string;
91
+ }): ComplianceReport;
92
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA8BA,OAAO,EAOL,KAAK,OAAO,EACb,MAAM,aAAa,CAAC;AACrB,OAAO,EAAc,KAAK,KAAK,EAAE,MAAM,iBAAiB,CAAC;AAEzD,MAAM,WAAW,cAAc;IAC7B,wDAAwD;IACxD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,qDAAqD;IACrD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yFAAyF;IACzF,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,OAAO;IACtB,CAAC,EAAE,CAAC,CAAC;IACL,IAAI,EAAE,KAAK,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,oFAAoF;IACpF,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC;IACvC,WAAW,EAAE,cAAc,CAAC;IAC5B,4EAA4E;IAC5E,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,kEAAkE;IAClE,GAAG,EAAE,MAAM,CAAC;CACb;AAED,MAAM,WAAW,GAAG;IAClB,IAAI,EAAE,OAAO,CAAC;IACd,UAAU,EAAE,YAAY,EAAE,CAAC;CAC5B;AAED,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE;QAAE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,MAAM,GAAG,IAAI,CAAC;KAC3B,CAAC;CACH;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,IAAI,GAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,gBAAgB,CAmE9G"}
package/dist/index.js ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * @zanii/sla — machine-verifiable service agreements between agents.
3
+ *
4
+ * Two parties co-sign terms — what service (a target scope), over what window, how
5
+ * much (min/max actions), how continuously (`max_gap_ms`, an uptime proxy) — and then
6
+ * **compliance is computed from receipts, not argued about**. `assessCompliance` is
7
+ * pure: same terms + same receipts → same verdict for everyone, and every breach cites
8
+ * the evidence. Pair with `@zanii/escrow`: a breach verdict is refund evidence.
9
+ *
10
+ * ## The property that makes the metrics honest
11
+ *
12
+ * Counting receipts is worthless if the provider can omit the bad hour. Zanii receipts
13
+ * form a **per-agent hash chain** (`prev` links), so completeness is *provable*:
14
+ * `assessCompliance` verifies the provided slice is consecutive in the provider's
15
+ * chain — a broken link is an `INCOMPLETE_RECORD` breach, not a silently wrong count.
16
+ * The provider hands over its chain segment covering the window; it cannot cherry-pick
17
+ * from the middle without the seam showing. (Chopping the *ends* off shortens the
18
+ * record visibly — fewer actions and bigger edge gaps — so trimming hurts, not helps.)
19
+ *
20
+ * ## The limit, stated up front
21
+ *
22
+ * Receipts prove what was *recorded*, with recording enforced by the rails — an action
23
+ * taken entirely off the rails is the credential-custody problem, not an SLA one. The
24
+ * chain check proves no *recorded* action was hidden between the endpooints you were
25
+ * given between the endpoints; it cannot conjure receipts that were never created. And a gap breach proves
26
+ * silence on the ledger, which the SLA defines as breach — that definition is the
27
+ * parties' agreement, not a law of nature.
28
+ */
29
+ import { ed25519 } from '@noble/curves/ed25519';
30
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
31
+ import { canonicalBytes, jcsHash, publicKeyFromDid, receiptHash, scopeCovers, verifyReceipt, } from '@zanii/core';
32
+ import { parseMoney } from '@zanii/payments';
33
+ export function buildSlaBody(input) {
34
+ if (!input.provider || !input.client)
35
+ throw new Error('provider and client are required');
36
+ if (input.provider === input.client)
37
+ throw new Error('provider and client must differ');
38
+ if (!input.scope)
39
+ throw new Error('scope is required (the target pattern the service receipts match)');
40
+ const start = Date.parse(input.window?.start ?? '');
41
+ const end = Date.parse(input.window?.end ?? '');
42
+ if (Number.isNaN(start) || Number.isNaN(end))
43
+ throw new Error('window start/end must be ISO timestamps');
44
+ if (start >= end)
45
+ throw new Error('window start must be before end');
46
+ if (Number.isNaN(Date.parse(input.createdAt)))
47
+ throw new Error('createdAt must be an ISO timestamp');
48
+ const c = input.commitments ?? {};
49
+ for (const [k, v] of Object.entries(c)) {
50
+ if (v !== undefined && (!Number.isInteger(v) || v < 0))
51
+ throw new Error(`commitment ${k} must be a non-negative integer`);
52
+ }
53
+ if (c.min_actions === undefined && c.max_actions === undefined && c.max_gap_ms === undefined) {
54
+ throw new Error('an SLA with no commitments commits to nothing');
55
+ }
56
+ if (c.min_actions !== undefined && c.max_actions !== undefined && c.min_actions > c.max_actions) {
57
+ throw new Error('min_actions must not exceed max_actions');
58
+ }
59
+ const body = {
60
+ v: 1,
61
+ type: 'sla',
62
+ provider: input.provider,
63
+ client: input.client,
64
+ scope: input.scope,
65
+ window: input.window,
66
+ commitments: c,
67
+ created_at: input.createdAt,
68
+ };
69
+ if (input.price)
70
+ body.price = parseMoney(input.price.amount, input.price.currency);
71
+ if (input.ref !== undefined)
72
+ body.ref = input.ref;
73
+ return body;
74
+ }
75
+ const sign = (obj, priv) => `ed25519:${bytesToHex(ed25519.sign(canonicalBytes(obj), priv))}`;
76
+ const sigValid = (obj, did, sig) => {
77
+ const pub = publicKeyFromDid(did);
78
+ const hex = typeof sig === 'string' && sig.startsWith('ed25519:') ? sig.slice(8) : '';
79
+ if (!pub || !/^[0-9a-f]{128}$/.test(hex))
80
+ return false;
81
+ try {
82
+ return ed25519.verify(hexToBytes(hex), canonicalBytes(obj), pub);
83
+ }
84
+ catch {
85
+ return false;
86
+ }
87
+ };
88
+ /** One party signs the terms. Collect one from the provider and one from the client. */
89
+ export function signSla(body, did, privateKey) {
90
+ return { did, sig: sign(body, privateKey) };
91
+ }
92
+ export function assembleSla(body, signatures) {
93
+ return { body, signatures };
94
+ }
95
+ export function slaHash(sla) {
96
+ return jcsHash(sla);
97
+ }
98
+ /** Verify the agreement: structure sane, BOTH provider and client signed these exact terms. */
99
+ export function verifySla(sla) {
100
+ const reasons = [];
101
+ const e = sla ?? {};
102
+ const b = e.body ?? {};
103
+ if (b.v !== 1 || b.type !== 'sla')
104
+ reasons.push('not an sla (v1)');
105
+ if (!b.provider || !b.client || b.provider === b.client)
106
+ reasons.push('missing/invalid parties');
107
+ if (!b.scope)
108
+ reasons.push('missing scope');
109
+ const start = Date.parse(b.window?.start ?? '');
110
+ const end = Date.parse(b.window?.end ?? '');
111
+ if (Number.isNaN(start) || Number.isNaN(end) || start >= end)
112
+ reasons.push('invalid window');
113
+ const c = b.commitments ?? {};
114
+ if (c.min_actions === undefined && c.max_actions === undefined && c.max_gap_ms === undefined) {
115
+ reasons.push('no commitments');
116
+ }
117
+ if (reasons.length === 0) {
118
+ for (const [party, role] of [[b.provider, 'provider'], [b.client, 'client']]) {
119
+ const s = (e.signatures ?? []).find((x) => x.did === party);
120
+ if (!s)
121
+ reasons.push(`missing signature from ${role}`);
122
+ else if (!sigValid(b, s.did, s.sig))
123
+ reasons.push(`invalid signature from ${role}`);
124
+ }
125
+ }
126
+ return { ok: reasons.length === 0, reasons };
127
+ }
128
+ /**
129
+ * The compliance verdict — pure computation. Pass the provider's **consecutive chain
130
+ * segment** covering the window (its export slice): every receipt is signature-checked,
131
+ * the `prev` links are verified so nothing recorded can be hidden between the endpoints
132
+ * (`INCOMPLETE_RECORD` otherwise), then the commitments are measured on the in-window,
133
+ * in-scope receipts. `asOf` (default: window end) caps the trailing-gap check so a
134
+ * mid-window assessment doesn't count the not-yet-elapsed silence as breach.
135
+ */
136
+ export function assessCompliance(sla, receipts, opts = {}) {
137
+ const agreement = verifySla(sla);
138
+ if (!agreement.ok) {
139
+ return { ok: false, breaches: agreement.reasons.map((r) => ({ kind: 'INVALID_RECEIPT', detail: `sla: ${r}` })), metrics: { actions: 0, max_gap_ms: null } };
140
+ }
141
+ const b = sla.body;
142
+ const breaches = [];
143
+ const winStart = Date.parse(b.window.start);
144
+ const winEnd = Date.parse(b.window.end);
145
+ if (opts.asOf !== undefined && Number.isNaN(Date.parse(opts.asOf)))
146
+ throw new Error('asOf must be an ISO timestamp');
147
+ const asOf = Math.min(opts.asOf !== undefined ? Date.parse(opts.asOf) : winEnd, winEnd);
148
+ // 1. Every receipt must be valid and the provider's.
149
+ const sorted = [...receipts].sort((x, y) => Date.parse(x.ts) - Date.parse(y.ts));
150
+ for (const r of sorted) {
151
+ const check = verifyReceipt(r);
152
+ if (!check.ok)
153
+ breaches.push({ kind: 'INVALID_RECEIPT', detail: check.error ?? 'invalid receipt', receipt: receiptHash(r) });
154
+ else if (r.agent_id !== b.provider)
155
+ breaches.push({ kind: 'INVALID_RECEIPT', detail: `receipt by ${r.agent_id}, not the provider`, receipt: receiptHash(r) });
156
+ }
157
+ // 2. The slice must be consecutive in the provider's hash chain — omission shows as a seam.
158
+ for (let i = 1; i < sorted.length; i++) {
159
+ if (sorted[i].prev !== receiptHash(sorted[i - 1])) {
160
+ breaches.push({
161
+ kind: 'INCOMPLETE_RECORD',
162
+ detail: `chain break between receipts #${i - 1} and #${i} — the slice is not the provider's consecutive record`,
163
+ receipt: receiptHash(sorted[i]),
164
+ });
165
+ }
166
+ }
167
+ // 3. Measure commitments on the in-window, in-scope receipts.
168
+ const matching = sorted.filter((r) => {
169
+ const t = Date.parse(r.ts);
170
+ return t >= winStart && t <= winEnd && scopeCovers(b.scope, r.target);
171
+ });
172
+ const c = b.commitments;
173
+ if (c.min_actions !== undefined && matching.length < c.min_actions) {
174
+ breaches.push({ kind: 'TOO_FEW_ACTIONS', detail: `${matching.length} matching actions < committed minimum ${c.min_actions}` });
175
+ }
176
+ if (c.max_actions !== undefined && matching.length > c.max_actions) {
177
+ breaches.push({ kind: 'TOO_MANY_ACTIONS', detail: `${matching.length} matching actions > committed maximum ${c.max_actions}` });
178
+ }
179
+ let maxGap = null;
180
+ if (matching.length > 0) {
181
+ const times = matching.map((r) => Date.parse(r.ts));
182
+ const gaps = [{ ms: times[0] - winStart }];
183
+ for (let i = 1; i < times.length; i++)
184
+ gaps.push({ ms: times[i] - times[i - 1], after: matching[i - 1] });
185
+ if (asOf > times[times.length - 1])
186
+ gaps.push({ ms: asOf - times[times.length - 1], after: matching[matching.length - 1] });
187
+ maxGap = Math.max(...gaps.map((g) => g.ms));
188
+ if (c.max_gap_ms !== undefined) {
189
+ for (const g of gaps) {
190
+ if (g.ms > c.max_gap_ms) {
191
+ breaches.push({
192
+ kind: 'MAX_GAP_EXCEEDED',
193
+ detail: `${g.ms}ms of silence > committed max ${c.max_gap_ms}ms`,
194
+ ...(g.after ? { receipt: receiptHash(g.after) } : {}),
195
+ });
196
+ }
197
+ }
198
+ }
199
+ }
200
+ else if (c.max_gap_ms !== undefined && asOf - winStart > c.max_gap_ms) {
201
+ breaches.push({ kind: 'MAX_GAP_EXCEEDED', detail: `no matching actions for ${asOf - winStart}ms > committed max ${c.max_gap_ms}ms` });
202
+ }
203
+ return { ok: breaches.length === 0, breaches, metrics: { actions: matching.length, max_gap_ms: maxGap } };
204
+ }
205
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EACL,cAAc,EACd,OAA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AM,CAAC,IAAI,IAAI,EAAE,CAAC;gBACrB,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC;oBACxB,QAAQ,CAAC,IAAI,CAAC;wBACZ,IAAI,EAAE,kBAAkB;wBACxB,MAAM,EAAE,GAAG,CAAC,CAAC,EAAE,iCAAiC,CAAC,CAAC,UAAU,IAAI;wBAChE,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;qBACtD,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;SAAM,IAAI,CAAC,CAAC,UAAU,KAAK,SAAS,IAAI,IAAI,GAAG,QAAQ,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC;QACxE,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,kBAAkB,EAAE,MAAM,EAAE,2BAA2B,IAAI,GAAG,QAAQ,sBAAsB,CAAC,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC;IACxI,CAAC;IAED,OAAO,EAAE,EAAE,EAAE,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC;AAC5G,CAAC"}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@zanii/sla",
3
+ "version": "0.1.0",
4
+ "description": "Machine-verifiable service agreements between agents - co-signed terms (scope, window, volume, max-gap uptime proxy) with compliance computed deterministically from receipts. The per-agent hash chain closes the omission hole: a broken prev-link is an INCOMPLETE_RECORD breach, so a provider cannot hide the bad hour. Disputes become arithmetic, and breaches cite receipts.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://ledger.zanii.agency",
7
+ "type": "module",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^26.1.0",
30
+ "typescript": "^5.8.2",
31
+ "vitest": "^3.0.9"
32
+ },
33
+ "dependencies": {
34
+ "@noble/curves": "^1.8.1",
35
+ "@noble/hashes": "^1.7.1",
36
+ "@zanii/core": "0.4.0",
37
+ "@zanii/payments": "0.1.0"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc -p tsconfig.build.json",
41
+ "test": "vitest run",
42
+ "typecheck": "tsc --noEmit"
43
+ }
44
+ }
package/src/index.ts ADDED
@@ -0,0 +1,279 @@
1
+ /**
2
+ * @zanii/sla — machine-verifiable service agreements between agents.
3
+ *
4
+ * Two parties co-sign terms — what service (a target scope), over what window, how
5
+ * much (min/max actions), how continuously (`max_gap_ms`, an uptime proxy) — and then
6
+ * **compliance is computed from receipts, not argued about**. `assessCompliance` is
7
+ * pure: same terms + same receipts → same verdict for everyone, and every breach cites
8
+ * the evidence. Pair with `@zanii/escrow`: a breach verdict is refund evidence.
9
+ *
10
+ * ## The property that makes the metrics honest
11
+ *
12
+ * Counting receipts is worthless if the provider can omit the bad hour. Zanii receipts
13
+ * form a **per-agent hash chain** (`prev` links), so completeness is *provable*:
14
+ * `assessCompliance` verifies the provided slice is consecutive in the provider's
15
+ * chain — a broken link is an `INCOMPLETE_RECORD` breach, not a silently wrong count.
16
+ * The provider hands over its chain segment covering the window; it cannot cherry-pick
17
+ * from the middle without the seam showing. (Chopping the *ends* off shortens the
18
+ * record visibly — fewer actions and bigger edge gaps — so trimming hurts, not helps.)
19
+ *
20
+ * ## The limit, stated up front
21
+ *
22
+ * Receipts prove what was *recorded*, with recording enforced by the rails — an action
23
+ * taken entirely off the rails is the credential-custody problem, not an SLA one. The
24
+ * chain check proves no *recorded* action was hidden between the endpooints you were
25
+ * given between the endpoints; it cannot conjure receipts that were never created. And a gap breach proves
26
+ * silence on the ledger, which the SLA defines as breach — that definition is the
27
+ * parties' agreement, not a law of nature.
28
+ */
29
+ import { ed25519 } from '@noble/curves/ed25519';
30
+ import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
31
+ import {
32
+ canonicalBytes,
33
+ jcsHash,
34
+ publicKeyFromDid,
35
+ receiptHash,
36
+ scopeCovers,
37
+ verifyReceipt,
38
+ type Receipt,
39
+ } from '@zanii/core';
40
+ import { parseMoney, type Money } from '@zanii/payments';
41
+
42
+ export interface SlaCommitments {
43
+ /** Fewest matching receipts the window must contain. */
44
+ min_actions?: number;
45
+ /** Most matching receipts the window may contain. */
46
+ max_actions?: number;
47
+ /** Max silence between matching receipts (and to the window edges) — an uptime proxy. */
48
+ max_gap_ms?: number;
49
+ }
50
+
51
+ export interface SlaBody {
52
+ v: 1;
53
+ type: 'sla';
54
+ provider: string;
55
+ client: string;
56
+ /** Scope pattern the service's receipts must match, e.g. `feed.sync` or `api.*`. */
57
+ scope: string;
58
+ window: { start: string; end: string };
59
+ commitments: SlaCommitments;
60
+ /** Informational price — ties to an escrow; not used by compliance math. */
61
+ price?: Money;
62
+ created_at: string;
63
+ ref?: string;
64
+ }
65
+
66
+ export interface SlaSignature {
67
+ did: string;
68
+ /** `ed25519:<hex>` over the canonical (JCS) bytes of the body. */
69
+ sig: string;
70
+ }
71
+
72
+ export interface Sla {
73
+ body: SlaBody;
74
+ signatures: SlaSignature[];
75
+ }
76
+
77
+ export interface SlaInput {
78
+ provider: string;
79
+ client: string;
80
+ scope: string;
81
+ window: { start: string; end: string };
82
+ commitments: SlaCommitments;
83
+ price?: { amount: string; currency: string };
84
+ createdAt: string;
85
+ ref?: string;
86
+ }
87
+
88
+ export function buildSlaBody(input: SlaInput): SlaBody {
89
+ if (!input.provider || !input.client) throw new Error('provider and client are required');
90
+ if (input.provider === input.client) throw new Error('provider and client must differ');
91
+ if (!input.scope) throw new Error('scope is required (the target pattern the service receipts match)');
92
+ const start = Date.parse(input.window?.start ?? '');
93
+ const end = Date.parse(input.window?.end ?? '');
94
+ if (Number.isNaN(start) || Number.isNaN(end)) throw new Error('window start/end must be ISO timestamps');
95
+ if (start >= end) throw new Error('window start must be before end');
96
+ if (Number.isNaN(Date.parse(input.createdAt))) throw new Error('createdAt must be an ISO timestamp');
97
+ const c = input.commitments ?? {};
98
+ for (const [k, v] of Object.entries(c)) {
99
+ if (v !== undefined && (!Number.isInteger(v) || v < 0)) throw new Error(`commitment ${k} must be a non-negative integer`);
100
+ }
101
+ if (c.min_actions === undefined && c.max_actions === undefined && c.max_gap_ms === undefined) {
102
+ throw new Error('an SLA with no commitments commits to nothing');
103
+ }
104
+ if (c.min_actions !== undefined && c.max_actions !== undefined && c.min_actions > c.max_actions) {
105
+ throw new Error('min_actions must not exceed max_actions');
106
+ }
107
+ const body: SlaBody = {
108
+ v: 1,
109
+ type: 'sla',
110
+ provider: input.provider,
111
+ client: input.client,
112
+ scope: input.scope,
113
+ window: input.window,
114
+ commitments: c,
115
+ created_at: input.createdAt,
116
+ };
117
+ if (input.price) body.price = parseMoney(input.price.amount, input.price.currency);
118
+ if (input.ref !== undefined) body.ref = input.ref;
119
+ return body;
120
+ }
121
+
122
+ const sign = (obj: Record<string, unknown>, priv: Uint8Array): string =>
123
+ `ed25519:${bytesToHex(ed25519.sign(canonicalBytes(obj), priv))}`;
124
+
125
+ const sigValid = (obj: Record<string, unknown>, did: string, sig: unknown): boolean => {
126
+ const pub = publicKeyFromDid(did);
127
+ const hex = typeof sig === 'string' && sig.startsWith('ed25519:') ? sig.slice(8) : '';
128
+ if (!pub || !/^[0-9a-f]{128}$/.test(hex)) return false;
129
+ try {
130
+ return ed25519.verify(hexToBytes(hex), canonicalBytes(obj), pub);
131
+ } catch {
132
+ return false;
133
+ }
134
+ };
135
+
136
+ /** One party signs the terms. Collect one from the provider and one from the client. */
137
+ export function signSla(body: SlaBody, did: string, privateKey: Uint8Array): SlaSignature {
138
+ return { did, sig: sign(body as unknown as Record<string, unknown>, privateKey) };
139
+ }
140
+
141
+ export function assembleSla(body: SlaBody, signatures: SlaSignature[]): Sla {
142
+ return { body, signatures };
143
+ }
144
+
145
+ export function slaHash(sla: Sla): string {
146
+ return jcsHash(sla as unknown as Record<string, unknown>);
147
+ }
148
+
149
+ export interface SlaCheck {
150
+ ok: boolean;
151
+ reasons: string[];
152
+ }
153
+
154
+ /** Verify the agreement: structure sane, BOTH provider and client signed these exact terms. */
155
+ export function verifySla(sla: Sla | undefined): SlaCheck {
156
+ const reasons: string[] = [];
157
+ const e = sla ?? ({} as Sla);
158
+ const b = e.body ?? ({} as SlaBody);
159
+ if (b.v !== 1 || b.type !== 'sla') reasons.push('not an sla (v1)');
160
+ if (!b.provider || !b.client || b.provider === b.client) reasons.push('missing/invalid parties');
161
+ if (!b.scope) reasons.push('missing scope');
162
+ const start = Date.parse(b.window?.start ?? '');
163
+ const end = Date.parse(b.window?.end ?? '');
164
+ if (Number.isNaN(start) || Number.isNaN(end) || start >= end) reasons.push('invalid window');
165
+ const c = b.commitments ?? {};
166
+ if (c.min_actions === undefined && c.max_actions === undefined && c.max_gap_ms === undefined) {
167
+ reasons.push('no commitments');
168
+ }
169
+ if (reasons.length === 0) {
170
+ for (const [party, role] of [[b.provider, 'provider'], [b.client, 'client']] as const) {
171
+ const s = (e.signatures ?? []).find((x) => x.did === party);
172
+ if (!s) reasons.push(`missing signature from ${role}`);
173
+ else if (!sigValid(b as unknown as Record<string, unknown>, s.did, s.sig)) reasons.push(`invalid signature from ${role}`);
174
+ }
175
+ }
176
+ return { ok: reasons.length === 0, reasons };
177
+ }
178
+
179
+ export type BreachKind =
180
+ | 'INVALID_RECEIPT'
181
+ | 'INCOMPLETE_RECORD'
182
+ | 'TOO_FEW_ACTIONS'
183
+ | 'TOO_MANY_ACTIONS'
184
+ | 'MAX_GAP_EXCEEDED';
185
+
186
+ export interface Breach {
187
+ kind: BreachKind;
188
+ detail: string;
189
+ /** JCS hash of the receipt at/after which the breach sits, when applicable. */
190
+ receipt?: string;
191
+ }
192
+
193
+ export interface ComplianceReport {
194
+ ok: boolean;
195
+ breaches: Breach[];
196
+ metrics: {
197
+ /** In-window, in-scope receipts. */
198
+ actions: number;
199
+ /** Largest observed silence (ms), window edges included. null when nothing matched. */
200
+ max_gap_ms: number | null;
201
+ };
202
+ }
203
+
204
+ /**
205
+ * The compliance verdict — pure computation. Pass the provider's **consecutive chain
206
+ * segment** covering the window (its export slice): every receipt is signature-checked,
207
+ * the `prev` links are verified so nothing recorded can be hidden between the endpoints
208
+ * (`INCOMPLETE_RECORD` otherwise), then the commitments are measured on the in-window,
209
+ * in-scope receipts. `asOf` (default: window end) caps the trailing-gap check so a
210
+ * mid-window assessment doesn't count the not-yet-elapsed silence as breach.
211
+ */
212
+ export function assessCompliance(sla: Sla, receipts: Receipt[], opts: { asOf?: string } = {}): ComplianceReport {
213
+ const agreement = verifySla(sla);
214
+ if (!agreement.ok) {
215
+ return { ok: false, breaches: agreement.reasons.map((r) => ({ kind: 'INVALID_RECEIPT' as const, detail: `sla: ${r}` })), metrics: { actions: 0, max_gap_ms: null } };
216
+ }
217
+ const b = sla.body;
218
+ const breaches: Breach[] = [];
219
+ const winStart = Date.parse(b.window.start);
220
+ const winEnd = Date.parse(b.window.end);
221
+ if (opts.asOf !== undefined && Number.isNaN(Date.parse(opts.asOf))) throw new Error('asOf must be an ISO timestamp');
222
+ const asOf = Math.min(opts.asOf !== undefined ? Date.parse(opts.asOf) : winEnd, winEnd);
223
+
224
+ // 1. Every receipt must be valid and the provider's.
225
+ const sorted = [...receipts].sort((x, y) => Date.parse(x.ts) - Date.parse(y.ts));
226
+ for (const r of sorted) {
227
+ const check = verifyReceipt(r);
228
+ if (!check.ok) breaches.push({ kind: 'INVALID_RECEIPT', detail: check.error ?? 'invalid receipt', receipt: receiptHash(r) });
229
+ else if (r.agent_id !== b.provider) breaches.push({ kind: 'INVALID_RECEIPT', detail: `receipt by ${r.agent_id}, not the provider`, receipt: receiptHash(r) });
230
+ }
231
+
232
+ // 2. The slice must be consecutive in the provider's hash chain — omission shows as a seam.
233
+ for (let i = 1; i < sorted.length; i++) {
234
+ if (sorted[i]!.prev !== receiptHash(sorted[i - 1]!)) {
235
+ breaches.push({
236
+ kind: 'INCOMPLETE_RECORD',
237
+ detail: `chain break between receipts #${i - 1} and #${i} — the slice is not the provider's consecutive record`,
238
+ receipt: receiptHash(sorted[i]!),
239
+ });
240
+ }
241
+ }
242
+
243
+ // 3. Measure commitments on the in-window, in-scope receipts.
244
+ const matching = sorted.filter((r) => {
245
+ const t = Date.parse(r.ts);
246
+ return t >= winStart && t <= winEnd && scopeCovers(b.scope, r.target);
247
+ });
248
+ const c = b.commitments;
249
+ if (c.min_actions !== undefined && matching.length < c.min_actions) {
250
+ breaches.push({ kind: 'TOO_FEW_ACTIONS', detail: `${matching.length} matching actions < committed minimum ${c.min_actions}` });
251
+ }
252
+ if (c.max_actions !== undefined && matching.length > c.max_actions) {
253
+ breaches.push({ kind: 'TOO_MANY_ACTIONS', detail: `${matching.length} matching actions > committed maximum ${c.max_actions}` });
254
+ }
255
+
256
+ let maxGap: number | null = null;
257
+ if (matching.length > 0) {
258
+ const times = matching.map((r) => Date.parse(r.ts));
259
+ const gaps: Array<{ ms: number; after?: Receipt }> = [{ ms: times[0]! - winStart }];
260
+ for (let i = 1; i < times.length; i++) gaps.push({ ms: times[i]! - times[i - 1]!, after: matching[i - 1] });
261
+ if (asOf > times[times.length - 1]!) gaps.push({ ms: asOf - times[times.length - 1]!, after: matching[matching.length - 1] });
262
+ maxGap = Math.max(...gaps.map((g) => g.ms));
263
+ if (c.max_gap_ms !== undefined) {
264
+ for (const g of gaps) {
265
+ if (g.ms > c.max_gap_ms) {
266
+ breaches.push({
267
+ kind: 'MAX_GAP_EXCEEDED',
268
+ detail: `${g.ms}ms of silence > committed max ${c.max_gap_ms}ms`,
269
+ ...(g.after ? { receipt: receiptHash(g.after) } : {}),
270
+ });
271
+ }
272
+ }
273
+ }
274
+ } else if (c.max_gap_ms !== undefined && asOf - winStart > c.max_gap_ms) {
275
+ breaches.push({ kind: 'MAX_GAP_EXCEEDED', detail: `no matching actions for ${asOf - winStart}ms > committed max ${c.max_gap_ms}ms` });
276
+ }
277
+
278
+ return { ok: breaches.length === 0, breaches, metrics: { actions: matching.length, max_gap_ms: maxGap } };
279
+ }