@byollm/protocol 0.1.0-alpha.9 → 0.1.0-alpha.91

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/dist/index.js CHANGED
@@ -1,10 +1,198 @@
1
- // src/audience.ts
1
+ // src/wire.ts
2
+ import { z as z9 } from "zod";
3
+
4
+ // src/keys.ts
5
+ import {
6
+ createHash,
7
+ createPrivateKey,
8
+ createPublicKey,
9
+ generateKeyPairSync,
10
+ sign,
11
+ verify
12
+ } from "crypto";
13
+ import { z } from "zod";
14
+ var PublicIdentity = z.object({
15
+ /** Raw Ed25519 public key. The pinned one. */
16
+ identity: z.string().min(1),
17
+ /** Raw X25519 public key, for sealing to this party. */
18
+ encryption: z.string().min(1),
19
+ /**
20
+ * Ed25519 signature over the encryption key, by the identity key.
21
+ *
22
+ * This is what stops an upstream substituting an encryption key of its
23
+ * own while relaying a genuine identity: the receiver pins the identity
24
+ * and refuses any encryption key not signed by it.
25
+ */
26
+ encryptionSig: z.string().min(1)
27
+ }).strict();
28
+ var StoredKeys = z.object({
29
+ version: z.literal(1),
30
+ identityPublic: z.string().min(1),
31
+ identityPrivate: z.string().min(1),
32
+ encryptionPublic: z.string().min(1),
33
+ encryptionPrivate: z.string().min(1),
34
+ encryptionSig: z.string().min(1),
35
+ createdAt: z.number().int().positive()
36
+ }).strict();
37
+ var ENCRYPTION_KEY_CONTEXT = "byollm/v1/encryption-key";
38
+ function rawPublic(key) {
39
+ const jwk = key.export({ format: "jwk" });
40
+ const x = jwk.x;
41
+ if (typeof x !== "string") throw new Error("key has no raw public component");
42
+ return x;
43
+ }
44
+ function importPublic(raw, crv) {
45
+ return createPublicKey({ key: { kty: "OKP", crv, x: raw }, format: "jwk" });
46
+ }
47
+ function importPrivate(stored) {
48
+ return createPrivateKey({
49
+ key: Buffer.from(stored, "base64"),
50
+ type: "pkcs8",
51
+ format: "der"
52
+ });
53
+ }
54
+ var exportPrivate = (key) => key.export({ type: "pkcs8", format: "der" }).toString("base64");
55
+ function generateKeys(now) {
56
+ const identity = generateKeyPairSync("ed25519");
57
+ const encryption = generateKeyPairSync("x25519");
58
+ const encryptionPublic = rawPublic(encryption.publicKey);
59
+ return {
60
+ version: 1,
61
+ identityPublic: rawPublic(identity.publicKey),
62
+ identityPrivate: exportPrivate(identity.privateKey),
63
+ encryptionPublic,
64
+ encryptionPrivate: exportPrivate(encryption.privateKey),
65
+ encryptionSig: sign(
66
+ null,
67
+ Buffer.from(`${ENCRYPTION_KEY_CONTEXT}:${encryptionPublic}`),
68
+ identity.privateKey
69
+ ).toString("base64url"),
70
+ createdAt: now
71
+ };
72
+ }
73
+ function publicIdentityOf(keys) {
74
+ return {
75
+ identity: keys.identityPublic,
76
+ encryption: keys.encryptionPublic,
77
+ encryptionSig: keys.encryptionSig
78
+ };
79
+ }
80
+ function verifyPublicIdentity(identity) {
81
+ try {
82
+ return verify(
83
+ null,
84
+ Buffer.from(`${ENCRYPTION_KEY_CONTEXT}:${identity.encryption}`),
85
+ importPublic(identity.identity, "Ed25519"),
86
+ Buffer.from(identity.encryptionSig, "base64url")
87
+ );
88
+ } catch {
89
+ return false;
90
+ }
91
+ }
92
+ function signWith(keys, data) {
93
+ return sign(null, data, importPrivate(keys.identityPrivate)).toString(
94
+ "base64url"
95
+ );
96
+ }
97
+ function verifyWith(identityPublic, data, signature) {
98
+ try {
99
+ return verify(
100
+ null,
101
+ data,
102
+ importPublic(identityPublic, "Ed25519"),
103
+ Buffer.from(signature, "base64url")
104
+ );
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+ var ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
110
+ function fingerprint(identityPublic) {
111
+ const digest = createHash("sha256").update(Buffer.from(identityPublic, "base64url")).digest();
112
+ let bits = 0;
113
+ let value = 0;
114
+ let out = "";
115
+ for (const byte of digest.subarray(0, 15)) {
116
+ value = value << 8 | byte;
117
+ bits += 8;
118
+ while (bits >= 5) {
119
+ out += ALPHABET.charAt(value >>> bits - 5 & 31);
120
+ bits -= 5;
121
+ }
122
+ }
123
+ const groups = out.match(/.{1,4}/g) ?? [];
124
+ return `BYOLLM-${groups.join("-")}`;
125
+ }
126
+ var keyId = (identityPublic) => fingerprint(identityPublic);
127
+
128
+ // src/succession.ts
2
129
  import { z as z2 } from "zod";
130
+ var SUCCESSION_CONTEXT = "byollm/v1/site-succession";
131
+ var RETIREMENT_WINDOW_MS = 7 * 24 * 60 * 60 * 1e3;
132
+ var MAX_SUCCESSION_CHAIN = 64;
133
+ var Succession = z2.object({
134
+ /**
135
+ * The predecessor's public identity — K1, in full.
136
+ *
137
+ * The whole identity rather than the key id, because a daemon meeting a
138
+ * chain it has not seen before has to *verify* each link, and a key id is
139
+ * a fingerprint: enough to compare, never enough to check a signature.
140
+ */
141
+ identity: PublicIdentity,
142
+ /** K1's signature over the statement naming K1 and its successor. */
143
+ signature: z2.string().min(1)
144
+ }).strict();
145
+ function successionStatement(fromKeyId, toKeyId) {
146
+ return Buffer.from(`${SUCCESSION_CONTEXT}:${fromKeyId}:${toKeyId}`);
147
+ }
148
+ function signSuccession(previous, next) {
149
+ return {
150
+ identity: {
151
+ identity: previous.identityPublic,
152
+ encryption: previous.encryptionPublic,
153
+ encryptionSig: previous.encryptionSig
154
+ },
155
+ signature: signWith(
156
+ previous,
157
+ successionStatement(keyId(previous.identityPublic), keyId(next.identity))
158
+ )
159
+ };
160
+ }
161
+ function verifyLink(link, toKeyId) {
162
+ if (!verifyPublicIdentity(link.identity)) return false;
163
+ return verifyWith(
164
+ link.identity.identity,
165
+ successionStatement(keyId(link.identity.identity), toKeyId),
166
+ link.signature
167
+ );
168
+ }
169
+ function walkSuccession(input) {
170
+ const { current, chain, approved } = input;
171
+ if (chain.length === 0) return { path: [current], failure: "no-chain" };
172
+ if (chain.length > MAX_SUCCESSION_CHAIN)
173
+ return { path: [current], failure: "too-long" };
174
+ const steps = [...chain].reverse();
175
+ const path = [current];
176
+ let succeeding = current;
177
+ for (const link of steps) {
178
+ if (!verifyLink(link, succeeding)) return { path, failure: "broken-link" };
179
+ const previous = keyId(link.identity.identity);
180
+ path.unshift(previous);
181
+ if (approved(previous)) return { path, from: previous };
182
+ succeeding = previous;
183
+ }
184
+ return { path, failure: "unknown-origin" };
185
+ }
186
+
187
+ // src/audience.ts
188
+ import { z as z4 } from "zod";
3
189
 
4
190
  // src/backends.ts
5
- import { z } from "zod";
6
- var BackendClass = z.enum(["http", "process"]);
7
- var BackendCost = z.enum(["free", "metered", "subscription"]);
191
+ import { isIP } from "net";
192
+ import { z as z3 } from "zod";
193
+ var BackendClass = z3.enum(["http", "process"]);
194
+ var BACKEND_CLASSES = Object.freeze(BackendClass.options);
195
+ var BackendCost = z3.enum(["free", "metered", "subscription"]);
8
196
  var backend = (b) => Object.freeze(b);
9
197
  var BACKENDS = Object.freeze({
10
198
  // -- free: local compute, costs electricity ------------------------------
@@ -162,10 +350,28 @@ var BACKENDS = Object.freeze({
162
350
  class: "process",
163
351
  cost: "subscription",
164
352
  adversarialCorpus: "process"
353
+ }),
354
+ /**
355
+ * OpenAI's Codex CLI, on a ChatGPT plan — byollm_016 stage 3.
356
+ *
357
+ * `subscription`, so `SUBSCRIPTION_SELF_LOCK` pins it to its owner's own
358
+ * work whatever the config says. That is load-bearing here in a way it is
359
+ * not for `claude-cli`: Codex is an *agent*, and its default feature set
360
+ * includes a shell tool, browser control and computer use. The daemon
361
+ * disables every one of them, verified against the shipped binary rather
362
+ * than assumed — see `codex-cli.ts` — but the self-lock is the floor under
363
+ * that verification rather than a duplicate of it.
364
+ */
365
+ "codex-cli": backend({
366
+ id: "codex-cli",
367
+ label: "Codex CLI (your ChatGPT plan)",
368
+ class: "process",
369
+ cost: "subscription",
370
+ adversarialCorpus: "process"
165
371
  })
166
372
  });
167
373
  var BACKEND_IDS = Object.freeze(Object.keys(BACKENDS));
168
- var BackendIdSchema = z.enum(
374
+ var BackendIdSchema = z3.enum(
169
375
  BACKEND_IDS
170
376
  );
171
377
  function isBackendId(value) {
@@ -177,42 +383,93 @@ function backendDescriptor(id) {
177
383
  function isLocalHost(hostname) {
178
384
  const host = hostname.toLowerCase().replace(/^\[|\]$/g, "");
179
385
  if (host === "localhost" || host.endsWith(".localhost")) return true;
180
- if (host === "::1") return true;
386
+ const version = isIP(host);
387
+ if (version === 0) return false;
388
+ if (version === 6) {
389
+ if (host === "::1") return true;
390
+ return /^f[cd]/.test(host);
391
+ }
181
392
  if (host.startsWith("127.")) return true;
182
393
  if (host.startsWith("10.")) return true;
183
394
  if (host.startsWith("192.168.")) return true;
184
- if (/^172\.(1[6-9]|2\d|3[01])\./.test(host)) return true;
185
- if (/^f[cd]/.test(host)) return true;
186
- return false;
395
+ return /^172\.(1[6-9]|2\d|3[01])\./.test(host);
187
396
  }
188
- function resolveCost(id, baseUrl) {
397
+ function isCloudTaggedModel(model) {
398
+ return /:[^:]*cloud$/.test(model);
399
+ }
400
+ function resolveCost(id, baseUrl, model) {
401
+ return classifyCost(id, baseUrl, model).cost;
402
+ }
403
+ function backendName(id) {
404
+ return BACKENDS[id].label.replace(/\s*\([^)]*\)$/, "");
405
+ }
406
+ function classifyCost(id, baseUrl, model) {
189
407
  const declared = BACKENDS[id].cost;
190
- if (declared !== null) return declared;
191
- if (baseUrl === void 0) return "metered";
408
+ if (declared === "free" && model !== void 0 && isCloudTaggedModel(model)) {
409
+ return {
410
+ cost: "metered",
411
+ because: `its model tag ends in \`:cloud\`, so the work runs on your provider's cloud account rather than on this machine \u2014 ${backendName(id)} serves hosted models through the same local address as local ones`
412
+ };
413
+ }
414
+ if (declared !== null) {
415
+ const label = BACKENDS[id].label;
416
+ return {
417
+ cost: declared,
418
+ because: {
419
+ subscription: `${label} runs on an account you subscribe to`,
420
+ metered: `${label} bills per token`,
421
+ free: `${label} runs on this machine`
422
+ }[declared]
423
+ };
424
+ }
425
+ if (model !== void 0 && isCloudTaggedModel(model)) {
426
+ return {
427
+ cost: "metered",
428
+ because: `its model tag ends in \`:cloud\`, so the work runs on your provider's cloud account rather than on this machine`
429
+ };
430
+ }
431
+ if (baseUrl === void 0) {
432
+ return {
433
+ cost: "metered",
434
+ because: "it has no address, so where the work runs cannot be checked"
435
+ };
436
+ }
192
437
  try {
193
- return isLocalHost(new URL(baseUrl).hostname) ? "free" : "metered";
438
+ return isLocalHost(new URL(baseUrl).hostname) ? { cost: "free", because: "it runs on this machine" } : {
439
+ cost: "metered",
440
+ because: "its address is not on this machine, so the work leaves it"
441
+ };
194
442
  } catch {
195
- return "metered";
443
+ return {
444
+ cost: "metered",
445
+ because: "its address cannot be read, so where the work runs is unknown"
446
+ };
196
447
  }
197
448
  }
198
449
 
199
450
  // src/audience.ts
200
- var Audience = z2.enum(["self", "named", "public"]);
201
- var OfferScope = z2.enum(["self", "named", "public"]);
451
+ var Audience = z4.enum(["private", "team"]);
452
+ var OfferScope = z4.enum(["private", "team"]);
202
453
  var AUDIENCES = Object.freeze(Audience.options);
203
454
  var OFFER_SCOPES = Object.freeze(OfferScope.options);
204
- var MatchRefusal = z2.enum([
455
+ var MatchRefusal = z4.enum([
205
456
  /** The daemon advertises no capability for this kind. */
206
457
  "no-capability",
207
- /** Job is `self` but this daemon belongs to a different user. */
458
+ /** Job is `private` but this daemon belongs to a different user. */
208
459
  "audience-self-other-owner",
209
- /** Job is `named` but this daemon's local allowlist does not admit the owner. */
460
+ /**
461
+ * Job is `team` and nothing this device verified admits the job's owner.
462
+ *
463
+ * The id predates the grant and is kept, because ids are public and cited
464
+ * by conformance output. What it means has not moved: this device was not
465
+ * shown anything it could check.
466
+ */
210
467
  "not-locally-allowed",
211
- /** Job is `named`/`public` but the server's own allowlist excludes this runner. */
468
+ /** Job is `team` but the server's own allowlist excludes this runner. */
212
469
  "not-in-server-allowlist",
213
- /** The backend offers only `self` and the job belongs to someone else. */
470
+ /** The service offers only `private` and the job belongs to someone else. */
214
471
  "offer-scope-too-narrow",
215
- /** The matched backend is subscription-class, which is locked to `self`. */
472
+ /** The matched backend is subscription-class, which is locked to `private`. */
216
473
  "subscription-self-lock",
217
474
  /** The backend spends the owner's money and they have not agreed to share it. */
218
475
  "metered-no-spend-consent",
@@ -222,16 +479,16 @@ var MatchRefusal = z2.enum([
222
479
  var ALLOWED = Object.freeze({ ok: true });
223
480
  var refuse = (refusal) => Object.freeze({ ok: false, refusal });
224
481
  function effectiveOfferScope(configured, cost, spend) {
225
- if (cost === "subscription") return "self";
226
- if (cost === "metered" && spend?.acknowledged !== true) return "self";
482
+ if (cost === "subscription") return "private";
483
+ if (cost === "metered" && spend?.acknowledged !== true) return "private";
227
484
  return configured;
228
485
  }
229
486
  function matchAudience(job, daemon) {
230
487
  const sameOwner = job.owner === daemon.owner;
231
- if (job.audience === "self" && !sameOwner) {
488
+ if (job.audience === "private" && !sameOwner) {
232
489
  return refuse("audience-self-other-owner");
233
490
  }
234
- if (job.audience === "named" && !sameOwner && job.audienceAllow !== void 0 && !job.audienceAllow.includes(daemon.owner)) {
491
+ if (job.audience === "team" && !sameOwner && job.audienceAllow !== void 0 && !job.audienceAllow.includes(daemon.owner)) {
235
492
  return refuse("not-in-server-allowlist");
236
493
  }
237
494
  const scope = effectiveOfferScope(
@@ -254,27 +511,212 @@ function matchAudience(job, daemon) {
254
511
  }
255
512
  }
256
513
  switch (scope) {
257
- case "self":
514
+ case "private":
258
515
  return refuse("offer-scope-too-narrow");
259
- case "named":
260
- return daemon.locallyAllows(job.owner) ? ALLOWED : refuse("not-locally-allowed");
261
- case "public":
262
- return ALLOWED;
516
+ case "team":
517
+ return daemon.admits(job.owner) ? ALLOWED : refuse("not-locally-allowed");
263
518
  }
264
519
  }
265
520
  var REFUSAL_MESSAGES = Object.freeze({
266
- "no-capability": "no backend on this machine is configured and healthy for that job kind",
267
- "audience-self-other-owner": "the job is private to its owner and this machine is paired to someone else",
268
- "not-locally-allowed": "the job's owner is not on this machine's allowlist (byollm allow <server> <user>)",
269
- "not-in-server-allowlist": "the app restricted this job to named runners and this machine is not one of them",
270
- "offer-scope-too-narrow": "this backend is offered to its owner only (byollm offer <backend> named|public to widen)",
521
+ "no-capability": "no backend on this device is configured and healthy for that job kind",
522
+ "audience-self-other-owner": "the job is private to its owner and this device is paired to someone else",
523
+ "not-locally-allowed": "nothing this device can verify says the job's owner may use it",
524
+ "not-in-server-allowlist": "the app restricted this job to named runners and this device is not one of them",
525
+ "offer-scope-too-narrow": "this service is offered to its owner only (`byollm offer <service> team` to widen)",
271
526
  "subscription-self-lock": "subscription-backed models run their owner's work only \u2014 this is a protocol rule, not a setting",
272
527
  "metered-no-spend-consent": "this backend bills its owner per token, and they have not agreed to spend it on other people's work",
273
528
  "metered-ceiling-reached": "this backend is shared but has reached the spend ceiling its owner set"
274
529
  });
275
530
 
531
+ // src/job.ts
532
+ import { z as z7 } from "zod";
533
+
534
+ // src/grant.ts
535
+ import { Buffer as Buffer2 } from "buffer";
536
+ import { z as z5 } from "zod";
537
+ var GRANT_MAX_AGE_MS = 12e4;
538
+ var CLOCK_SKEW_WARN_MS = 3e4;
539
+ var CLOCK_ATTRIBUTION_MS = 5e3;
540
+ var GRANT_CONTEXT = "byollm/v1/grant";
541
+ var SignedGrant = z5.object({
542
+ /**
543
+ * This grant's own id — what makes it single-use.
544
+ *
545
+ * **Not the job id, and the difference is load-bearing.** Binding
546
+ * single-use to `jobId` would refuse a legitimate retry: a claim that
547
+ * times out is re-claimed, the control plane authors a second grant for
548
+ * the same job, and a device that recorded the job id as spent would
549
+ * reject its own recovery. A fresh id per authorship replays nothing and
550
+ * retries fine.
551
+ */
552
+ grantId: z5.string().min(1),
553
+ /**
554
+ * The job this grant admits, and only this one.
555
+ *
556
+ * A grant lifted from one job and presented for another is the obvious
557
+ * attack, and this field is why it fails.
558
+ */
559
+ jobId: z5.string().min(1),
560
+ /**
561
+ * The site the work came from, **as a key id** — byollm-review 2026-08-27.
562
+ *
563
+ * This was `siteId`, holding the site's id in the control plane's
564
+ * namespace, and it was signed by the engine and read by nobody. A signed
565
+ * field nobody checks is not a weak guarantee, it is the appearance of
566
+ * one: the design says "the grant carries the site", and nothing anywhere
567
+ * compared it to anything.
568
+ *
569
+ * It could not be compared. Job ids are chosen per site, so a grant
570
+ * authored for (site A, `job_1`) satisfied every device check against a
571
+ * stub naming (site B, `job_1`) — but the device holds sites only by the
572
+ * key ids it pinned, and had no way to relate a control-plane uuid to
573
+ * one. Checking the field would have meant a lookup through the party the
574
+ * grant exists to distrust.
575
+ *
576
+ * So the namespace changes to the one the device already has, and the
577
+ * name changes with it: this is the same value as {@link JobStub.site},
578
+ * compared directly, no lookup and nothing to believe. The control-plane
579
+ * id is not carried alongside — it had no reader, and keeping an
580
+ * unchecked field beside a checked one is how this hole was dug.
581
+ */
582
+ site: z5.string().min(1),
583
+ /** Whose job it is — the person the site enqueued for. */
584
+ user: z5.string().min(1),
585
+ /**
586
+ * Whose device it is for.
587
+ *
588
+ * Passed to {@link verifyGrant} rather than read out of the document, for
589
+ * the reason every verifier here takes its subject as an argument: a
590
+ * verifier that recovered the owner from the signed bytes would accept a
591
+ * genuine grant belonging to somebody else and pass every check.
592
+ */
593
+ owner: z5.string().min(1),
594
+ /** The site purpose this job serves — byollm_016 Amendment L. */
595
+ purpose: z5.string().min(1),
596
+ /** The kind of work. */
597
+ kind: z5.string().min(1),
598
+ /**
599
+ * The service the control plane resolved this (purpose, kind) to, from
600
+ * the user's own mapping.
601
+ *
602
+ * Selection is the control plane's; **offer-consistency is the
603
+ * device's**. A device verifies it actually offers this service, at a
604
+ * scope that includes {@link user}, before running anything.
605
+ */
606
+ service: z5.string().min(1),
607
+ /** When the control plane signed it — epoch ms, the only anchor for age. */
608
+ issuedAt: z5.number().int().positive(),
609
+ /** Base64url Ed25519 over {@link grantStatement}. */
610
+ signature: z5.string().min(1)
611
+ }).strict();
612
+ var GRANT_SIGNED_FIELDS = Object.freeze(
613
+ Object.keys(SignedGrant.shape).filter((key) => key !== "signature").sort()
614
+ );
615
+ function grantStatement(claims) {
616
+ return Buffer2.from(
617
+ JSON.stringify([
618
+ GRANT_CONTEXT,
619
+ ...GRANT_SIGNED_FIELDS.map((field) => claims[field])
620
+ ]),
621
+ "utf8"
622
+ );
623
+ }
624
+ function signGrant(keys, claims) {
625
+ return { ...claims, signature: signWith(keys, grantStatement(claims)) };
626
+ }
627
+ function verifyGrant(input) {
628
+ const { grant, now } = input;
629
+ if (grant.owner !== input.owner) return "wrong-owner";
630
+ if (grant.jobId !== input.jobId) return "wrong-job";
631
+ const age = now - grant.issuedAt;
632
+ if (age < -CLOCK_SKEW_WARN_MS) return "from-the-future";
633
+ if (age > (input.maxAgeMs ?? GRANT_MAX_AGE_MS)) return "expired";
634
+ return verifyWith(
635
+ input.controlPlanePublic,
636
+ grantStatement(grant),
637
+ grant.signature
638
+ ) ? null : "bad-signature";
639
+ }
640
+
641
+ // src/json-size.ts
642
+ function jsonLength(value) {
643
+ try {
644
+ return count(value, /* @__PURE__ */ new Set());
645
+ } catch {
646
+ return void 0;
647
+ }
648
+ }
649
+ var OutOfDomain = class extends Error {
650
+ };
651
+ function bail() {
652
+ throw new OutOfDomain("not a JSON value");
653
+ }
654
+ function count(value, seen) {
655
+ if (value === null) return 4;
656
+ switch (typeof value) {
657
+ case "boolean":
658
+ return value ? 4 : 5;
659
+ // true / false
660
+ case "number":
661
+ return Number.isFinite(value) ? String(value).length : 4;
662
+ case "string":
663
+ return stringLength(value);
664
+ case "object":
665
+ break;
666
+ default:
667
+ return bail();
668
+ }
669
+ const object = value;
670
+ if (seen.has(object)) return bail();
671
+ seen.add(object);
672
+ try {
673
+ if (Array.isArray(object)) {
674
+ let total2 = 2 + Math.max(0, object.length - 1);
675
+ for (const element of object) {
676
+ total2 += element === void 0 || typeof element === "function" ? 4 : count(element, seen);
677
+ }
678
+ return total2;
679
+ }
680
+ if ("toJSON" in object) return bail();
681
+ const proto = Object.getPrototypeOf(object);
682
+ if (proto !== Object.prototype) return bail();
683
+ let total = 2;
684
+ let first = true;
685
+ for (const [key, entry] of Object.entries(object)) {
686
+ if (entry === void 0 || typeof entry === "function") continue;
687
+ total += (first ? 0 : 1) + stringLength(key) + 1 + count(entry, seen);
688
+ first = false;
689
+ }
690
+ return total;
691
+ } finally {
692
+ seen.delete(object);
693
+ }
694
+ }
695
+ function stringLength(text) {
696
+ let total = 2;
697
+ for (let index = 0; index < text.length; index += 1) {
698
+ const code = text.charCodeAt(index);
699
+ if (code === 34 || code === 92) {
700
+ total += 2;
701
+ } else if (code < 32) {
702
+ total += code === 8 || code === 9 || code === 10 || code === 12 || code === 13 ? 2 : 6;
703
+ } else if (code >= 55296 && code <= 57343) {
704
+ const paired = code <= 56319 && index + 1 < text.length && text.charCodeAt(index + 1) >= 56320 && text.charCodeAt(index + 1) <= 57343;
705
+ if (paired) {
706
+ total += 2;
707
+ index += 1;
708
+ } else {
709
+ total += 6;
710
+ }
711
+ } else {
712
+ total += 1;
713
+ }
714
+ }
715
+ return total;
716
+ }
717
+
276
718
  // src/kinds.ts
277
- import { z as z3 } from "zod";
719
+ import { z as z6 } from "zod";
278
720
  var PAYLOAD_LIMITS = Object.freeze({
279
721
  /** Max characters in any single text field. */
280
722
  maxTextChars: 1e6,
@@ -283,23 +725,36 @@ var PAYLOAD_LIMITS = Object.freeze({
283
725
  /** Max characters across the whole payload. */
284
726
  maxTotalChars: 4e6
285
727
  });
286
- var ChatMessage = z3.object({
287
- role: z3.enum(["system", "user", "assistant"]),
288
- content: z3.string().max(PAYLOAD_LIMITS.maxTextChars)
289
- });
290
- var GeneratePayload = z3.object({
291
- prompt: z3.string().min(1).max(PAYLOAD_LIMITS.maxTextChars),
292
- system: z3.string().max(PAYLOAD_LIMITS.maxTextChars).optional()
293
- }).strict();
294
- var ChatPayload = z3.object({
295
- messages: z3.array(ChatMessage).min(1).max(PAYLOAD_LIMITS.maxMessages),
296
- system: z3.string().max(PAYLOAD_LIMITS.maxTextChars).optional()
728
+ var ChatMessage = z6.object({
729
+ role: z6.enum(["system", "user", "assistant"]),
730
+ content: z6.string().max(PAYLOAD_LIMITS.maxTextChars)
297
731
  }).strict();
298
- var JobKind = z3.enum(["llm.generate", "llm.chat"]);
732
+ var GeneratePayload = z6.object({
733
+ prompt: z6.string().min(1).max(PAYLOAD_LIMITS.maxTextChars),
734
+ system: z6.string().max(PAYLOAD_LIMITS.maxTextChars).optional()
735
+ }).strict().refine(
736
+ (payload) => payload.prompt.length + (payload.system?.length ?? 0) <= PAYLOAD_LIMITS.maxTotalChars,
737
+ {
738
+ message: `payload exceeds ${String(PAYLOAD_LIMITS.maxTotalChars)} characters`
739
+ }
740
+ );
741
+ var ChatPayload = z6.object({
742
+ messages: z6.array(ChatMessage).min(1).max(PAYLOAD_LIMITS.maxMessages),
743
+ system: z6.string().max(PAYLOAD_LIMITS.maxTextChars).optional()
744
+ }).strict().refine(
745
+ (payload) => payload.messages.reduce((sum, m) => sum + m.content.length, 0) + (payload.system?.length ?? 0) <= PAYLOAD_LIMITS.maxTotalChars,
746
+ {
747
+ message: `payload exceeds ${String(PAYLOAD_LIMITS.maxTotalChars)} characters`
748
+ }
749
+ );
750
+ var JobKind = z6.enum(["llm.generate", "llm.chat"]);
299
751
  var JOB_KINDS = Object.freeze(JobKind.options);
300
- var KindedPayload = z3.discriminatedUnion("kind", [
301
- z3.object({ kind: z3.literal("llm.generate"), payload: GeneratePayload }),
302
- z3.object({ kind: z3.literal("llm.chat"), payload: ChatPayload })
752
+ var KindedPayload = z6.discriminatedUnion("kind", [
753
+ // Strict on the wrappers too. A union member that strips is a door beside
754
+ // the one that is locked: the payloads inside are strict, and an extra key
755
+ // on the envelope vanished just as quietly.
756
+ z6.object({ kind: z6.literal("llm.generate"), payload: GeneratePayload }).strict(),
757
+ z6.object({ kind: z6.literal("llm.chat"), payload: ChatPayload }).strict()
303
758
  ]);
304
759
  function isJobKind(value) {
305
760
  return JOB_KINDS.includes(value);
@@ -316,8 +771,7 @@ function payloadTextLength(kinded) {
316
771
  }
317
772
 
318
773
  // src/job.ts
319
- import { z as z4 } from "zod";
320
- var JobState = z4.enum([
774
+ var JobState = z7.enum([
321
775
  "queued",
322
776
  "claimed",
323
777
  "running",
@@ -349,7 +803,7 @@ var TRANSITIONS = Object.freeze({
349
803
  function canTransition(from, to) {
350
804
  return TRANSITIONS[from].includes(to);
351
805
  }
352
- var Lease = z4.object({
806
+ var Lease = z7.object({
353
807
  /**
354
808
  * Identifies *this* grant, not just its holder.
355
809
  *
@@ -364,40 +818,83 @@ var Lease = z4.object({
364
818
  * and release *is*, per lease, but not across leases, because nothing in
365
819
  * the request said which one.
366
820
  */
367
- id: z4.string().min(1),
821
+ id: z7.string().min(1),
368
822
  /** The runner holding the lease. */
369
- runnerId: z4.string().min(1),
823
+ runnerId: z7.string().min(1),
370
824
  /** Epoch milliseconds after which the claim is void. */
371
- expiresAt: z4.number().int().positive()
372
- });
373
- var JobPayload = z4.union([GeneratePayload, ChatPayload]);
374
- var ClaimedJob = z4.object({
375
- id: z4.string().min(1),
825
+ expiresAt: z7.number().int().positive()
826
+ }).strict();
827
+ var JobPayload = z7.union([GeneratePayload, ChatPayload]);
828
+ var ClaimedJob = z7.object({
829
+ id: z7.string().min(1),
376
830
  kind: JobKind,
377
831
  payload: JobPayload,
378
832
  audience: Audience,
379
833
  /** The app's id for the user who enqueued it. */
380
- owner: z4.string().min(1),
381
- /** Runner owners the app restricted a `named` job to, if any. */
382
- audienceAllow: z4.array(z4.string().min(1)).optional(),
834
+ owner: z7.string().min(1),
835
+ /**
836
+ * Which site's job — V1-3.
837
+ *
838
+ * The stub has always carried it; the opened job did not, so everything
839
+ * downstream of the payload — the ingress line above all — recorded a job
840
+ * id that belongs to a site without saying which. Two sites can choose
841
+ * the same id, and the meter is the product.
842
+ *
843
+ * Optional so a caller assembling a job by hand is not forced to invent
844
+ * one, and so this reads as what it is: a fact about where the work came
845
+ * from, not a second copy of the routing key.
846
+ */
847
+ site: z7.string().min(1).optional(),
848
+ /**
849
+ * Which of the owner's services runs this — resolved, not requested.
850
+ *
851
+ * The daemon picks the backend from this, so it has to be the answer
852
+ * rather than a wish. On a relayed route it is copied off the **grant**,
853
+ * where a control plane put the person's own mapping and signed it; a
854
+ * site never named it and could not.
855
+ *
856
+ * It used to be what the site asked for, which made a job that selected a
857
+ * non-default service liable to be served by the default instead — the
858
+ * substitution `NO_PAYLOAD_ROUTING` forbids. Amendment L removed the
859
+ * asking; what is left is the answering.
860
+ *
861
+ * Optional, because direct mode has no control plane to resolve anything
862
+ * and the owner's own defaults answer under the ambiguity law.
863
+ */
864
+ service: z7.string().min(1).optional(),
865
+ /**
866
+ * When the work stops being worth doing — the stub's own TTL, carried on
867
+ * so the daemon can stop at it (B199).
868
+ *
869
+ * **A third clock, and not the lease.** The lease bounds how long this
870
+ * device holds the claim; this bounds how long the answer is wanted. A box
871
+ * ground two chat jobs toward `maxWallClockMs` — ten minutes — while their
872
+ * TTL was two, holding both slots and claiming nothing the whole time.
873
+ *
874
+ * Optional because the field is carried rather than required: a caller
875
+ * assembling a `ClaimedJob` without it gets the unclamped ceiling, which is
876
+ * the behaviour that existed before. The stub always has it, and the
877
+ * runner's own call site already spread it — this makes the type say so.
878
+ */
879
+ deadlineAt: z7.number().int().positive().optional(),
383
880
  lease: Lease
384
881
  }).strict();
385
- var ResultProvenance = z4.object({
882
+ var ResultProvenance = z7.object({
386
883
  /** The audience the job ran under. */
387
884
  audience: Audience,
388
885
  /** The runner that produced it. */
389
- runnerId: z4.string().min(1),
886
+ runnerId: z7.string().min(1),
390
887
  /** The runner owner's id in this app's namespace. */
391
- runnerOwner: z4.string().min(1),
888
+ runnerOwner: z7.string().min(1),
392
889
  /** Which backend class produced it — an HTTP call or a sandboxed spawn. */
393
890
  backendClass: BackendClass,
394
891
  /** The model the runner reports having used. */
395
- model: z4.string().min(1),
892
+ model: z7.string().min(1),
396
893
  /**
397
894
  * False only for `self` jobs. When true the app MUST treat `text` as
398
895
  * untrusted third-party content.
399
896
  */
400
- untrusted: z4.boolean()
897
+ untrusted: z7.boolean()
401
898
  }).strict();
402
899
  function provenanceFor(input) {
403
900
  return {
@@ -406,38 +903,154 @@ function provenanceFor(input) {
406
903
  runnerOwner: input.runnerOwner,
407
904
  backendClass: input.backendClass,
408
905
  model: input.model,
409
- untrusted: input.audience !== "self"
906
+ untrusted: input.audience !== "private"
410
907
  };
411
908
  }
412
- var JobResultOk = z4.object({
413
- outcome: z4.literal("ok"),
414
- text: z4.string(),
909
+ var StopReasonSchema = z7.enum([
910
+ "end",
911
+ "length",
912
+ "stop-sequence",
913
+ "unknown"
914
+ ]);
915
+ var RunMetadata = z7.object({
916
+ /** Which model actually served it. */
917
+ model: z7.string().min(1),
918
+ backendClass: BackendClass,
919
+ /** Wall-clock milliseconds the backend call took. */
920
+ durationMs: z7.number().int().nonnegative(),
921
+ /**
922
+ * Why generation stopped — B064 step 4.
923
+ *
924
+ * Here rather than on {@link JobResultOk} because the outcome is the
925
+ * ANSWER and this is the daemon's signed account of how it was produced.
926
+ * Why generation ended is the same kind of fact as how long it took.
927
+ *
928
+ * **Optional because it is meaningless, not because it is new.** A
929
+ * cancelled job has no model to have stopped and an error has no
930
+ * generation to have ended, and `ran` travels on those arms too.
931
+ * Instruction 10 forbids optionality bought for compatibility — a
932
+ * version gate wearing a question mark — and this is not that: it is
933
+ * absent exactly where it would be a fact about nothing. Present on
934
+ * every `ok` result, always, because the whole value is the difference
935
+ * between `end`, `length` and `unknown` and that difference only exists
936
+ * if it is always there.
937
+ */
938
+ stop: StopReasonSchema.optional(),
939
+ /**
940
+ * Whether the adapter could read a stop signal at all — B105's lesson,
941
+ * carried to the wire.
942
+ *
943
+ * Without this the site re-commits the defect B064's third mapping kind
944
+ * was introduced to fix. `unknown` is TWO facts: an adapter that cannot
945
+ * report one, and an adapter that reported a word we do not map — and
946
+ * `openai-http` maps `stop` and `length` and nothing else, so the second
947
+ * is the common case rather than the corner.
948
+ *
949
+ * A site told only `unknown` would say "we do not know why this stopped"
950
+ * for a `claude-cli` job forever, which is true, and for a
951
+ * `content_filter` result, which is not the same thing at all.
952
+ */
953
+ stopReported: z7.boolean().optional()
954
+ }).strict();
955
+ var JobResultOk = z7.object({
956
+ outcome: z7.literal("ok"),
957
+ text: z7.string(),
415
958
  /** Optional reference to a stored artifact; never a local path. */
416
- artifactUrl: z4.url().optional()
959
+ artifactUrl: z7.url().optional()
417
960
  }).strict();
418
- var JobResultError = z4.object({
419
- outcome: z4.literal("error"),
420
- code: z4.string().min(1),
421
- message: z4.string().min(1),
961
+ var JobResultError = z7.object({
962
+ outcome: z7.literal("error"),
963
+ code: z7.string().min(1),
964
+ message: z7.string().min(1),
422
965
  /** Whether the app may reasonably re-enqueue. */
423
- retryable: z4.boolean()
966
+ retryable: z7.boolean()
424
967
  }).strict();
425
- var JobResultCanceled = z4.object({
426
- outcome: z4.literal("canceled")
968
+ var JobResultCanceled = z7.object({
969
+ outcome: z7.literal("canceled")
427
970
  }).strict();
428
- var JobOutcome = z4.discriminatedUnion("outcome", [
971
+ var JobOutcome = z7.discriminatedUnion("outcome", [
429
972
  JobResultOk,
430
973
  JobResultError,
431
974
  JobResultCanceled
432
975
  ]);
433
- var DeliveredResult = z4.object({
434
- jobId: z4.string().min(1),
976
+ var RefusalReason = z7.enum([
977
+ /**
978
+ * Two or more services answer this kind and the owner has named no default,
979
+ * so the kind is withheld. Nobody may pick on the owner's behalf — the wrong
980
+ * guess is the metered one.
981
+ *
982
+ * Told apart from its neighbour deliberately, and the line is whether a
983
+ * requester can walk a namespace. There are two kinds; asking about one
984
+ * enumerates nothing they could not learn from what the device advertises,
985
+ * and the difference is actionable — "the owner has not chosen" is fixable
986
+ * by the owner, "the default cannot serve you" is not. It is also already
987
+ * what a team member sees on the devices page: `awaitingDefault` carries
988
+ * exactly this, by kind, for exactly this reason.
989
+ */
990
+ "default-ambiguity",
991
+ /**
992
+ * A default exists and this requester can never use it — byollm_016's
993
+ * defaults-meet-audiences corner.
994
+ *
995
+ * The specimen: an owner's default for `llm.chat` is their Claude
996
+ * subscription, self-locked by `SUBSCRIPTION_SELF_LOCK`. A team member's
997
+ * job resolves to it and can never be served by it. That must be a refusal
998
+ * on the spot, not a wait that expires an hour later looking like nobody
999
+ * was online.
1000
+ *
1001
+ * Bounded like the value above, and unprobeable for the same reason: the
1002
+ * requester named nothing, so there is no name space to walk.
1003
+ */
1004
+ "default-unusable"
1005
+ ]);
1006
+ var JobRefused = z7.object({
1007
+ outcome: z7.literal("refused"),
1008
+ reason: RefusalReason,
1009
+ /** Plain words for a human reading a log, never parsed. */
1010
+ message: z7.string().min(1)
1011
+ }).strict();
1012
+ var REFUSAL_TEXT = Object.freeze({
1013
+ "default-ambiguity": "this device serves that kind from more than one service and its owner has not chosen which",
1014
+ "default-unusable": "this device's default for that kind cannot run work for you"
1015
+ });
1016
+ var SealedOutcome = z7.object({ outcome: JobOutcome, ran: RunMetadata }).strict();
1017
+ var DeliveredResult = z7.object({
1018
+ jobId: z7.string().min(1),
435
1019
  state: JobState,
436
1020
  outcome: JobOutcome.optional(),
437
- provenance: ResultProvenance.optional()
438
- }).strict();
439
- var SizeClass = z4.enum(["small", "medium", "large", "unbounded"]);
440
- var SIZE_CLASS_LIMITS = Object.freeze({
1021
+ provenance: ResultProvenance.optional(),
1022
+ /**
1023
+ * Present, and always `true`, when this did not come from a runner —
1024
+ * {@link MUSTS.FALLBACK_LABELED}.
1025
+ *
1026
+ * The app's own `onNoRunner` value produced it: a hosted model, a cached
1027
+ * answer, an apology. It never travels on the wire, because nothing on
1028
+ * the wire produced it; it exists so that a result which did not come
1029
+ * from the user's own compute cannot be reported as though it did.
1030
+ *
1031
+ * A literal rather than a boolean, so `fallback: false` is not a
1032
+ * spelling anybody can reach for. The absence of this field means a
1033
+ * runner ran the job, and the *server* stamps it — an app cannot supply
1034
+ * a substitute that hides what it is.
1035
+ */
1036
+ fallback: z7.literal(true).optional()
1037
+ }).strict();
1038
+ var SizeClass = z7.enum(["small", "medium", "large", "unbounded"]);
1039
+ var SIZE_CLASSES = Object.freeze(SizeClass.options);
1040
+ var MAX_ENVELOPE_BYTES = 6 * 1024 * 1024;
1041
+ function envelopeBytes(envelope) {
1042
+ const counted = jsonLength(envelope);
1043
+ if (counted !== void 0) return counted;
1044
+ const serialised = JSON.stringify(envelope);
1045
+ return serialised === void 0 ? 0 : serialised.length;
1046
+ }
1047
+ function describeBytes(bytes) {
1048
+ return `${(Math.ceil(bytes / (1024 * 1024) * 10) / 10).toFixed(1)} MB`;
1049
+ }
1050
+ function tooLargeMessage(input) {
1051
+ return `this message is ${describeBytes(input.bytes)} and the limit is ${describeBytes(input.limit)} \u2014 it is a limit on one message rather than on how many you send. Split the work into smaller jobs and send them separately.`;
1052
+ }
1053
+ var SIZE_CLASS_LIMITS = Object.freeze({
441
1054
  small: 4e3,
442
1055
  medium: 64e3,
443
1056
  large: Number.POSITIVE_INFINITY
@@ -451,165 +1064,119 @@ function sizeClassOf(textChars) {
451
1064
  if (textChars <= SIZE_CLASS_LIMITS.medium) return "medium";
452
1065
  return "large";
453
1066
  }
454
- var JobStub = z4.object({
455
- id: z4.string().min(1),
1067
+ var JobStub = z7.object({
1068
+ id: z7.string().min(1),
456
1069
  kind: JobKind,
457
1070
  /** The app's id for the user who enqueued it. */
458
- owner: z4.string().min(1),
1071
+ owner: z7.string().min(1),
1072
+ /**
1073
+ * Which site this job belongs to — byollm_009 Amendment A §A.3.
1074
+ *
1075
+ * **The site's identity key id**, not an id somebody assigned it. §6 has
1076
+ * listed `site` since this spec was frozen; the schema never carried it,
1077
+ * which is the drift the amendment closes.
1078
+ *
1079
+ * A key id rather than an opaque handle for one reason above the others:
1080
+ * it makes the stub *self-describing* instead of a pointer into somebody
1081
+ * else's table. A daemon holds this key id already, from pinning, so it
1082
+ * can check `stub.site` against the payload envelope's `senderKeyId`
1083
+ * without a lookup and without trusting the party that routed it. An
1084
+ * opaque id can only be believed.
1085
+ *
1086
+ * It also avoids inventing a second namespace for a thing that has a
1087
+ * canonical one — the shape of finding 41 (two owner namespaces compared
1088
+ * for equality) and of finding fourteen before it.
1089
+ *
1090
+ * Rotation is a designed transition rather than a cost: a site publishes a
1091
+ * new identity signed by the outgoing one, both are valid through an
1092
+ * overlap window, and a daemon re-keys its own map by verifying that
1093
+ * signature against the key it already pinned (§A.3.1).
1094
+ */
1095
+ site: z7.string().min(1),
459
1096
  audience: Audience,
460
- audienceAllow: z4.array(z4.string().min(1)).optional(),
1097
+ // `audienceAllow` is **not** here, and its absence is the enforcement —
1098
+ // cloud_008 §0.2.
1099
+ //
1100
+ // It was a list of the people who may run a job, travelling to every
1101
+ // routing party on every shared job. byollm_001 Rev 1 §B settled who
1102
+ // decides that long before this schema existed: *the daemon's own list
1103
+ // decides, not the server's*, and `allowlist.predicateFor(origin)` is the
1104
+ // enforcement in both lanes. So this was a second answer to a question the
1105
+ // daemon already owned — able only to agree, in which case it was
1106
+ // redundant, or to disagree, in which case nothing said which wins.
1107
+ //
1108
+ // The rule it leaves behind, which decides the next field too: **a class
1109
+ // the router acts on may travel; membership never does.** `audience` stays
1110
+ // for exactly that reason — the relay narrows on it. A roster does not
1111
+ // travel, so `ROSTER_NOT_DISCLOSED` holds here by absence, which is the
1112
+ // strongest way for a MUST to hold.
1113
+ //
1114
+ // The site keeps its own copy on `JobRecord` and still filters candidates
1115
+ // with it before offering. That is server-internal, where the party
1116
+ // holding the list authored it.
1117
+ /**
1118
+ * Which of the site's declared purposes this job serves — Amendment L.
1119
+ *
1120
+ * **A need, never a name.** The site's vocabulary is its own purposes;
1121
+ * the person's is their services; and the two never meet. This field says
1122
+ * "writing-assistant", and a control plane joins it to whatever that
1123
+ * person mapped it to. The site learns only whether the slot was
1124
+ * satisfiable.
1125
+ *
1126
+ * It replaced `service`, which let a site name one of the owner's
1127
+ * services directly. That field is gone from both routes (Amendment L
1128
+ * rider) and its refusal machinery with it — including the collapsed
1129
+ * `select-unavailable`, which existed so that "no such service" and "not
1130
+ * offered to you" could not be told apart. There is nothing left to
1131
+ * probe: **a vocabulary that never crosses the boundary cannot be
1132
+ * enumerated across it**, which is a stronger guarantee than the one the
1133
+ * collapse gave.
1134
+ *
1135
+ * It travels for the reason the absent `audienceAllow` establishes: *a
1136
+ * class the router acts on may travel; membership never does.* A purpose
1137
+ * is a class, and the control plane acts on it.
1138
+ *
1139
+ * Optional because direct mode has no control plane to hold a mapping and
1140
+ * is kind-only: the owner's own config and defaults answer, under the
1141
+ * ambiguity law as shipped. Absent on a relayed route resolves against
1142
+ * the site's reserved purpose, which a site that declared its own
1143
+ * purposes will not have mapped — so the slot reads as unmapped and the
1144
+ * site falls back, loudly enough and without a special case.
1145
+ *
1146
+ * A **stub** field and never a payload field, which is the line
1147
+ * `NO_PAYLOAD_ROUTING` draws: the prompt cannot reach it, so no amount of
1148
+ * user text can influence what runs.
1149
+ */
1150
+ purpose: z7.string().min(1).optional(),
461
1151
  sizeClass: SizeClass,
462
1152
  /** Reserved for byollm_006. False until streaming exists. */
463
- streaming: z4.boolean(),
1153
+ streaming: z7.boolean(),
464
1154
  /** Epoch ms after which the work is pointless; bounds ciphertext retention. */
465
- deadlineAt: z4.number().int().positive()
1155
+ deadlineAt: z7.number().int().positive()
1156
+ }).strict();
1157
+ var ClaimedStub = JobStub.extend({
1158
+ lease: Lease,
1159
+ grant: SignedGrant.optional()
466
1160
  }).strict();
467
- var ClaimedStub = JobStub.extend({ lease: Lease }).strict();
468
1161
 
469
1162
  // src/envelope.ts
470
1163
  import { createPrivateKey as createPrivateKey2, createPublicKey as createPublicKey2 } from "crypto";
471
1164
  import sodium from "libsodium-wrappers";
472
- import { z as z6 } from "zod";
473
-
474
- // src/keys.ts
475
- import {
476
- createHash,
477
- createPrivateKey,
478
- createPublicKey,
479
- generateKeyPairSync,
480
- sign,
481
- verify
482
- } from "crypto";
483
- import { z as z5 } from "zod";
484
- var PublicIdentity = z5.object({
485
- /** Raw Ed25519 public key. The pinned one. */
486
- identity: z5.string().min(1),
487
- /** Raw X25519 public key, for sealing to this party. */
488
- encryption: z5.string().min(1),
489
- /**
490
- * Ed25519 signature over the encryption key, by the identity key.
491
- *
492
- * This is what stops an upstream substituting an encryption key of its
493
- * own while relaying a genuine identity: the receiver pins the identity
494
- * and refuses any encryption key not signed by it.
495
- */
496
- encryptionSig: z5.string().min(1)
497
- }).strict();
498
- var StoredKeys = z5.object({
499
- version: z5.literal(1),
500
- identityPublic: z5.string().min(1),
501
- identityPrivate: z5.string().min(1),
502
- encryptionPublic: z5.string().min(1),
503
- encryptionPrivate: z5.string().min(1),
504
- encryptionSig: z5.string().min(1),
505
- createdAt: z5.number().int().positive()
506
- }).strict();
507
- var ENCRYPTION_KEY_CONTEXT = "byollm/v1/encryption-key";
508
- function rawPublic(key) {
509
- const jwk = key.export({ format: "jwk" });
510
- const x = jwk.x;
511
- if (typeof x !== "string") throw new Error("key has no raw public component");
512
- return x;
513
- }
514
- function importPublic(raw, crv) {
515
- return createPublicKey({ key: { kty: "OKP", crv, x: raw }, format: "jwk" });
516
- }
517
- function importPrivate(stored) {
518
- return createPrivateKey({
519
- key: Buffer.from(stored, "base64"),
520
- type: "pkcs8",
521
- format: "der"
522
- });
523
- }
524
- var exportPrivate = (key) => key.export({ type: "pkcs8", format: "der" }).toString("base64");
525
- function generateKeys(now) {
526
- const identity = generateKeyPairSync("ed25519");
527
- const encryption = generateKeyPairSync("x25519");
528
- const encryptionPublic = rawPublic(encryption.publicKey);
529
- return {
530
- version: 1,
531
- identityPublic: rawPublic(identity.publicKey),
532
- identityPrivate: exportPrivate(identity.privateKey),
533
- encryptionPublic,
534
- encryptionPrivate: exportPrivate(encryption.privateKey),
535
- encryptionSig: sign(
536
- null,
537
- Buffer.from(`${ENCRYPTION_KEY_CONTEXT}:${encryptionPublic}`),
538
- identity.privateKey
539
- ).toString("base64url"),
540
- createdAt: now
541
- };
542
- }
543
- function publicIdentityOf(keys) {
544
- return {
545
- identity: keys.identityPublic,
546
- encryption: keys.encryptionPublic,
547
- encryptionSig: keys.encryptionSig
548
- };
549
- }
550
- function verifyPublicIdentity(identity) {
551
- try {
552
- return verify(
553
- null,
554
- Buffer.from(`${ENCRYPTION_KEY_CONTEXT}:${identity.encryption}`),
555
- importPublic(identity.identity, "Ed25519"),
556
- Buffer.from(identity.encryptionSig, "base64url")
557
- );
558
- } catch {
559
- return false;
560
- }
561
- }
562
- function signWith(keys, data) {
563
- return sign(null, data, importPrivate(keys.identityPrivate)).toString(
564
- "base64url"
565
- );
566
- }
567
- function verifyWith(identityPublic, data, signature) {
568
- try {
569
- return verify(
570
- null,
571
- data,
572
- importPublic(identityPublic, "Ed25519"),
573
- Buffer.from(signature, "base64url")
574
- );
575
- } catch {
576
- return false;
577
- }
578
- }
579
- var ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
580
- function fingerprint(identityPublic) {
581
- const digest = createHash("sha256").update(Buffer.from(identityPublic, "base64url")).digest();
582
- let bits = 0;
583
- let value = 0;
584
- let out = "";
585
- for (const byte of digest.subarray(0, 15)) {
586
- value = value << 8 | byte;
587
- bits += 8;
588
- while (bits >= 5) {
589
- out += ALPHABET.charAt(value >>> bits - 5 & 31);
590
- bits -= 5;
591
- }
592
- }
593
- const groups = out.match(/.{1,4}/g) ?? [];
594
- return `BYOLLM-${groups.join("-")}`;
595
- }
596
- var keyId = (identityPublic) => fingerprint(identityPublic);
597
-
598
- // src/envelope.ts
1165
+ import { z as z8 } from "zod";
599
1166
  var readied;
600
1167
  async function cryptoReady() {
601
1168
  readied ??= sodium.ready;
602
1169
  await readied;
603
1170
  }
604
1171
  var ENVELOPE_MAX_AGE_MS = 24 * 60 * 6e4;
605
- var EnvelopeDirection = z6.enum(["payload", "result"]);
606
- var SealedEnvelope = z6.object({
1172
+ var EnvelopeDirection = z8.enum(["payload", "result"]);
1173
+ var SealedEnvelope = z8.object({
607
1174
  /** Base64url `crypto_box_seal` output over the signed plaintext. */
608
- ciphertext: z6.string().min(1),
1175
+ ciphertext: z8.string().min(1),
609
1176
  /** Who this was sealed to — the recipient checks it is them. */
610
- recipientKeyId: z6.string().min(1),
1177
+ recipientKeyId: z8.string().min(1),
611
1178
  /** Who signed it — the recipient checks this against its pin. */
612
- senderKeyId: z6.string().min(1),
1179
+ senderKeyId: z8.string().min(1),
613
1180
  direction: EnvelopeDirection,
614
1181
  /**
615
1182
  * When this ciphertext stops being worth keeping.
@@ -623,7 +1190,7 @@ var SealedEnvelope = z6.object({
623
1190
  * Not trusted as written: it is also inside the signature, so a changed
624
1191
  * deadline fails to verify.
625
1192
  */
626
- deadlineAt: z6.number().int().positive()
1193
+ deadlineAt: z8.number().int().positive()
627
1194
  }).strict();
628
1195
  function signedBody(context, plaintext) {
629
1196
  return Buffer.from(
@@ -710,23 +1277,855 @@ async function open(input) {
710
1277
  if (claims["jobId"] !== expected.jobId || claims["senderKeyId"] !== expected.senderKeyId || claims["recipientKeyId"] !== expected.recipientKeyId || claims["deadlineAt"] !== envelope.deadlineAt || claims["direction"] !== expected.direction) {
711
1278
  return { ok: false, reason: "context-mismatch" };
712
1279
  }
713
- if (typeof claims["plaintext"] !== "string") {
714
- return { ok: false, reason: "malformed" };
1280
+ if (typeof claims["plaintext"] !== "string") {
1281
+ return { ok: false, reason: "malformed" };
1282
+ }
1283
+ return { ok: true, plaintext: claims["plaintext"] };
1284
+ }
1285
+
1286
+ // src/wire.ts
1287
+ var PROTOCOL_VERSION = "1";
1288
+ var SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
1289
+ PROTOCOL_VERSION
1290
+ ]);
1291
+ var MIN_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0] ?? PROTOCOL_VERSION;
1292
+ function declaredVersion(input) {
1293
+ const { body, query } = input;
1294
+ if (typeof body === "object" && body !== null && Object.hasOwn(body, "protocolVersion")) {
1295
+ return body.protocolVersion;
1296
+ }
1297
+ return query?.get("protocolVersion") ?? void 0;
1298
+ }
1299
+ function checkProtocolVersion(body) {
1300
+ const declared = typeof body === "object" && body !== null && Object.hasOwn(body, "protocolVersion") ? body.protocolVersion : void 0;
1301
+ if (typeof declared !== "string" || declared.length === 0) {
1302
+ return {
1303
+ error: "unsupported-protocol-version",
1304
+ message: `this request declared no protocol version. Upgrade the daemon: \`${UPGRADE_COMMAND}\`.`,
1305
+ supported: SUPPORTED_PROTOCOL_VERSIONS,
1306
+ minimum: MIN_PROTOCOL_VERSION
1307
+ };
1308
+ }
1309
+ if (!SUPPORTED_PROTOCOL_VERSIONS.includes(declared)) {
1310
+ return {
1311
+ error: "unsupported-protocol-version",
1312
+ message: `this server speaks protocol ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")} and the daemon asked for ${declared}. ` + (declared < MIN_PROTOCOL_VERSION ? `Upgrade the daemon: \`${UPGRADE_COMMAND}\`.` : "This daemon is newer than the server; the server needs upgrading."),
1313
+ supported: SUPPORTED_PROTOCOL_VERSIONS,
1314
+ minimum: MIN_PROTOCOL_VERSION
1315
+ };
1316
+ }
1317
+ return null;
1318
+ }
1319
+ var UPGRADE_COMMAND = "npm i -g byollm@latest";
1320
+ var PROTOCOL_PREFIX = "/byollm";
1321
+ var ENDPOINTS = Object.freeze([
1322
+ "pair",
1323
+ "claim",
1324
+ "fetch",
1325
+ "heartbeat",
1326
+ "result",
1327
+ "release"
1328
+ ]);
1329
+ var Capability = z9.object({
1330
+ kind: JobKind,
1331
+ /**
1332
+ * The owner's name for the service answering this kind — byollm_016.
1333
+ *
1334
+ * A device advertises *which* of its services serves a kind, not merely
1335
+ * that something does. **A site never sees this**, and never did after
1336
+ * Amendment L: it is what a control plane resolves a person's mapping
1337
+ * against, so that the service a grant names is one this device actually
1338
+ * offers rather than one somebody invented.
1339
+ *
1340
+ * `isDefault` used to sit beside it, saying which row an unselected job
1341
+ * took. Nothing selects any more — a job names a purpose and a person's
1342
+ * mapping names a service — so there is no unselected job for a default
1343
+ * to catch, and the field went with the machinery it served.
1344
+ */
1345
+ service: z9.string().min(1),
1346
+ backendId: BackendIdSchema,
1347
+ backendClass: BackendClass,
1348
+ model: z9.string().min(1),
1349
+ /**
1350
+ * Models this device's CLI knows about — byollm_017 ruling 3.
1351
+ *
1352
+ * **Suggestions, not a vocabulary.** Free text is always allowed: the
1353
+ * promise is that a model released this morning works this morning, and a
1354
+ * frozen list anywhere a person picks from breaks that on the first day
1355
+ * it matters. What makes free text safe is ruling 2 — a model is probed
1356
+ * before it is stored, so "found is not works" is answered by the device
1357
+ * rather than by a list.
1358
+ *
1359
+ * Announced with the capability rather than kept in the dashboard,
1360
+ * because the answer is "what does THIS device's CLI know" and only the
1361
+ * device can say. A list held cloud-side would be one more thing to
1362
+ * update on release day, and wrong for anybody who had not upgraded.
1363
+ *
1364
+ * Optional, and empty is legal. A backend with nothing to suggest — a
1365
+ * local server serving one model — is not a backend in an error state,
1366
+ * and a reader must not render an absent list as "no models available".
1367
+ */
1368
+ knownModels: z9.array(z9.string().min(1)).optional(),
1369
+ offerScope: OfferScope
1370
+ }).strict();
1371
+ var CapabilityMatrix = z9.array(Capability);
1372
+ var WithheldKind = z9.object({
1373
+ kind: JobKind,
1374
+ claimants: z9.array(
1375
+ z9.object({ service: z9.string().min(1), offer: OfferScope }).strict()
1376
+ ).min(2)
1377
+ }).strict();
1378
+ var GrantRef = z9.object({ jobId: z9.string().min(1), leaseId: z9.string().min(1) }).strict();
1379
+ var PairStartRequest = z9.object({
1380
+ protocolVersion: z9.literal(PROTOCOL_VERSION),
1381
+ action: z9.literal("start"),
1382
+ daemon: z9.object({
1383
+ version: z9.string().min(1),
1384
+ /** Shown in the app's runner list so a user can tell their machines apart. */
1385
+ label: z9.string().min(1).max(120),
1386
+ platform: z9.enum(["darwin", "linux", "win32"])
1387
+ }).strict(),
1388
+ /**
1389
+ * This machine's public keys (byollm_009 §5).
1390
+ *
1391
+ * Pairing is where the two parties learn each other's identities, because
1392
+ * it is the one moment a human is already deciding to trust: the approval
1393
+ * click. A key exchanged anywhere else would be a key nobody chose.
1394
+ */
1395
+ device: PublicIdentity,
1396
+ capabilities: CapabilityMatrix
1397
+ }).strict();
1398
+ var PairStartResponse = z9.object({
1399
+ /** Secret the daemon polls with. Never shown to the user. */
1400
+ deviceCode: z9.string().min(20),
1401
+ /** Short code the user reads and confirms in the browser. */
1402
+ userCode: z9.string().min(4).max(16),
1403
+ /** Where the user approves. Must be on the server's own origin. */
1404
+ verificationUrl: z9.url(),
1405
+ /** Epoch ms after which the code is dead ({@link MUSTS.PAIR_CODE_EXPIRES}). */
1406
+ expiresAt: z9.number().int().positive(),
1407
+ /** How often the daemon may poll. */
1408
+ pollIntervalMs: z9.number().int().min(500).max(6e4)
1409
+ }).strict();
1410
+ var PairPollRequest = z9.object({
1411
+ protocolVersion: z9.literal(PROTOCOL_VERSION),
1412
+ action: z9.literal("poll"),
1413
+ deviceCode: z9.string().min(20)
1414
+ }).strict();
1415
+ var PairPollResponse = z9.discriminatedUnion("status", [
1416
+ z9.object({ status: z9.literal("pending") }).strict(),
1417
+ z9.object({ status: z9.literal("denied") }).strict(),
1418
+ z9.object({ status: z9.literal("expired") }).strict(),
1419
+ z9.object({
1420
+ status: z9.literal("approved"),
1421
+ // `runnerToken` is gone — cloud_008 §2.4, finding 37.
1422
+ //
1423
+ // It was minted here, hashed into `RunnerRecord.tokenHash`, written to
1424
+ // the daemon's pairings file, and then **never sent, never looked up
1425
+ // and never compared**. `getRunnerByTokenHash` existed on both stores
1426
+ // and was called by nothing but a test asserting it returns null.
1427
+ //
1428
+ // Not merely dead wire, which is what `audienceAllow` and
1429
+ // `HeartbeatResponse.leases` were. This was a *secret*: minted,
1430
+ // transmitted, and written to two disks at rest, for nothing. A
1431
+ // credential with no purpose is a liability rather than clutter,
1432
+ // because the only thing it can ever do is leak.
1433
+ //
1434
+ // `REQUESTS_SIGNED_NOT_BEARER` was already the rule and was already
1435
+ // enforced — every authenticated call is signed by the device's pinned
1436
+ // identity key. This removes the thing the MUST is named after.
1437
+ runnerId: z9.string().min(1),
1438
+ /** The app's id for the approving user — this daemon's owner forever. */
1439
+ owner: z9.string().min(1),
1440
+ /** Display name for the trust UI, if the app offers one. */
1441
+ ownerLabel: z9.string().optional(),
1442
+ /**
1443
+ * The sites this pairing covers, for the daemon to pin (byollm_009 §5),
1444
+ * keyed by each site's identity key id — cloud_009 §5.
1445
+ *
1446
+ * Returned only on approval: a pending or denied poll learns nothing,
1447
+ * so an unapproved code cannot be used to enumerate a site's keys.
1448
+ *
1449
+ * **One pairing per upstream, not one per site.** A user who connects a
1450
+ * site on a web dashboard has no reason to go back to a laptop and run
1451
+ * a command, so which sites a pairing covers is a projection of consent
1452
+ * — refreshed on the heartbeat — rather than something frozen at
1453
+ * pairing. A direct site answers with exactly one entry, which is the
1454
+ * same shape and not a special case.
1455
+ *
1456
+ * Keyed by the id `stub.site` carries (Amendment A §A.3), so the
1457
+ * runner's lookup is a map read rather than a join across two
1458
+ * namespaces.
1459
+ */
1460
+ sites: z9.record(z9.string().min(1), PublicIdentity),
1461
+ /**
1462
+ * The control plane's grant-signing key, pinned here — Amendment J.
1463
+ *
1464
+ * **Pairing is when, and that is the whole question.** Pairing is
1465
+ * already the ceremony where an owner proves out of band that this
1466
+ * device is theirs, so a key learned here rides trust that has already
1467
+ * happened. The rejected alternative is trust-on-first-grant, and it is
1468
+ * rejected because it hands the decision back to the relay: a daemon
1469
+ * that learns whose signature to trust from the first grant to arrive
1470
+ * has its admission authority chosen by whoever controls delivery.
1471
+ *
1472
+ * Optional on the wire, and only on the wire: a direct-mode server has
1473
+ * no control plane and signs nothing, and a daemon that receives no key
1474
+ * serves its owner alone. It is not optional for a relay with a control
1475
+ * plane — one that omitted it would be asking devices to accept grants
1476
+ * from nobody in particular, and would find every job refused.
1477
+ *
1478
+ * Rotation is Amendment C's, with no path where a grant teaches a
1479
+ * daemon a new key.
1480
+ */
1481
+ controlPlanePublic: z9.string().min(1).optional()
1482
+ }).strict()
1483
+ ]);
1484
+ var PairRequest = z9.discriminatedUnion("action", [
1485
+ PairStartRequest,
1486
+ PairPollRequest
1487
+ ]);
1488
+ var ClaimRequest = z9.object({
1489
+ protocolVersion: z9.literal(PROTOCOL_VERSION),
1490
+ runnerId: z9.string().min(1),
1491
+ /** Re-sent on every claim so a server never matches against a stale matrix. */
1492
+ capabilities: CapabilityMatrix,
1493
+ /** Upper bound on jobs to return; the server may return fewer. */
1494
+ max: z9.number().int().min(1).max(64)
1495
+ }).strict();
1496
+ var ClaimResponse = z9.object({
1497
+ /**
1498
+ * Stubs, not jobs. The payload arrives from `fetch`, sealed to whichever
1499
+ * device claimed — see {@link JobStub} for the exhaustive metadata list.
1500
+ */
1501
+ jobs: z9.array(ClaimedStub),
1502
+ /** Lease duration granted, so the daemon knows its renewal deadline. */
1503
+ leaseMs: z9.number().int().positive()
1504
+ }).strict();
1505
+ var HeartbeatRequest = z9.object({
1506
+ protocolVersion: z9.literal(PROTOCOL_VERSION),
1507
+ runnerId: z9.string().min(1),
1508
+ daemonVersion: z9.string().min(1),
1509
+ capabilities: CapabilityMatrix,
1510
+ /**
1511
+ * Kinds this device is withholding, and why it can be said.
1512
+ *
1513
+ * Optional so a daemon that has nothing withheld sends nothing, and so an
1514
+ * older daemon against a newer hub is simply a device with no withheld
1515
+ * kinds rather than a parse failure.
1516
+ */
1517
+ withheld: z9.array(WithheldKind).default([]),
1518
+ /**
1519
+ * Leases this daemon believes it holds; the server renews exactly these.
1520
+ *
1521
+ * Lease ids rather than job ids, so a replayed heartbeat cannot renew a
1522
+ * grant the runner no longer holds — see {@link Lease.id}.
1523
+ */
1524
+ activeLeases: z9.array(GrantRef),
1525
+ /** True while the owner has the daemon paused; the server stops offering work. */
1526
+ paused: z9.boolean()
1527
+ }).strict();
1528
+ var HeartbeatResponse = z9.object({
1529
+ /**
1530
+ * The sites this daemon may serve, right now — cloud_008 finding 59.
1531
+ *
1532
+ * Revocation used to be a boolean, and it was device-wide: the daemon
1533
+ * plane refused every call when the (owner, hub-site) consent was gone,
1534
+ * heartbeat answered `revoked: true` with `lost: all`, and the daemon
1535
+ * dropped its whole pairing by origin. Under a hub that is one site's
1536
+ * revocation ending a machine's relationship with every other site it
1537
+ * served — the amplification finding 48 warned about, arriving through
1538
+ * the one field nobody thought of as tenancy.
1539
+ *
1540
+ * So the answer is the set. A site that leaves it is revoked *for that
1541
+ * site*: the daemon drops that pin and keeps the rest. An empty set is
1542
+ * what "revoked" used to mean, and the daemon can see that for itself
1543
+ * rather than being told a second time — two fields for one fact is how
1544
+ * they drift.
1545
+ */
1546
+ sites: z9.record(z9.string().min(1), PublicIdentity),
1547
+ /**
1548
+ * How a site's current key traces back to one this daemon already holds —
1549
+ * byollm_009 Amendment C.
1550
+ *
1551
+ * Keyed by the same id as `sites`, and **additive on purpose**: `sites`
1552
+ * remains the one statement of which key is current, and this says only
1553
+ * how that key got there. Two fields for one fact is how they drift; this
1554
+ * is two facts, and the second is evidence about the first.
1555
+ *
1556
+ * Optional because a site that has never rotated has no chain, which is
1557
+ * every site today. A daemon that receives one for an id it already holds
1558
+ * ignores it: the pin it has is the pin it approved.
1559
+ *
1560
+ * §12 carries what this adds to the metadata surface — a site's rotation
1561
+ * history is public by construction, because a daemon that cannot read it
1562
+ * cannot verify it.
1563
+ */
1564
+ successions: z9.record(
1565
+ z9.string().min(1),
1566
+ z9.object({
1567
+ /** Oldest last, as the projection carries it. */
1568
+ succeeds: z9.array(Succession).max(MAX_SUCCESSION_CHAIN),
1569
+ /**
1570
+ * Until when the superseded key may still sign work — epoch ms.
1571
+ *
1572
+ * The daemon holds its own clock against this, for the reason it
1573
+ * holds its own allowlist: a projection that could extend the
1574
+ * window indefinitely would be a two-key site forever, decided by
1575
+ * the party this design does not trust.
1576
+ */
1577
+ retiringUntil: z9.number().int().positive().optional()
1578
+ }).strict()
1579
+ ).optional(),
1580
+ /**
1581
+ * Per-job cancel (byollm_001 Rev 1 §C). The daemon aborts these jobs'
1582
+ * in-flight backend calls and reports them `canceled`.
1583
+ *
1584
+ * **The grant, not the id** — V1-3. Job ids are chosen per site, so two
1585
+ * sites may pick the same one, and a bare id told a daemon holding both
1586
+ * to abort whichever it happened to have filed under that name. The lease
1587
+ * is the unique grant and the daemon already keys its work by it; this is
1588
+ * the same shape `activeLeases` sends in the other direction.
1589
+ */
1590
+ cancel: z9.array(
1591
+ z9.object({ jobId: z9.string().min(1), leaseId: z9.string().min(1) }).strict()
1592
+ ),
1593
+ // `leases` is deliberately absent — cloud_008 §1.4b, finding 16.
1594
+ //
1595
+ // It carried "these leases were renewed, and here is the new expiry", and
1596
+ // **no daemon ever read it.** A mutation returning an empty list while
1597
+ // renewing correctly survived every test, which is what made it visible.
1598
+ //
1599
+ // It is neither a class nor membership, so Amendment A's rule does not
1600
+ // decide it — the older test does: nothing reads it, so it is dead wire.
1601
+ // §6's exhaustiveness is a commitment about what an upstream can see, and
1602
+ // it applies to every message rather than only to the stub.
1603
+ //
1604
+ // `lost` is the actionable signal and always was: a daemon stops work on
1605
+ // a lease it no longer holds. "Renewed" was the same question answered a
1606
+ // second time, and a second answer can only agree or contradict.
1607
+ //
1608
+ // Renewal itself is untouched — the upstream still extends the grants a
1609
+ // heartbeat names, which is what §0.6 fixed. What ended is telling the
1610
+ // daemon about it in a field it ignored. If an upstream ever needs to
1611
+ // push lease decisions, that is a new field with a reader, added on
1612
+ // purpose.
1613
+ /**
1614
+ * Jobs the daemon thinks it holds but the server has reassigned or
1615
+ * expired. The daemon must stop work on these and not report results.
1616
+ *
1617
+ * Named by grant rather than by id, for V1-3's reason: a bare id is
1618
+ * ambiguous across sites, and "the lease you no longer hold" is exactly
1619
+ * what this field means anyway.
1620
+ */
1621
+ lost: z9.array(
1622
+ z9.object({ jobId: z9.string().min(1), leaseId: z9.string().min(1) }).strict()
1623
+ ),
1624
+ /** Server clock, so a daemon with a skewed clock still honors leases. */
1625
+ serverTime: z9.number().int().positive(),
1626
+ /**
1627
+ * Sites whose disclosure the user must read again before work moves —
1628
+ * cloud_008 finding 48, named rather than counted.
1629
+ *
1630
+ * A **subset of `sites`**, deliberately: a paused site keeps its pin, so
1631
+ * re-consenting never costs a re-pair. The daemon can say which site is
1632
+ * waiting and the user can go and read it, which is the difference
1633
+ * between a machine that is quietly idle and one that says why.
1634
+ *
1635
+ * Not `revoked`, which is a human ending a relationship, and not
1636
+ * `paused`, which on the request side already means "this daemon's
1637
+ * operator stopped it" — one word with two subjects on two halves of one
1638
+ * exchange is a confusion nobody untangles from a log.
1639
+ */
1640
+ awaitingConsent: z9.array(z9.string().min(1)),
1641
+ /**
1642
+ * A version this daemon should move itself to — B053.
1643
+ *
1644
+ * The channel the auto-updater reads, and it is the channel the daemon
1645
+ * already polls rather than a new phone-home, which is what the ruling
1646
+ * asked for (016 §Auto-update).
1647
+ *
1648
+ * **The hub may not send this to every daemon.** This schema is
1649
+ * `.strict()`, so a daemon built before the field exists does not ignore
1650
+ * it — it rejects the whole heartbeat and stops working. Which would mean
1651
+ * the message carrying the update is the message that breaks the machines
1652
+ * it was meant to update.
1653
+ *
1654
+ * That is decidable without any new handshake, because the request
1655
+ * already carries `daemonVersion`. {@link mayOfferUpdate} is the rule,
1656
+ * kept here as code rather than as a paragraph in a runbook, so both
1657
+ * sides read the same one.
1658
+ *
1659
+ * Exact versions only, never a tag: the daemon refuses anything else, and
1660
+ * a fleet resolving one tag at different minutes is a fleet on different
1661
+ * builds reporting one number.
1662
+ */
1663
+ updateTo: z9.string().min(1).optional()
1664
+ }).strict();
1665
+ var ResultDisposition = z9.enum(["ok", "error", "canceled"]);
1666
+ var ResultRequest = z9.object({
1667
+ protocolVersion: z9.literal(PROTOCOL_VERSION),
1668
+ runnerId: z9.string().min(1),
1669
+ jobId: z9.string().min(1),
1670
+ /**
1671
+ * The grant this result was produced under — cloud_008 §1.4a.
1672
+ *
1673
+ * `fetch` has always named its lease, with the reasoning written beside
1674
+ * it: a request that names only the job would be answerable for whatever
1675
+ * lease exists when it arrives. **The operation that writes the result did
1676
+ * not**, on either plane, and checked only the runner id — which survives
1677
+ * a claim-release-reclaim cycle, so a device whose grant had been swept
1678
+ * and reissued could still land a result for a job it no longer held.
1679
+ *
1680
+ * Found by tracing a mutation that survived in §0.6: the lease lapsed, the
1681
+ * sweep requeued, the daemon re-claimed under a new grant, and the
1682
+ * original run finished and posted anyway. The relay marked the job done
1683
+ * with a result the site cannot open — it verifies the envelope against
1684
+ * the *current* holder's device, so the crypto contains the substitution —
1685
+ * and then refused the real holder's result as a replay. A lost job, in
1686
+ * silence.
1687
+ *
1688
+ * `LEASE_HONORED` is a statement about a lease *instance*. That was
1689
+ * learned once already, when a replayed release yanked a later grant, and
1690
+ * it applies here for the same reason.
1691
+ */
1692
+ leaseId: z9.string().min(1),
1693
+ /**
1694
+ * The outcome, sealed to the site and signed by the device.
1695
+ *
1696
+ * The return leg of the payload envelope, and sealed for the same reason:
1697
+ * a model's answer is as sensitive as the prompt that produced it, and an
1698
+ * intermediary that cannot read one must not be handed the other.
1699
+ */
1700
+ envelope: SealedEnvelope,
1701
+ /**
1702
+ * The sealed outcome's discriminator, in the clear.
1703
+ *
1704
+ * Checked against the envelope once opened. It is a routing hint, not a
1705
+ * fact: believing it unverified would let a daemon mark a job `ok` while
1706
+ * sealing an error, and only the app would ever find out.
1707
+ */
1708
+ disposition: ResultDisposition
1709
+ // `model`, `backendClass` and `durationMs` are **inside the envelope** —
1710
+ // cloud_008 §2.5. See {@link RunMetadata}.
1711
+ //
1712
+ // They were here, in the clear, and that was two problems wearing one
1713
+ // coat. On the direct plane the site recorded unauthenticated fields
1714
+ // beside an authenticated answer: a daemon could seal one result and
1715
+ // declare a different model, and only the unsigned half would reach the
1716
+ // app. Through a relay they reached a third party that acts on none of
1717
+ // them — `model` in particular being the sort of detail Amendment A's
1718
+ // rule keeps off the wire.
1719
+ //
1720
+ // `disposition` stays, and the difference is the test: a relay *routes*
1721
+ // on it, so it is a class a routing party consumes. Nobody between the
1722
+ // two ends consumes these.
1723
+ }).strict();
1724
+ var ResultResponse = z9.object({
1725
+ /**
1726
+ * False when this submission wrote nothing — the daemon should discard,
1727
+ * not retry ({@link MUSTS.RESULT_IDEMPOTENT}).
1728
+ */
1729
+ accepted: z9.boolean(),
1730
+ /**
1731
+ * True when this device had already recorded this job's result.
1732
+ *
1733
+ * The difference between "already recorded" and "you no longer hold this"
1734
+ * — cloud_008 §3.6. A daemon whose acknowledgment was lost is in the first
1735
+ * case and needs to hear it: its answer is safely on disk. Reporting a
1736
+ * stale lease instead invents a worry about a result that is already
1737
+ * stored, and sends its owner looking for a routing problem.
1738
+ *
1739
+ * Set only for the device that finished the job. A different device gets
1740
+ * the same refusal it would get for a job that is *not* terminal, so a job
1741
+ * id cannot be used as a terminality probe.
1742
+ */
1743
+ duplicate: z9.boolean().optional(),
1744
+ /** The job's state after this submission. */
1745
+ state: z9.string().min(1)
1746
+ }).strict();
1747
+ var ReleaseRequest = z9.object({
1748
+ protocolVersion: z9.literal(PROTOCOL_VERSION),
1749
+ runnerId: z9.string().min(1),
1750
+ /**
1751
+ * Which leases to release — the grant, not just the job.
1752
+ *
1753
+ * A release naming only a job id releases whatever lease exists at the
1754
+ * moment it arrives, which for a replayed request is not the lease the
1755
+ * daemon meant. See {@link Lease.id}.
1756
+ */
1757
+ leases: z9.array(GrantRef),
1758
+ /**
1759
+ * Why, so the app's runner list can say something true.
1760
+ *
1761
+ * `refused` is load-bearing, not cosmetic: the server cannot evaluate
1762
+ * what a device will admit (§4.2), so it may legitimately offer
1763
+ * a job this daemon then declines. The server MUST record the refusal and
1764
+ * stop offering that job to that runner, or the pair would spin between
1765
+ * claim and release forever.
1766
+ */
1767
+ reason: z9.enum(["shutdown", "pause", "revoked", "backend-down", "refused"])
1768
+ }).strict();
1769
+ var ReleaseResponse = z9.object({
1770
+ released: z9.array(z9.string().min(1))
1771
+ }).strict();
1772
+ var WireErrorCode = z9.enum([
1773
+ "bad-request",
1774
+ "unsupported-protocol-version",
1775
+ /**
1776
+ * The daemon is older than this hub will serve — B052.
1777
+ *
1778
+ * Distinct from `unsupported-protocol-version`, which is about the
1779
+ * contract; this is about the build. A daemon can speak protocol 1
1780
+ * perfectly and still be old enough that we would rather move it than keep
1781
+ * carrying it — and the two need different remedies in the message, since
1782
+ * one is "your daemon and this server disagree" and the other is "yours
1783
+ * works, and it is time".
1784
+ *
1785
+ * The floor is the backstop to the auto-updater (B053), and the only lever
1786
+ * that reaches a machine which never opted into offers.
1787
+ */
1788
+ "daemon-below-floor",
1789
+ // "We do not know who you are." Exactly 401, and only that — cloud_008
1790
+ // §1.4d.
1791
+ "unauthorized",
1792
+ /**
1793
+ * "We know exactly who you are, and the answer is no." Exactly 403.
1794
+ *
1795
+ * Five refusals across both planes served 403 with `unauthorized`, whose
1796
+ * table entry is 401: a revoked device, a site claiming another site's
1797
+ * stub, a job you do not hold, a device belonging to another owner, a
1798
+ * relay that does not route for you. Every one of them is an *identified*
1799
+ * caller being refused.
1800
+ *
1801
+ * Collapsing the two loses a distinction that matters everywhere it is
1802
+ * read: a revoked daemon would look like an unsigned one in every log and
1803
+ * every client branch, and "check your keys" is the wrong advice for both
1804
+ * of them in opposite directions.
1805
+ */
1806
+ "forbidden",
1807
+ "revoked",
1808
+ "not-found",
1809
+ // Claimed, but the site has not sealed the payload yet — cloud_008 §1.4.
1810
+ //
1811
+ // A daemon must retry rather than abandon: the job is legitimately still
1812
+ // its own until the lease or the awaiting-payload clock says otherwise.
1813
+ // That is why it cannot be `not-found` or `server-error`, and why it was
1814
+ // the protocol gap that produced a bare 409 in the first place.
1815
+ "not-ready",
1816
+ /**
1817
+ * The job is over, and this call is about a job — V1-6, and the code the
1818
+ * site plane has been serving without one (V1-13).
1819
+ *
1820
+ * Distinct from `not-found`, which says "no such job", and from
1821
+ * `not-ready`, which says "not yet, keep asking". This one says "yes, and
1822
+ * it finished" — so a daemon must stop rather than retry, and a replayed
1823
+ * request must not be able to reopen it.
1824
+ */
1825
+ "too-late",
1826
+ // The caller's clock is too far from ours to judge a signature's freshness.
1827
+ //
1828
+ // Split out from `unauthorized` because the remedy is completely different
1829
+ // and only the server can tell them apart: a bad signature means the key is
1830
+ // wrong, this means the machine's time is wrong. A daemon reporting it as a
1831
+ // generic rejection sends its owner looking at their network.
1832
+ "clock-skew",
1833
+ "rate-limited",
1834
+ "server-error"
1835
+ ]);
1836
+ var WireError = z9.object({
1837
+ error: WireErrorCode,
1838
+ message: z9.string().min(1),
1839
+ /**
1840
+ * What this server speaks, on `unsupported-protocol-version` — §B.4.
1841
+ *
1842
+ * The refusal has carried these since the version handshake existed and
1843
+ * the enumeration did not model them, so the one error that exists to be
1844
+ * *acted on* was the one that failed to parse as a wire error. Found by
1845
+ * the relay's own suite the day the relay started sending it: a refusal
1846
+ * outside the enumerated shape is a refusal a client cannot branch on,
1847
+ * which is the whole reason §1.4 enumerates them.
1848
+ *
1849
+ * Modelled the way `clock-skew`'s two fields already are — code-specific
1850
+ * extras, refused on any other code by the refinement below.
1851
+ */
1852
+ supported: z9.array(z9.string().min(1)).optional(),
1853
+ minimum: z9.string().min(1).optional(),
1854
+ /**
1855
+ * The oldest daemon this hub serves, on `daemon-below-floor` — B052.
1856
+ *
1857
+ * Carried for the same reason `supported` and `minimum` are: a refusal
1858
+ * that cannot be branched on is a refusal a client can only print. The
1859
+ * message already names the floor for a person; this names it for the
1860
+ * code, so a surface can say "you are two versions under" without
1861
+ * parsing English.
1862
+ */
1863
+ floor: z9.string().min(1).optional(),
1864
+ /** Seconds; mirrors Retry-After for `rate-limited` and `server-error`. */
1865
+ retryAfter: z9.number().int().nonnegative().optional(),
1866
+ /**
1867
+ * The server's clock, and the window it allows. `clock-skew` only.
1868
+ *
1869
+ * So the far side can say *how far off* rather than *that something is
1870
+ * wrong* — the difference between "adjust your clock by four minutes" and
1871
+ * "something is wrong with your connection". Not a disclosure: the
1872
+ * heartbeat response returns the same value, and so does every `Date`
1873
+ * header.
1874
+ */
1875
+ serverTime: z9.number().int().positive().optional(),
1876
+ maxSkewMs: z9.number().int().positive().optional()
1877
+ }).strict().superRefine((error, ctx) => {
1878
+ const skew = error.error === "clock-skew";
1879
+ const carried = error.serverTime !== void 0 || error.maxSkewMs !== void 0;
1880
+ if (skew && !carried) {
1881
+ ctx.addIssue({
1882
+ code: "custom",
1883
+ message: "clock-skew must carry serverTime and maxSkewMs"
1884
+ });
1885
+ }
1886
+ if (!skew && carried) {
1887
+ ctx.addIssue({
1888
+ code: "custom",
1889
+ message: `${error.error} must not carry serverTime or maxSkewMs`
1890
+ });
1891
+ }
1892
+ const floored = error.error === "daemon-below-floor";
1893
+ if (floored && error.floor === void 0) {
1894
+ ctx.addIssue({
1895
+ code: "custom",
1896
+ message: "daemon-below-floor must carry floor"
1897
+ });
1898
+ }
1899
+ if (!floored && error.floor !== void 0) {
1900
+ ctx.addIssue({
1901
+ code: "custom",
1902
+ message: `${error.error} must not carry floor`
1903
+ });
1904
+ }
1905
+ const version = error.error === "unsupported-protocol-version";
1906
+ const versionFields = error.supported !== void 0 || error.minimum !== void 0;
1907
+ if (version && !versionFields) {
1908
+ ctx.addIssue({
1909
+ code: "custom",
1910
+ message: "unsupported-protocol-version must carry supported and minimum"
1911
+ });
1912
+ }
1913
+ if (!version && versionFields) {
1914
+ ctx.addIssue({
1915
+ code: "custom",
1916
+ message: `${error.error} must not carry supported or minimum`
1917
+ });
1918
+ }
1919
+ });
1920
+ var ERROR_STATUS = Object.freeze({
1921
+ "bad-request": 400,
1922
+ "unsupported-protocol-version": 400,
1923
+ /**
1924
+ * 426 Upgrade Required — B052, and it is the one status that says this.
1925
+ *
1926
+ * Not 403, which this daemon reads as a permission problem and which
1927
+ * sits beside `revoked` in every log. Not 400, which reads as a
1928
+ * malformed request; the request was perfect and the sender is old.
1929
+ *
1930
+ * It also fails safely on a daemon that predates the code: 426 is not in
1931
+ * that switch, so it lands on the 4xx default — `rejected`, which is
1932
+ * "never retried: the request is wrong, and repeating it stays wrong".
1933
+ * Vaguer than the remedy, and the right behaviour, which is what a
1934
+ * fallback has to be.
1935
+ */
1936
+ "daemon-below-floor": 426,
1937
+ unauthorized: 401,
1938
+ forbidden: 403,
1939
+ revoked: 403,
1940
+ "not-found": 404,
1941
+ // 409, not 404: the job exists and is yours, it is simply not ready.
1942
+ "not-ready": 409,
1943
+ // The same 409 as `not-ready` and the opposite instruction: that one says
1944
+ // keep asking, this one says stop. The status is the class of the
1945
+ // problem — a request that does not fit the resource's state — and the
1946
+ // code is what a caller acts on.
1947
+ "too-late": 409,
1948
+ // 401 alongside `unauthorized`, because that is what it is — the
1949
+ // signature could not be judged. The code is what carries the remedy.
1950
+ "clock-skew": 401,
1951
+ "rate-limited": 429,
1952
+ "server-error": 500
1953
+ });
1954
+ var FetchRequest = z9.object({
1955
+ // `literal`, like every other request — V1-17. This one said
1956
+ // `string().min(1)`, so a daemon speaking a version this server does not
1957
+ // know got past the handshake on the one endpoint that hands over a
1958
+ // sealed payload. The version check exists so that a mismatch is a named
1959
+ // refusal rather than a schema failure three fields later; here it was
1960
+ // neither.
1961
+ protocolVersion: z9.literal(PROTOCOL_VERSION),
1962
+ runnerId: z9.string().min(1),
1963
+ jobId: z9.string().min(1),
1964
+ /**
1965
+ * The grant this daemon holds.
1966
+ *
1967
+ * Named, not inferred: a fetch is lease-scoped, and a request that names
1968
+ * only the job would be answerable for whatever lease exists when it
1969
+ * arrives ({@link Lease.id}).
1970
+ */
1971
+ leaseId: z9.string().min(1)
1972
+ }).strict();
1973
+ var FetchResponse = z9.object({
1974
+ /**
1975
+ * The work, sealed to the device that claimed it — byollm_009 §6.
1976
+ *
1977
+ * Not plaintext. The site opens its own at-rest envelope and re-seals to
1978
+ * the claiming device's key, signed by the site's identity, so the work
1979
+ * is readable only by the machine that took it and only if it came from
1980
+ * the site that machine pinned.
1981
+ */
1982
+ envelope: SealedEnvelope
1983
+ }).strict();
1984
+
1985
+ // src/update-offer.ts
1986
+ var UPDATE_OFFER_SINCE = "0.1.0-alpha.83";
1987
+ function parse(version) {
1988
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(
1989
+ version
1990
+ );
1991
+ if (match === null) return void 0;
1992
+ return {
1993
+ release: [Number(match[1]), Number(match[2]), Number(match[3])],
1994
+ pre: match[4] === void 0 ? [] : match[4].split(".").map((part) => /^\d+$/.test(part) ? Number(part) : part)
1995
+ };
1996
+ }
1997
+ function compareVersions(a, b) {
1998
+ const left = parse(a);
1999
+ const right = parse(b);
2000
+ if (left === void 0 || right === void 0) return void 0;
2001
+ for (let i = 0; i < 3; i += 1) {
2002
+ const diff = (left.release[i] ?? 0) - (right.release[i] ?? 0);
2003
+ if (diff !== 0) return diff < 0 ? -1 : 1;
2004
+ }
2005
+ if (left.pre.length === 0 && right.pre.length > 0) return 1;
2006
+ if (left.pre.length > 0 && right.pre.length === 0) return -1;
2007
+ for (let i = 0; i < Math.max(left.pre.length, right.pre.length); i += 1) {
2008
+ const l = left.pre[i];
2009
+ const r = right.pre[i];
2010
+ if (l === void 0) return -1;
2011
+ if (r === void 0) return 1;
2012
+ if (l === r) continue;
2013
+ if (typeof l === "number" && typeof r === "number") return l < r ? -1 : 1;
2014
+ if (typeof l === "number") return -1;
2015
+ if (typeof r === "number") return 1;
2016
+ return l < r ? -1 : 1;
715
2017
  }
716
- return { ok: true, plaintext: claims["plaintext"] };
2018
+ return 0;
2019
+ }
2020
+ function mayOfferUpdate(daemonVersion) {
2021
+ const order = compareVersions(daemonVersion, UPDATE_OFFER_SINCE);
2022
+ return order !== void 0 && order >= 0;
2023
+ }
2024
+ function checkDaemonFloor(input) {
2025
+ const order = compareVersions(input.daemonVersion, input.floor);
2026
+ if (order === void 0 || order >= 0) return null;
2027
+ return {
2028
+ error: "daemon-below-floor",
2029
+ message: `byollm ${input.daemonVersion} is below the supported floor (${input.floor}). Run \`${input.upgradeCommand}\`, then \`byollm start\`.`,
2030
+ floor: input.floor
2031
+ };
2032
+ }
2033
+ function updateOfferFor(input) {
2034
+ const { offer, daemonVersion } = input;
2035
+ if (offer === void 0) return {};
2036
+ if (exactOffer(offer) === void 0) return {};
2037
+ if (!mayOfferUpdate(daemonVersion)) return {};
2038
+ if (daemonVersion === offer) return {};
2039
+ return { updateTo: offer };
2040
+ }
2041
+ function exactOffer(value) {
2042
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(value) ? value : void 0;
2043
+ }
2044
+ function withoutComments(source) {
2045
+ return source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/^[ \t]*\/\/.*$/gm, " ");
717
2046
  }
2047
+ function mentionsWireField(source, field) {
2048
+ return new RegExp(`\\b${field}\\b`).test(withoutComments(source));
2049
+ }
2050
+
2051
+ // src/about.ts
2052
+ var ABOUT = `# About BYOLLM
2053
+
2054
+ **What BYOLLM is**
2055
+
2056
+ BYOLLM lets you use your own AI on websites. You install one small program on
2057
+ your computer. Then, websites that support BYOLLM can use the AI you already
2058
+ have \u2014 a free model running on your machine, or an AI service you already pay
2059
+ for \u2014 instead of the website paying for AI and passing the cost to you.
2060
+
2061
+ **Why it matters**
2062
+
2063
+ For you:
2064
+
2065
+ - Your favorite model, everywhere you go.
2066
+ - New models the moment you get them \u2013 not when a site gets around to adding
2067
+ them.
2068
+ - Encrypted end-to-end. Your prompts go to your own device; byollm.cloud can't
2069
+ read them.
2070
+ - Sites never learn which model you use, and your subscriptions are never
2071
+ shared.
2072
+ - Pay less. Sites that don't pay for AI can charge you less \u2013 or nothing.
2073
+
2074
+ For sites and developers:
2075
+
2076
+ - Zero AI bills. Your users bring their own compute.
2077
+ - No floating money \u2013 you don't pay LLM bills up front and hope to collect
2078
+ later, and you never ask people to prepay just to try you.
2079
+ - Free trials that cost you nothing to offer.
2080
+ - Ship the AI features you kept private for fear of the API bill.
2081
+ - One small integration. Your users choose the models.
2082
+
2083
+ **Your device**
2084
+
2085
+ The \`byollm\` program runs on your computer. It knows which AI services you have
2086
+ set up: free open-source models on your machine, metered services you pay per
2087
+ use, or your own subscriptions like Claude Pro/Max. When a website you have
2088
+ enabled sends work, your device runs it with the service you chose. Your
2089
+ prompts are encrypted end-to-end to your own device. byollm.cloud passes them
2090
+ along and cannot read them.
2091
+
2092
+ **Sites**
2093
+
2094
+ A website that wants to use BYOLLM says what it needs \u2014 "writing help," "chat,"
2095
+ and so on. When you connect the site, you pick which of your services answers
2096
+ each one. The site never learns which model you use. You can turn a site off at
2097
+ any time, and it stops getting your work.
2098
+
2099
+ **Teams (optional)**
2100
+
2101
+ A team lets you share what runs on your devices with people you name \u2014 the free
2102
+ open-source models on your machine, or a metered service with a spending limit
2103
+ you set. Your subscription accounts (like Claude Pro/Max) are never shared with
2104
+ anyone. That is a rule, not a setting.
2105
+
2106
+ **byollm.cloud (or your own relay)**
2107
+
2108
+ Many sites, many devices, many people. byollm.cloud keeps track of who has
2109
+ allowed what and sends each job to the right device. It never sees your
2110
+ prompts. If you would rather run this part yourself, the relay is open source \u2014
2111
+ you can run your own instead of using byollm.cloud.`;
2112
+ var ABOUT_SHORT_LEDE = "BYOLLM \u2013 Bring Your Own LLM \u2013 lets you use your own AI on websites you authorize. A small program installed on your machine lets you use your own models and subscriptions on any BYOLLM-integrated site, including new models the moment you get access \u2013 no site updates required. BYOLLM Cloud connects sites to your devices with end-to-end encryption, so no one, including us, can see your data.";
2113
+ var ABOUT_SHORT_TAIL = "Sites can charge you less because you bring your own \u2013 see why that matters \u2192. Teams can optionally share the free or metered services on their devices with people they name. Personal subscriptions are never shared.";
2114
+ var ABOUT_SHORT = `${ABOUT_SHORT_LEDE}
2115
+
2116
+ ${ABOUT_SHORT_TAIL}`;
718
2117
 
719
2118
  // src/signing.ts
720
2119
  import { createHash as createHash2 } from "crypto";
721
- import { z as z7 } from "zod";
2120
+ import { z as z10 } from "zod";
722
2121
  var MAX_CLOCK_SKEW_MS = 12e4;
723
- var RequestSignature = z7.object({
2122
+ var RequestSignature = z10.object({
724
2123
  /** Which runner is calling. The server looks up its pinned identity. */
725
- runnerId: z7.string().min(1),
2124
+ runnerId: z10.string().min(1),
726
2125
  /** Epoch ms, bounded by {@link MAX_CLOCK_SKEW_MS}. */
727
- issuedAt: z7.number().int().positive(),
2126
+ issuedAt: z10.number().int().positive(),
728
2127
  /** Base64url Ed25519 signature over {@link canonicalRequest}. */
729
- signature: z7.string().min(1)
2128
+ signature: z10.string().min(1)
730
2129
  }).strict();
731
2130
  function canonicalRequest(input) {
732
2131
  const digest = createHash2("sha256").update(input.body, "utf8").digest("hex");
@@ -779,7 +2178,60 @@ function verifyRequest(input) {
779
2178
  return ok ? null : "bad-signature";
780
2179
  }
781
2180
 
2181
+ // src/manifest.ts
2182
+ import { z as z11 } from "zod";
2183
+ var RESERVED_PURPOSE = "default";
2184
+ var RENDERABLE = /^[^\p{Cc}\p{Cf}\p{Cs}\p{Co}]+$/u;
2185
+ var renderable = (max, what) => z11.string().min(1).max(max).regex(
2186
+ RENDERABLE,
2187
+ `a ${what} is text a person reads \u2014 no control characters, direction overrides or zero-width padding`
2188
+ ).refine((value) => value.trim() !== "", {
2189
+ message: `a ${what} cannot be blank`
2190
+ });
2191
+ var PurposeKey = z11.string().regex(
2192
+ /^[a-z0-9][a-z0-9-]*$/,
2193
+ "a purpose key is a lowercase slug \u2014 letters, digits and hyphens"
2194
+ ).max(64);
2195
+ var Purpose = z11.object({
2196
+ /**
2197
+ * What a person reads on the consent screen. The only rendered field.
2198
+ *
2199
+ * Declared rather than derived from the key, because a key is a
2200
+ * compromise between machines and this is not. "Writing Assistant" is
2201
+ * what somebody understands; `writing-assistant` is what travels.
2202
+ */
2203
+ label: renderable(80, "label"),
2204
+ /** One line of context for the consent screen. Optional. */
2205
+ description: renderable(280, "description").optional(),
2206
+ /**
2207
+ * The kinds this purpose uses.
2208
+ *
2209
+ * A purpose may span kinds, and a mapping is per (purpose, kind) — so a
2210
+ * person can send this purpose's chat to one service and its generation
2211
+ * to another. Listing a kind here is what makes that slot appear.
2212
+ */
2213
+ kinds: z11.array(JobKind).min(1).max(JOB_KINDS.length).refine((kinds) => new Set(kinds).size === kinds.length, {
2214
+ message: "a purpose lists each kind once"
2215
+ })
2216
+ }).strict();
2217
+ var MAX_PURPOSES = 32;
2218
+ var Manifest = z11.record(PurposeKey, Purpose).refine((manifest) => Object.keys(manifest).length > 0, {
2219
+ message: "a manifest declares at least one purpose"
2220
+ }).refine((manifest) => Object.keys(manifest).length <= MAX_PURPOSES, {
2221
+ message: `a manifest declares at most ${String(MAX_PURPOSES)} purposes \u2014 a consent screen is a set of questions somebody answers one at a time`
2222
+ }).refine((manifest) => !(RESERVED_PURPOSE in manifest), {
2223
+ message: `"${RESERVED_PURPOSE}" is reserved for a site that declares no purposes of its own \u2014 give this one a name from your own vocabulary`
2224
+ });
2225
+ function singlePurposeManifest(input) {
2226
+ return {
2227
+ [RESERVED_PURPOSE]: { label: input.label, kinds: [...input.kinds] }
2228
+ };
2229
+ }
2230
+
782
2231
  // src/musts.ts
2232
+ function kindsOf(must2) {
2233
+ return typeof must2.verifiedBy === "string" ? [must2.verifiedBy] : must2.verifiedBy;
2234
+ }
783
2235
  var must = (m) => Object.freeze(m);
784
2236
  var MUSTS = Object.freeze({
785
2237
  // ---- Pairing and identity -------------------------------------------
@@ -812,6 +2264,50 @@ var MUSTS = Object.freeze({
812
2264
  verifiedBy: "conformance",
813
2265
  source: "byollm_009 \xA74"
814
2266
  }),
2267
+ SITE_KEY_BY_STUB: must({
2268
+ id: "SITE_KEY_BY_STUB",
2269
+ statement: "A daemon MUST verify a job's payload against the pinned key of the site the stub names, and MUST refuse a job naming a site it has not pinned. It MUST NOT fall back to another pinned key, and MUST refuse an envelope whose declared sender disagrees with the stub's site.",
2270
+ enforcedBy: "daemon",
2271
+ // Adversarial, and the reason is the finding that produced it: the
2272
+ // honest paths pass with every site check deleted, because `open`
2273
+ // refuses a signature from the wrong key anyway. What distinguishes an
2274
+ // enforced rule from a coincidence here is a hostile pairing of stub and
2275
+ // envelope, which no conformance client would ever send.
2276
+ verifiedBy: "adversarial",
2277
+ source: "byollm_009 \xA7A.3"
2278
+ }),
2279
+ SITES_LOCALLY_APPROVED: must({
2280
+ id: "SITES_LOCALLY_APPROVED",
2281
+ statement: "A daemon MUST NOT run work for a site on an upstream's word alone. An upstream may propose a site set; work for any site in it MUST additionally carry a grant signed by the control-plane key this daemon pinned at pairing. A key that has changed for an id this daemon already pinned MUST be refused for the life of the pairing, including after that id has left the set and returned. A **verified succession** is not a changed key: a new key id carrying a signature, by a key this daemon has already pinned, over a statement naming both key ids MUST be accepted \u2014 provided the control plane projects the same successor \u2014 and MUST be announced rather than applied silently. The first job from a site this daemon has never served MUST be announced at the machine.",
2282
+ enforcedBy: "daemon",
2283
+ // Two kinds, and the second is the one that matters — V1-1.
2284
+ //
2285
+ // `construction`: the daemon cannot serve a site that is not in its
2286
+ // pinned map, and admission refuses before a payload is fetched — and
2287
+ // since byollm_016 Amendment K, being in the map is no longer sufficient
2288
+ // either: a signed grant is, and the relay proposing the set cannot
2289
+ // produce one.
2290
+ //
2291
+ // `adversarial`: the property that survives is about a *sequence* —
2292
+ // remove the id, re-offer it under a different key — which no honest
2293
+ // upstream sends and which the fence above does not see. That was the
2294
+ // bypass: the pin was deleted with the id, so the comparison had nothing
2295
+ // to compare against and the substitution arrived as a stranger.
2296
+ // **Not `conformance`, and that is a live gap rather than a judgement.**
2297
+ // Amendment C's succession clause is a rule about two implementations
2298
+ // agreeing, which is what a conformance check is for — but rotating a
2299
+ // site's key is not something `ConformanceTarget` can express, and adding
2300
+ // an optional hook that most targets omit would produce a check reporting
2301
+ // success for a reason unrelated to the property it claims. That is this
2302
+ // project's most-repeated bug, and it is not worth reintroducing for a
2303
+ // stronger-sounding word in a table. The rotation path is verified by
2304
+ // `site-rotation.test.ts` (both directions, against the shipped runner)
2305
+ // and `relay/test/rotation.test.ts` (both planes, against the reference
2306
+ // relay); the missing piece is a second *independent* implementation to
2307
+ // check them against, and there is not one yet.
2308
+ verifiedBy: ["construction", "adversarial"],
2309
+ source: "byollm_009 \xA7B.2, Amendment C"
2310
+ }),
815
2311
  KEYS_EXCHANGED_AT_CONSENT: must({
816
2312
  id: "KEYS_EXCHANGED_AT_CONSENT",
817
2313
  statement: "Pairing MUST exchange both parties' public identities; each side MUST verify that the encryption key is signed by the identity presenting it, and MUST pin the identity. Keys MUST NOT be delivered before approval.",
@@ -908,14 +2404,14 @@ var MUSTS = Object.freeze({
908
2404
  }),
909
2405
  SUBSCRIPTION_SELF_LOCK: must({
910
2406
  id: "SUBSCRIPTION_SELF_LOCK",
911
- statement: "A subscription-class backend's offer scope MUST be 'self' and MUST NOT be widened by configuration.",
2407
+ statement: "A subscription-class backend's offer scope MUST be 'private' and MUST NOT be widened by configuration.",
912
2408
  enforcedBy: "daemon",
913
2409
  verifiedBy: "conformance",
914
2410
  source: "byollm_001 \xA7The audience model"
915
2411
  }),
916
2412
  METERED_DEFAULTS_SELF: must({
917
2413
  id: "METERED_DEFAULTS_SELF",
918
- statement: "A metered backend's effective offer scope MUST be 'self' unless the owner has explicitly acknowledged spending money on others' work.",
2414
+ statement: "A metered backend's effective offer scope MUST be 'private' unless the owner has explicitly acknowledged spending money on others' work.",
919
2415
  enforcedBy: "daemon",
920
2416
  verifiedBy: "conformance",
921
2417
  source: "byollm_007 \xA74"
@@ -943,7 +2439,7 @@ var MUSTS = Object.freeze({
943
2439
  }),
944
2440
  NAMED_LOCAL_ALLOWLIST: must({
945
2441
  id: "NAMED_LOCAL_ALLOWLIST",
946
- statement: "A 'named' job MUST be admitted only by the daemon's own local (server origin, user id) allowlist \u2014 never on the server's assertion alone.",
2442
+ statement: "A 'team' job MUST be admitted only by something the device itself verified, keyed by (server origin, user id) \u2014 never on the routing party's assertion alone.",
947
2443
  enforcedBy: "daemon",
948
2444
  verifiedBy: "conformance",
949
2445
  source: "byollm_001 Rev 1 \xA7B"
@@ -999,12 +2495,12 @@ var MUSTS = Object.freeze({
999
2495
  verifiedBy: "conformance",
1000
2496
  source: "byollm_001 \xA7Endpoints.4"
1001
2497
  }),
1002
- RESULT_PROVENANCE: must({
1003
- id: "RESULT_PROVENANCE",
1004
- statement: "A result from a non-'self' job MUST carry its provenance (audience and runner) to the delivery seam so an app never treats volunteer output as first-party.",
2498
+ PROVENANCE_NAMES_DEVICE: must({
2499
+ id: "PROVENANCE_NAMES_DEVICE",
2500
+ statement: "A result MUST carry the claiming device's key id and its relationship to the requester, to the delivery seam, so an app never treats volunteer output as first-party. The key id MUST be the device the upstream granted the lease to, and a result whose signature does not verify against that device MUST be refused rather than recorded.",
1005
2501
  enforcedBy: "server",
1006
2502
  verifiedBy: "conformance",
1007
- source: "byollm_003 Rev 1 \xA7Return-trip"
2503
+ source: "byollm_009 \xA711"
1008
2504
  }),
1009
2505
  // ---- The trust surface -------------------------------------------------
1010
2506
  INGRESS_LOGGED_BEFORE_EXECUTION: must({
@@ -1022,12 +2518,33 @@ var MUSTS = Object.freeze({
1022
2518
  verifiedBy: "adversarial",
1023
2519
  source: "byollm_004 \xA72"
1024
2520
  }),
2521
+ /**
2522
+ * Amended for byollm_016 Phase B, and the amendment is deliberately narrow.
2523
+ *
2524
+ * A site may now name a **service** on the stub. The temptation is to read
2525
+ * that as a crack in this law, so the statement below says exactly where the
2526
+ * line is: a name selects from a menu the owner published, and resolves to a
2527
+ * model, backend, base URL and flags **only** through that owner's own
2528
+ * config. The site supplies a key; the owner supplies every value it maps
2529
+ * to. A name the owner does not advertise is refused rather than
2530
+ * substituted, because substitution is how "you may pick from my list" turns
2531
+ * into "you may ask for anything and get something".
2532
+ *
2533
+ * Two properties keep it from drifting into "sites demand models":
2534
+ *
2535
+ * 1. **Nothing the site sends is ever a value.** No model string, no URL,
2536
+ * no flag crosses the wire — only a key that means nothing off this
2537
+ * owner's machine.
2538
+ * 2. **It is a stub field, never a payload field.** The prompt cannot
2539
+ * reach it. That is unchanged and is the sentence the second clause
2540
+ * below still enforces verbatim.
2541
+ */
1025
2542
  NO_PAYLOAD_ROUTING: must({
1026
2543
  id: "NO_PAYLOAD_ROUTING",
1027
- statement: "Model, backend, base URL, and flags MUST come from owner config only; a payload MUST NOT influence any of them.",
2544
+ statement: "Model, backend, base URL, and flags MUST come from owner config only; a payload MUST NOT influence any of them. A stub MAY name a service the owner advertises, which selects among that owner's own config entries and MUST NOT introduce any value the owner did not write; an unadvertised name MUST be refused, never substituted.",
1028
2545
  enforcedBy: "daemon",
1029
2546
  verifiedBy: "adversarial",
1030
- source: "byollm_004 \xA72"
2547
+ source: "byollm_004 \xA72, amended byollm_016 \xA7Phase B"
1031
2548
  }),
1032
2549
  STRIPPED_CHILD_ENV: must({
1033
2550
  id: "STRIPPED_CHILD_ENV",
@@ -1056,296 +2573,111 @@ var MUSTS = Object.freeze({
1056
2573
  enforcedBy: "daemon",
1057
2574
  verifiedBy: "adversarial",
1058
2575
  source: "byollm_004 \xA74"
2576
+ }),
2577
+ REVOCATION_IMMEDIATE: must({
2578
+ id: "REVOCATION_IMMEDIATE",
2579
+ statement: "Revocation MUST take effect at the upstream at once \u2014 a revoked runner MUST NOT be granted further work from the moment the record changes \u2014 and MUST reach the daemon by its next heartbeat.",
2580
+ // Both, and stated as one sentence with two obligations rather than
2581
+ // folded into REVOCATION_HONORED. That one binds the *daemon*: a revoked
2582
+ // daemon stops claiming and abandons in-flight work. This binds the
2583
+ // *upstream*. byollm_009 §5 is explicit that the pair is the point — "a
2584
+ // revocation enforced at one end survives a compromise of that end" — and
2585
+ // one entry covering both would make a compromised daemon look compliant.
2586
+ enforcedBy: "both",
2587
+ verifiedBy: "conformance",
2588
+ source: "byollm_009 \xA711"
2589
+ }),
2590
+ CONSENT_BEFORE_ROUTE: must({
2591
+ id: "CONSENT_BEFORE_ROUTE",
2592
+ statement: "An upstream MUST NOT route a job to a device without a record binding that user, that site and that scope. There MUST be no discovery path by which a device receives work it was never granted.",
2593
+ enforcedBy: "server",
2594
+ verifiedBy: "conformance",
2595
+ source: "byollm_009 \xA711"
2596
+ }),
2597
+ ROSTER_NOT_DISCLOSED: must({
2598
+ id: "ROSTER_NOT_DISCLOSED",
2599
+ statement: "A site MUST NOT learn the membership of a group whose compute it uses, and MUST NOT publish membership to a routing party. No wire message may carry a list of who may run a job.",
2600
+ // Checkable since cloud_008 §0.2 took `audienceAllow` off the stub: the
2601
+ // property now holds by *absence*, and absence is exactly what a strict
2602
+ // schema and a serialised stub can be asked about. Before that it was a
2603
+ // sentence — and one this project cited in code comments, tests and two
2604
+ // specs as though it were enforced data, which is why it is worth
2605
+ // stating precisely rather than generously.
2606
+ enforcedBy: "both",
2607
+ verifiedBy: "conformance",
2608
+ source: "byollm_009 \xA711"
2609
+ }),
2610
+ EFFECTIVE_OFFER_ONLY: must({
2611
+ id: "EFFECTIVE_OFFER_ONLY",
2612
+ statement: "A daemon MUST declare effective offers only. An upstream MUST NOT receive raw config, allowlists, or capacity the owner has not shared, and MUST act on the declared offer rather than on what was asked for.",
2613
+ enforcedBy: "both",
2614
+ verifiedBy: "conformance",
2615
+ source: "byollm_009 \xA711"
2616
+ }),
2617
+ FALLBACK_LABELED: must({
2618
+ id: "FALLBACK_LABELED",
2619
+ statement: "Work served by anything other than the user's own compute MUST be labelled as such wherever it is reported, and MUST NOT be silently substituted.",
2620
+ // `construction` today, and deliberately not `conformance`. Nothing on
2621
+ // the wire yet distinguishes a fallback from any other community job —
2622
+ // the ledger that would give it a surface is unbuilt — so a check would
2623
+ // have to assert something it cannot observe. Promoted the day that
2624
+ // surface exists. Marking it `conformance` now would put "verified"
2625
+ // beside a property no third party can see, which is the one thing the
2626
+ // kinds exist to prevent.
2627
+ enforcedBy: "both",
2628
+ verifiedBy: "construction",
2629
+ source: "byollm_009 \xA711"
2630
+ }),
2631
+ RELAY_BLIND: must({
2632
+ id: "RELAY_BLIND",
2633
+ statement: "A relay MUST NOT hold any key capable of decrypting a payload, a result, or a delta frame.",
2634
+ // Operator: a third party can read the relay's types and see there is
2635
+ // nowhere to put such a key, but the kit certifies a *server* and cannot
2636
+ // reach inside somebody's deployment to prove what it holds.
2637
+ enforcedBy: "server",
2638
+ verifiedBy: "operator",
2639
+ source: "byollm_009 \xA711"
2640
+ }),
2641
+ SHARED_COMPUTE_DISCLOSED: must({
2642
+ id: "SHARED_COMPUTE_DISCLOSED",
2643
+ statement: "Before a user's work first runs on compute they do not own, they MUST be told in plain language that the machine's owner can see it.",
2644
+ // Operator, and cloud_008 §0.3 is why the classification now comes with a
2645
+ // standing answer rather than a standing question. The screen is not
2646
+ // wire-observable, but the *string the server composes* is, and it is
2647
+ // now unit-tested with the two false sentences forbidden by name. The
2648
+ // kind stays `operator` because a third-party site can still render
2649
+ // whatever it likes; what changed is that the part inside our own
2650
+ // boundary stopped depending on somebody remembering to audit it.
2651
+ enforcedBy: "server",
2652
+ verifiedBy: "operator",
2653
+ source: "byollm_009 \xA711"
1059
2654
  })
1060
2655
  });
2656
+ var RETIRED_MUSTS = Object.freeze({
2657
+ RESULT_PROVENANCE: {
2658
+ supersededBy: "PROVENANCE_NAMES_DEVICE",
2659
+ note: "Strengthened, not renamed: attribution is now by proof of possession \u2014 the result's signature must verify against the device the upstream granted the lease to \u2014 rather than by a provenance label travelling beside it. byollm_009 \xA711 states the stronger form."
2660
+ }
2661
+ });
1061
2662
  var MUST_IDS = Object.freeze(Object.keys(MUSTS));
1062
2663
  function mustsVerifiedBy(kind) {
1063
- return MUST_IDS.filter((id) => MUSTS[id].verifiedBy === kind);
1064
- }
1065
-
1066
- // src/wire.ts
1067
- import { z as z8 } from "zod";
1068
- var PROTOCOL_VERSION = "0";
1069
- var SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
1070
- PROTOCOL_VERSION
1071
- ]);
1072
- var MIN_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0] ?? PROTOCOL_VERSION;
1073
- function checkProtocolVersion(body) {
1074
- const declared = typeof body === "object" && body !== null && Object.hasOwn(body, "protocolVersion") ? body.protocolVersion : void 0;
1075
- if (typeof declared !== "string" || declared.length === 0) {
1076
- return {
1077
- error: "unsupported-protocol-version",
1078
- message: "this request declared no protocol version. Upgrade the daemon: `npm i -g byollm@alpha`.",
1079
- supported: SUPPORTED_PROTOCOL_VERSIONS,
1080
- minimum: MIN_PROTOCOL_VERSION
1081
- };
1082
- }
1083
- if (!SUPPORTED_PROTOCOL_VERSIONS.includes(declared)) {
1084
- return {
1085
- error: "unsupported-protocol-version",
1086
- message: `this server speaks protocol ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")} and the daemon asked for ${declared}. ` + (declared < MIN_PROTOCOL_VERSION ? "Upgrade the daemon: `npm i -g byollm@alpha`." : "This daemon is newer than the server; the server needs upgrading."),
1087
- supported: SUPPORTED_PROTOCOL_VERSIONS,
1088
- minimum: MIN_PROTOCOL_VERSION
1089
- };
1090
- }
1091
- return null;
2664
+ return MUST_IDS.filter((id) => kindsOf(MUSTS[id]).includes(kind));
1092
2665
  }
1093
- var PROTOCOL_PREFIX = "/byollm";
1094
- var ENDPOINTS = Object.freeze([
1095
- "pair",
1096
- "claim",
1097
- "fetch",
1098
- "heartbeat",
1099
- "result",
1100
- "release"
1101
- ]);
1102
- var Capability = z8.object({
1103
- kind: JobKind,
1104
- backendId: BackendIdSchema,
1105
- backendClass: BackendClass,
1106
- model: z8.string().min(1),
1107
- offerScope: OfferScope
1108
- }).strict();
1109
- var CapabilityMatrix = z8.array(Capability);
1110
- var PairStartRequest = z8.object({
1111
- protocolVersion: z8.literal(PROTOCOL_VERSION),
1112
- action: z8.literal("start"),
1113
- daemon: z8.object({
1114
- version: z8.string().min(1),
1115
- /** Shown in the app's runner list so a user can tell their machines apart. */
1116
- label: z8.string().min(1).max(120),
1117
- platform: z8.enum(["darwin", "linux", "win32"])
1118
- }),
1119
- /**
1120
- * This machine's public keys (byollm_009 §5).
1121
- *
1122
- * Pairing is where the two parties learn each other's identities, because
1123
- * it is the one moment a human is already deciding to trust: the approval
1124
- * click. A key exchanged anywhere else would be a key nobody chose.
1125
- */
1126
- device: PublicIdentity,
1127
- capabilities: CapabilityMatrix
1128
- }).strict();
1129
- var PairStartResponse = z8.object({
1130
- /** Secret the daemon polls with. Never shown to the user. */
1131
- deviceCode: z8.string().min(20),
1132
- /** Short code the user reads and confirms in the browser. */
1133
- userCode: z8.string().min(4).max(16),
1134
- /** Where the user approves. Must be on the server's own origin. */
1135
- verificationUrl: z8.url(),
1136
- /** Epoch ms after which the code is dead ({@link MUSTS.PAIR_CODE_EXPIRES}). */
1137
- expiresAt: z8.number().int().positive(),
1138
- /** How often the daemon may poll. */
1139
- pollIntervalMs: z8.number().int().min(500).max(6e4)
1140
- }).strict();
1141
- var PairPollRequest = z8.object({
1142
- protocolVersion: z8.literal(PROTOCOL_VERSION),
1143
- action: z8.literal("poll"),
1144
- deviceCode: z8.string().min(20)
1145
- }).strict();
1146
- var PairPollResponse = z8.discriminatedUnion("status", [
1147
- z8.object({ status: z8.literal("pending") }).strict(),
1148
- z8.object({ status: z8.literal("denied") }).strict(),
1149
- z8.object({ status: z8.literal("expired") }).strict(),
1150
- z8.object({
1151
- status: z8.literal("approved"),
1152
- /** Bearer token for every later call. Scoped to exactly one user. */
1153
- runnerToken: z8.string().min(20),
1154
- runnerId: z8.string().min(1),
1155
- /** The app's id for the approving user — this daemon's owner forever. */
1156
- owner: z8.string().min(1),
1157
- /** Display name for the trust UI, if the app offers one. */
1158
- ownerLabel: z8.string().optional(),
1159
- /**
1160
- * The site's public keys, for the daemon to pin (byollm_009 §5).
1161
- *
1162
- * Returned only on approval — a pending or denied poll learns nothing,
1163
- * so an unapproved code cannot be used to enumerate a site's keys.
1164
- */
1165
- site: PublicIdentity
1166
- }).strict()
1167
- ]);
1168
- var PairRequest = z8.discriminatedUnion("action", [
1169
- PairStartRequest,
1170
- PairPollRequest
1171
- ]);
1172
- var ClaimRequest = z8.object({
1173
- protocolVersion: z8.literal(PROTOCOL_VERSION),
1174
- runnerId: z8.string().min(1),
1175
- /** Re-sent on every claim so a server never matches against a stale matrix. */
1176
- capabilities: CapabilityMatrix,
1177
- /** Upper bound on jobs to return; the server may return fewer. */
1178
- max: z8.number().int().min(1).max(64)
1179
- }).strict();
1180
- var ClaimResponse = z8.object({
1181
- /**
1182
- * Stubs, not jobs. The payload arrives from `fetch`, sealed to whichever
1183
- * device claimed — see {@link JobStub} for the exhaustive metadata list.
1184
- */
1185
- jobs: z8.array(ClaimedStub),
1186
- /** Lease duration granted, so the daemon knows its renewal deadline. */
1187
- leaseMs: z8.number().int().positive()
1188
- }).strict();
1189
- var HeartbeatRequest = z8.object({
1190
- protocolVersion: z8.literal(PROTOCOL_VERSION),
1191
- runnerId: z8.string().min(1),
1192
- daemonVersion: z8.string().min(1),
1193
- capabilities: CapabilityMatrix,
1194
- /**
1195
- * Leases this daemon believes it holds; the server renews exactly these.
1196
- *
1197
- * Lease ids rather than job ids, so a replayed heartbeat cannot renew a
1198
- * grant the runner no longer holds — see {@link Lease.id}.
1199
- */
1200
- activeLeases: z8.array(
1201
- z8.object({ jobId: z8.string().min(1), leaseId: z8.string().min(1) })
1202
- ),
1203
- /** True while the owner has the daemon paused; the server stops offering work. */
1204
- paused: z8.boolean()
1205
- }).strict();
1206
- var HeartbeatResponse = z8.object({
1207
- /** Once true, the daemon stops claiming and abandons in-flight work. */
1208
- revoked: z8.boolean(),
1209
- /**
1210
- * Per-job cancel (byollm_001 Rev 1 §C). The daemon aborts these jobs'
1211
- * in-flight backend calls and reports them `canceled`.
1212
- */
1213
- cancel: z8.array(z8.string().min(1)),
1214
- /** Jobs whose leases were renewed, with their new expiry. */
1215
- leases: z8.array(
1216
- z8.object({
1217
- jobId: z8.string().min(1),
1218
- expiresAt: z8.number().int().positive()
1219
- }).strict()
1220
- ),
1221
- /**
1222
- * Jobs the daemon thinks it holds but the server has reassigned or
1223
- * expired. The daemon must stop work on these and not report results.
1224
- */
1225
- lost: z8.array(z8.string().min(1)),
1226
- /** Server clock, so a daemon with a skewed clock still honors leases. */
1227
- serverTime: z8.number().int().positive()
1228
- }).strict();
1229
- var ResultDisposition = z8.enum(["ok", "error", "canceled"]);
1230
- var ResultRequest = z8.object({
1231
- protocolVersion: z8.literal(PROTOCOL_VERSION),
1232
- runnerId: z8.string().min(1),
1233
- jobId: z8.string().min(1),
1234
- /**
1235
- * The outcome, sealed to the site and signed by the device.
1236
- *
1237
- * The return leg of the payload envelope, and sealed for the same reason:
1238
- * a model's answer is as sensitive as the prompt that produced it, and an
1239
- * intermediary that cannot read one must not be handed the other.
1240
- */
1241
- envelope: SealedEnvelope,
1242
- /**
1243
- * The sealed outcome's discriminator, in the clear.
1244
- *
1245
- * Checked against the envelope once opened. It is a routing hint, not a
1246
- * fact: believing it unverified would let a daemon mark a job `ok` while
1247
- * sealing an error, and only the app would ever find out.
1248
- */
1249
- disposition: ResultDisposition,
1250
- /** Which model actually served it, for the result's provenance. */
1251
- model: z8.string().min(1),
1252
- backendClass: BackendClass,
1253
- /** Wall-clock milliseconds the backend call took. */
1254
- durationMs: z8.number().int().nonnegative()
1255
- }).strict();
1256
- var ResultResponse = z8.object({
1257
- /**
1258
- * False when the submission lost an idempotency race or the lease was
1259
- * already gone — the daemon should discard, not retry
1260
- * ({@link MUSTS.RESULT_IDEMPOTENT}).
1261
- */
1262
- accepted: z8.boolean(),
1263
- /** The job's state after this submission. */
1264
- state: z8.string().min(1)
1265
- }).strict();
1266
- var ReleaseRequest = z8.object({
1267
- protocolVersion: z8.literal(PROTOCOL_VERSION),
1268
- runnerId: z8.string().min(1),
1269
- /**
1270
- * Which leases to release — the grant, not just the job.
1271
- *
1272
- * A release naming only a job id releases whatever lease exists at the
1273
- * moment it arrives, which for a replayed request is not the lease the
1274
- * daemon meant. See {@link Lease.id}.
1275
- */
1276
- leases: z8.array(
1277
- z8.object({ jobId: z8.string().min(1), leaseId: z8.string().min(1) })
1278
- ),
1279
- /**
1280
- * Why, so the app's runner list can say something true.
1281
- *
1282
- * `refused` is load-bearing, not cosmetic: the server cannot evaluate a
1283
- * daemon's *local* `named` allowlist (§4.2), so it may legitimately offer
1284
- * a job this daemon then declines. The server MUST record the refusal and
1285
- * stop offering that job to that runner, or the pair would spin between
1286
- * claim and release forever.
1287
- */
1288
- reason: z8.enum(["shutdown", "pause", "revoked", "backend-down", "refused"])
1289
- }).strict();
1290
- var ReleaseResponse = z8.object({
1291
- released: z8.array(z8.string().min(1))
1292
- }).strict();
1293
- var WireErrorCode = z8.enum([
1294
- "bad-request",
1295
- "unsupported-protocol-version",
1296
- "unauthorized",
1297
- "revoked",
1298
- "not-found",
1299
- "rate-limited",
1300
- "server-error"
1301
- ]);
1302
- var WireError = z8.object({
1303
- error: WireErrorCode,
1304
- message: z8.string().min(1),
1305
- /** Seconds; mirrors Retry-After for `rate-limited` and `server-error`. */
1306
- retryAfter: z8.number().int().nonnegative().optional()
1307
- }).strict();
1308
- var ERROR_STATUS = Object.freeze({
1309
- "bad-request": 400,
1310
- "unsupported-protocol-version": 400,
1311
- unauthorized: 401,
1312
- revoked: 403,
1313
- "not-found": 404,
1314
- "rate-limited": 429,
1315
- "server-error": 500
1316
- });
1317
- var FetchRequest = z8.object({
1318
- protocolVersion: z8.string().min(1),
1319
- runnerId: z8.string().min(1),
1320
- jobId: z8.string().min(1),
1321
- /**
1322
- * The grant this daemon holds.
1323
- *
1324
- * Named, not inferred: a fetch is lease-scoped, and a request that names
1325
- * only the job would be answerable for whatever lease exists when it
1326
- * arrives ({@link Lease.id}).
1327
- */
1328
- leaseId: z8.string().min(1)
1329
- }).strict();
1330
- var FetchResponse = z8.object({
1331
- /**
1332
- * The work, sealed to the device that claimed it — byollm_009 §6.
1333
- *
1334
- * Not plaintext. The site opens its own at-rest envelope and re-seals to
1335
- * the claiming device's key, signed by the site's identity, so the work
1336
- * is readable only by the machine that took it and only if it came from
1337
- * the site that machine pinned.
1338
- */
1339
- envelope: SealedEnvelope
1340
- }).strict();
1341
2666
  export {
2667
+ ABOUT,
2668
+ ABOUT_SHORT,
2669
+ ABOUT_SHORT_LEDE,
2670
+ ABOUT_SHORT_TAIL,
1342
2671
  AUDIENCES,
1343
2672
  Audience,
1344
2673
  BACKENDS,
2674
+ BACKEND_CLASSES,
1345
2675
  BACKEND_IDS,
1346
2676
  BackendClass,
1347
2677
  BackendCost,
1348
2678
  BackendIdSchema,
2679
+ CLOCK_ATTRIBUTION_MS,
2680
+ CLOCK_SKEW_WARN_MS,
1349
2681
  Capability,
1350
2682
  CapabilityMatrix,
1351
2683
  ChatMessage,
@@ -1355,19 +2687,25 @@ export {
1355
2687
  ClaimedJob,
1356
2688
  ClaimedStub,
1357
2689
  DeliveredResult,
2690
+ ENCRYPTION_KEY_CONTEXT,
1358
2691
  ENDPOINTS,
1359
2692
  ENVELOPE_MAX_AGE_MS,
1360
2693
  ERROR_STATUS,
1361
2694
  EnvelopeDirection,
1362
2695
  FetchRequest,
1363
2696
  FetchResponse,
2697
+ GRANT_CONTEXT,
2698
+ GRANT_MAX_AGE_MS,
2699
+ GRANT_SIGNED_FIELDS,
1364
2700
  GeneratePayload,
2701
+ GrantRef,
1365
2702
  HeartbeatRequest,
1366
2703
  HeartbeatResponse,
1367
2704
  JOB_KINDS,
1368
2705
  JobKind,
1369
2706
  JobOutcome,
1370
2707
  JobPayload,
2708
+ JobRefused,
1371
2709
  JobResultCanceled,
1372
2710
  JobResultError,
1373
2711
  JobResultOk,
@@ -1376,9 +2714,13 @@ export {
1376
2714
  KindedPayload,
1377
2715
  Lease,
1378
2716
  MAX_CLOCK_SKEW_MS,
2717
+ MAX_ENVELOPE_BYTES,
2718
+ MAX_PURPOSES,
2719
+ MAX_SUCCESSION_CHAIN,
1379
2720
  MIN_PROTOCOL_VERSION,
1380
2721
  MUSTS,
1381
2722
  MUST_IDS,
2723
+ Manifest,
1382
2724
  MatchRefusal,
1383
2725
  OFFER_SCOPES,
1384
2726
  OfferScope,
@@ -1391,7 +2733,12 @@ export {
1391
2733
  PairStartRequest,
1392
2734
  PairStartResponse,
1393
2735
  PublicIdentity,
2736
+ Purpose,
1394
2737
  REFUSAL_MESSAGES,
2738
+ REFUSAL_TEXT,
2739
+ RESERVED_PURPOSE,
2740
+ RETIREMENT_WINDOW_MS,
2741
+ RefusalReason,
1395
2742
  ReleaseRequest,
1396
2743
  ReleaseResponse,
1397
2744
  RequestSignature,
@@ -1399,28 +2746,50 @@ export {
1399
2746
  ResultProvenance,
1400
2747
  ResultRequest,
1401
2748
  ResultResponse,
2749
+ RunMetadata,
2750
+ SIZE_CLASSES,
1402
2751
  SIZE_CLASS_LIMITS,
2752
+ SUCCESSION_CONTEXT,
1403
2753
  SUPPORTED_PROTOCOL_VERSIONS,
1404
2754
  SealedEnvelope,
2755
+ SealedOutcome,
2756
+ SignedGrant,
1405
2757
  SizeClass,
2758
+ StopReasonSchema,
1406
2759
  StoredKeys,
2760
+ Succession,
1407
2761
  TERMINAL_STATES,
2762
+ UPDATE_OFFER_SINCE,
2763
+ UPGRADE_COMMAND,
1408
2764
  WireError,
1409
2765
  WireErrorCode,
2766
+ WithheldKind,
1410
2767
  backendDescriptor,
2768
+ backendName,
1411
2769
  canTransition,
1412
2770
  canonicalRequest,
2771
+ checkDaemonFloor,
1413
2772
  checkProtocolVersion,
2773
+ classifyCost,
2774
+ compareVersions,
1414
2775
  cryptoReady,
2776
+ declaredVersion,
2777
+ describeBytes,
1415
2778
  effectiveOfferScope,
2779
+ envelopeBytes,
1416
2780
  fingerprint,
1417
2781
  generateKeys,
2782
+ grantStatement,
1418
2783
  isBackendId,
2784
+ isCloudTaggedModel,
1419
2785
  isJobKind,
1420
2786
  isLocalHost,
1421
2787
  isTerminal,
1422
2788
  keyId,
2789
+ kindsOf,
1423
2790
  matchAudience,
2791
+ mayOfferUpdate,
2792
+ mentionsWireField,
1424
2793
  mustsVerifiedBy,
1425
2794
  open,
1426
2795
  payloadTextLength,
@@ -1428,14 +2797,24 @@ export {
1428
2797
  publicIdentityOf,
1429
2798
  resolveCost,
1430
2799
  seal,
2800
+ signGrant,
1431
2801
  signRequest,
1432
2802
  signSiteRequest,
2803
+ signSuccession,
1433
2804
  signWith,
2805
+ singlePurposeManifest,
1434
2806
  sizeClassCeiling,
1435
2807
  sizeClassOf,
2808
+ successionStatement,
2809
+ tooLargeMessage,
2810
+ updateOfferFor,
2811
+ verifyGrant,
2812
+ verifyLink,
1436
2813
  verifyPublicIdentity,
1437
2814
  verifyRequest,
1438
2815
  verifySiteRequest,
1439
- verifyWith
2816
+ verifyWith,
2817
+ walkSuccession,
2818
+ withoutComments
1440
2819
  };
1441
2820
  //# sourceMappingURL=index.js.map