@byollm/server 0.1.0-alpha.4 → 0.1.0-alpha.7

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/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  > [!WARNING]
2
- > **Alpha (`0.1.0-alpha.4`) — under active development. Don't use this yet.**
2
+ > **Alpha (`0.1.0-alpha.7`) — under active development. Don't use this yet.**
3
3
  >
4
4
  > Install it deliberately: `npm install @byollm/server@alpha`.
5
5
  >
@@ -13,7 +13,20 @@
13
13
  > not an npm deprecation, which would read as *abandoned* rather than *early*.
14
14
  > Ask for `@alpha` explicitly so your lockfile records that you meant to.
15
15
  >
16
- > **`alpha.4` breaks every integration.** Three things changed for you:
16
+ > **`alpha.7` breaks nobody who is not implementing a relay.** `@byollm/relay`'s
17
+ > projection gains `devices` — the device keys a control plane has approved —
18
+ > and the relay refuses to pair a device that is not in it. `revoked` becomes
19
+ > `{owner, siteId}` instead of a composite string. Sites, daemons, stores and
20
+ > the wire format are all untouched; no runner re-pairs.
21
+ >
22
+ > **`alpha.5` broke store adapters, and nothing else.** If you implement
23
+ > `JobStore` yourself, two changes are required: a new `adopt(args)` method
24
+ > (record a lease granted by an upstream this store does not own), and
25
+ > `CompleteArgs.runnerId` is replaced by `holder` — a discriminated union
26
+ > naming either a runner or a lease. Apps, daemons and the wire format are
27
+ > unaffected; `@byollm/conformance` will tell you if you missed one.
28
+ >
29
+ > **`alpha.4` broke every integration.** Three things changed for you:
17
30
  >
18
31
  > 1. **`siteKeys` is required.** Run `npx @byollm/server@alpha keygen` once,
19
32
  > set `BYOLLM_SITE_KEYS`, and pass it to `ByollmApp` and `createHandler`.
@@ -43,13 +43,11 @@ var generateLeaseId = () => randomUUID();
43
43
 
44
44
  // src/handlers.ts
45
45
  import {
46
- ENVELOPE_MAX_AGE_MS,
47
46
  FetchRequest,
48
- seal,
49
47
  JobOutcome,
50
- keyId,
51
- open,
52
- publicIdentityOf,
48
+ keyId as keyId2,
49
+ open as open2,
50
+ publicIdentityOf as publicIdentityOf2,
53
51
  RequestSignature,
54
52
  verifyRequest,
55
53
  verifyPublicIdentity,
@@ -62,6 +60,49 @@ import {
62
60
  ResultRequest,
63
61
  provenanceFor
64
62
  } from "@byollm/protocol";
63
+
64
+ // src/reseal.ts
65
+ import {
66
+ ENVELOPE_MAX_AGE_MS,
67
+ keyId,
68
+ open,
69
+ publicIdentityOf,
70
+ seal
71
+ } from "@byollm/protocol";
72
+ async function resealForDevice(input) {
73
+ const senderKeyId = keyId(publicIdentityOf(input.siteKeys).identity);
74
+ const opened = await open({
75
+ envelope: input.job.envelope,
76
+ recipientKeys: input.siteKeys,
77
+ senderIdentityPublic: input.siteKeys.identityPublic,
78
+ expected: {
79
+ jobId: input.job.id,
80
+ senderKeyId,
81
+ recipientKeyId: senderKeyId,
82
+ direction: "payload"
83
+ }
84
+ });
85
+ if (!opened.ok) {
86
+ return { ok: false, reason: "unopenable" };
87
+ }
88
+ const envelope = await seal({
89
+ plaintext: opened.plaintext,
90
+ senderKeys: input.siteKeys,
91
+ recipientEncryptionPublic: input.device.encryption,
92
+ context: {
93
+ jobId: input.job.id,
94
+ senderKeyId,
95
+ recipientKeyId: keyId(input.device.identity),
96
+ // From the record, never recomputed from a fresh clock read — the
97
+ // envelope's own deadline is what the signature bound.
98
+ deadlineAt: input.job.createdAt + ENVELOPE_MAX_AGE_MS,
99
+ direction: "payload"
100
+ }
101
+ });
102
+ return { ok: true, envelope };
103
+ }
104
+
105
+ // src/handlers.ts
65
106
  var DEFAULTS = {
66
107
  leaseMs: 6e4,
67
108
  pairingTtlMs: 10 * 6e4,
@@ -91,7 +132,7 @@ var ByollmHandlers = class {
91
132
  #siteKeys;
92
133
  constructor(config) {
93
134
  this.#store = config.store;
94
- if (!verifyPublicIdentity(publicIdentityOf(config.siteKeys))) {
135
+ if (!verifyPublicIdentity(publicIdentityOf2(config.siteKeys))) {
95
136
  throw new Error(
96
137
  "siteKeys are not internally consistent: the encryption key is not signed by the identity key. Generate a fresh pair with `npx @byollm/server keygen`."
97
138
  );
@@ -188,34 +229,15 @@ var ByollmHandlers = class {
188
229
  if (!job || job.lease?.runnerId !== runner.id || job.lease.id !== request.leaseId) {
189
230
  return fail("not-found", "no such lease on this job");
190
231
  }
191
- const senderKeyId = keyId(publicIdentityOf(this.#siteKeys).identity);
192
- const opened = await open({
193
- envelope: job.envelope,
194
- recipientKeys: this.#siteKeys,
195
- senderIdentityPublic: this.#siteKeys.identityPublic,
196
- expected: {
197
- jobId: job.id,
198
- senderKeyId,
199
- recipientKeyId: senderKeyId,
200
- direction: "payload"
201
- }
232
+ const resealed = await resealForDevice({
233
+ siteKeys: this.#siteKeys,
234
+ job: { id: job.id, envelope: job.envelope, createdAt: job.createdAt },
235
+ device: runner.device
202
236
  });
203
- if (!opened.ok) {
237
+ if (!resealed.ok) {
204
238
  return fail("server-error", "this job's payload could not be opened");
205
239
  }
206
- const resealed = await seal({
207
- plaintext: opened.plaintext,
208
- senderKeys: this.#siteKeys,
209
- recipientEncryptionPublic: runner.device.encryption,
210
- context: {
211
- jobId: job.id,
212
- senderKeyId,
213
- recipientKeyId: keyId(runner.device.identity),
214
- deadlineAt: job.createdAt + ENVELOPE_MAX_AGE_MS,
215
- direction: "payload"
216
- }
217
- });
218
- return ok({ envelope: resealed });
240
+ return ok({ envelope: resealed.envelope });
219
241
  }
220
242
  // -- 1. pair --------------------------------------------------------------
221
243
  async #pair(body) {
@@ -279,7 +301,7 @@ var ByollmHandlers = class {
279
301
  owner: pairing.owner,
280
302
  // Only on approval: a pending or denied poll learns nothing, so an
281
303
  // unapproved code cannot be used to enumerate a site's keys.
282
- site: publicIdentityOf(this.#siteKeys)
304
+ site: publicIdentityOf2(this.#siteKeys)
283
305
  };
284
306
  await this.#store.consumePairingToken(pairing.deviceCodeHash);
285
307
  return ok(response);
@@ -390,7 +412,7 @@ var ByollmHandlers = class {
390
412
  });
391
413
  const { accepted, job: updated } = await this.#store.complete({
392
414
  jobId: request.jobId,
393
- runnerId: runner.id,
415
+ holder: { by: "runner", runnerId: runner.id },
394
416
  outcome: outcome.value,
395
417
  provenance,
396
418
  now
@@ -417,14 +439,14 @@ var ByollmHandlers = class {
417
439
  */
418
440
  async #openResult(request, runner) {
419
441
  const refuse = (why) => ({ ok: false, failure: fail("bad-request", why) });
420
- const opened = await open({
442
+ const opened = await open2({
421
443
  envelope: request.envelope,
422
444
  recipientKeys: this.#siteKeys,
423
445
  senderIdentityPublic: runner.device.identity,
424
446
  expected: {
425
447
  jobId: request.jobId,
426
- senderKeyId: keyId(runner.device.identity),
427
- recipientKeyId: keyId(publicIdentityOf(this.#siteKeys).identity),
448
+ senderKeyId: keyId2(runner.device.identity),
449
+ recipientKeyId: keyId2(publicIdentityOf2(this.#siteKeys).identity),
428
450
  direction: "result"
429
451
  }
430
452
  });
@@ -590,10 +612,11 @@ export {
590
612
  hashSecret,
591
613
  secretsMatch,
592
614
  generateLeaseId,
615
+ resealForDevice,
593
616
  ByollmHandlers,
594
617
  SERVED_PROTOCOL_VERSION,
595
618
  routeEndpoint,
596
619
  signatureFrom,
597
620
  createFetchHandler
598
621
  };
599
- //# sourceMappingURL=chunk-MGJX6626.js.map
622
+ //# sourceMappingURL=chunk-4NIHWQAT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ids.ts","../src/handlers.ts","../src/reseal.ts","../src/http.ts"],"sourcesContent":["import {\n createHash,\n randomBytes,\n randomUUID,\n timingSafeEqual,\n} from \"node:crypto\";\n\n/**\n * Alphabet for the user-facing pairing code.\n *\n * Excludes `0/O`, `1/I/L`, `5/S` and `U/V` — a code is read aloud or copied\n * off a terminal into a browser, and a user who mistypes it gets a failure\n * they cannot diagnose. 27 symbols over 8 characters is ~38 bits, which is\n * ample for a code that lives ten minutes, is single-use, and is rate-limited.\n */\nconst USER_CODE_ALPHABET = \"ABCDEFGHJKMNPQRTWXYZ2346789\";\n\n/** A device code: the secret the daemon polls with. Never shown to a user. */\nexport function generateDeviceCode(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\n/** A runner bearer token. */\nexport function generateRunnerToken(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\n/** A runner id. */\nexport function generateRunnerId(): string {\n return `runner_${randomUUID()}`;\n}\n\n/** A job id. */\nexport function generateJobId(): string {\n // A bare UUID, not a prefixed one.\n //\n // The app mints this now, because byollm_009 §6 binds the job id into the\n // envelope's signature — so the id must exist before the row does. A\n // `job_`-prefixed string is not a `uuid`, and the Supabase adapter's column\n // is, so the prefix would have made every enqueue fail there while passing\n // in memory. Ids are opaque to the protocol; the prefix was only ever\n // decoration.\n return randomUUID();\n}\n\n/**\n * A short code the user reads and confirms, formatted `XXXX-XXXX`.\n * Drawn with rejection sampling so the alphabet stays uniform.\n */\nexport function generateUserCode(): string {\n const chars: string[] = [];\n while (chars.length < 8) {\n for (const byte of randomBytes(16)) {\n // 256 % 28 !== 0, so bytes at or above the largest whole multiple are\n // discarded rather than folded — folding would bias the low symbols.\n const limit = 256 - (256 % USER_CODE_ALPHABET.length);\n if (byte >= limit) continue;\n const symbol = USER_CODE_ALPHABET[byte % USER_CODE_ALPHABET.length];\n if (symbol === undefined) continue;\n chars.push(symbol);\n if (chars.length === 8) break;\n }\n }\n return `${chars.slice(0, 4).join(\"\")}-${chars.slice(4).join(\"\")}`;\n}\n\n/** SHA-256, hex. Tokens and device codes are stored only as this. */\nexport function hashSecret(secret: string): string {\n return createHash(\"sha256\").update(secret, \"utf8\").digest(\"hex\");\n}\n\n/**\n * Compare two hex digests without leaking their difference through timing.\n * Lengths are compared first because `timingSafeEqual` throws on a mismatch.\n */\nexport function secretsMatch(aHex: string, bHex: string): boolean {\n if (aHex.length !== bHex.length) return false;\n return timingSafeEqual(Buffer.from(aHex, \"hex\"), Buffer.from(bHex, \"hex\"));\n}\n\n/**\n * A fresh id for one lease grant.\n *\n * Not a secret and not guessed at — a daemon is told its lease id in the claim\n * response. It exists to distinguish *this* grant from the next one over the\n * same job by the same runner, which is what stops a replayed release landing\n * on a lease the sender never meant.\n */\nexport const generateLeaseId = (): string => randomUUID();\n","import {\n FetchRequest,\n JobOutcome,\n keyId,\n open,\n publicIdentityOf,\n type FetchResponse,\n RequestSignature,\n verifyRequest,\n verifyPublicIdentity,\n type StoredKeys,\n ClaimRequest,\n type ClaimRequest as ClaimRequestType,\n type HeartbeatRequest as HeartbeatRequestType,\n type ReleaseRequest as ReleaseRequestType,\n type ResultRequest as ResultRequestType,\n ERROR_STATUS,\n HeartbeatRequest,\n PairRequest,\n PROTOCOL_VERSION,\n ReleaseRequest,\n ResultRequest,\n provenanceFor,\n type ClaimResponse,\n type Endpoint,\n type HeartbeatResponse,\n type PairPollResponse,\n type PairStartResponse,\n type ReleaseResponse,\n type ResultResponse,\n type WireErrorCode,\n} from \"@byollm/protocol\";\nimport { generateDeviceCode, generateUserCode, hashSecret } from \"./ids.js\";\nimport { resealForDevice } from \"./reseal.js\";\nimport type { JobRecord, RunnerRecord } from \"./records.js\";\nimport type { ByollmStore } from \"./store.js\";\n\n/** Everything a mount needs to serve the protocol. */\n/**\n * What a transport must hand the handler to authenticate a call.\n *\n * `rawBody` is the exact bytes received, not a re-serialisation of the parsed\n * object: JSON.stringify does not round-trip byte-for-byte, and a signature\n * over re-serialised input verifies something the sender never signed.\n */\nexport interface AuthContext {\n readonly endpoint: string;\n readonly rawBody: string;\n readonly signature: unknown;\n}\n\nexport interface HandlerConfig {\n readonly store: ByollmStore;\n /**\n * Absolute URL of the page where a user approves a pairing. The device code\n * is *not* appended — the user types the short code into the app's own\n * authenticated page, which is what keeps pairing interactive.\n */\n readonly verificationUrl: string;\n /** How long a lease lasts. Default 60s — six heartbeats of headroom. */\n readonly leaseMs?: number;\n /** How long an unapproved pairing code lives. Default 10 minutes. */\n readonly pairingTtlMs?: number;\n /** How often a daemon may poll for pairing approval. Default 2s. */\n readonly pollIntervalMs?: number;\n /** Injectable clock, so tests can move time without sleeping. */\n readonly now?: () => number;\n /**\n * This site's keypairs (byollm_009 §5) — **supplied, never generated here.**\n *\n * A site is usually more than one process. Generating keys at startup would\n * work perfectly in development and fail only in production, silently: each\n * instance would have a different identity, a daemon would pin whichever\n * one approved its pairing, and every request routed to a different\n * instance would fail a signature check it had no way to explain. So this\n * is a required input, and there is a `keygen` script that produces one.\n */\n readonly siteKeys: StoredKeys;\n}\n\nconst DEFAULTS = {\n leaseMs: 60_000,\n pairingTtlMs: 10 * 60_000,\n pollIntervalMs: 2_000,\n} as const;\n\n/** A handled protocol call: a status and a JSON body. */\nexport interface HandlerResult {\n readonly status: number;\n readonly body: unknown;\n /** Set for `rate-limited` and `server-error`. */\n readonly retryAfterSeconds?: number;\n}\n\nfunction fail(\n error: WireErrorCode,\n message: string,\n retryAfterSeconds?: number,\n): HandlerResult {\n return {\n status: ERROR_STATUS[error],\n body: {\n error,\n message,\n ...(retryAfterSeconds === undefined\n ? {}\n : { retryAfter: retryAfterSeconds }),\n },\n ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }),\n };\n}\n\nfunction ok(body: unknown): HandlerResult {\n return { status: 200, body };\n}\n\n/**\n * The five protocol endpoints, over any {@link ByollmStore}.\n *\n * Transport-free on purpose: a mount adapts `Request`/`Response` (or Express,\n * or whatever) onto {@link ByollmHandlers.handle}, and everything the\n * protocol actually specifies lives here where the conformance kit can reach\n * it without an HTTP server in the way.\n */\nexport class ByollmHandlers {\n readonly #store: ByollmStore;\n readonly #verificationUrl: string;\n readonly #leaseMs: number;\n readonly #pairingTtlMs: number;\n readonly #pollIntervalMs: number;\n readonly #now: () => number;\n readonly #siteKeys: StoredKeys;\n\n constructor(config: HandlerConfig) {\n this.#store = config.store;\n // Fail at construction, not at the first pairing. A site whose keys are\n // malformed should not start and then refuse its users one at a time.\n if (!verifyPublicIdentity(publicIdentityOf(config.siteKeys))) {\n throw new Error(\n \"siteKeys are not internally consistent: the encryption key is not \" +\n \"signed by the identity key. Generate a fresh pair with \" +\n \"`npx @byollm/server keygen`.\",\n );\n }\n this.#siteKeys = config.siteKeys;\n this.#verificationUrl = config.verificationUrl;\n this.#leaseMs = config.leaseMs ?? DEFAULTS.leaseMs;\n this.#pairingTtlMs = config.pairingTtlMs ?? DEFAULTS.pairingTtlMs;\n this.#pollIntervalMs = config.pollIntervalMs ?? DEFAULTS.pollIntervalMs;\n this.#now = config.now ?? Date.now;\n }\n\n /**\n * Dispatch one protocol call.\n *\n * @param endpoint - which of the five, already routed from the path\n * @param body - the parsed JSON request body, untrusted\n * @param auth - the signature and the exact bytes it covers\n */\n async handle(\n endpoint: Endpoint,\n body: unknown,\n auth: AuthContext,\n ): Promise<HandlerResult> {\n switch (endpoint) {\n case \"pair\":\n return this.#pair(body);\n case \"claim\":\n return this.#authed(auth, body, ClaimRequest, this.#claim.bind(this));\n case \"heartbeat\":\n // Heartbeat is the channel revocation travels on, so a revoked runner\n // must reach the handler and be told `revoked: true` rather than be\n // bounced with a 403 it would treat as a transport problem\n // ({@link MUSTS.REVOCATION_HONORED}).\n return this.#authed(\n auth,\n body,\n HeartbeatRequest,\n this.#heartbeat.bind(this),\n { allowRevoked: true },\n );\n case \"fetch\":\n return this.#authed(auth, body, FetchRequest, this.#fetch.bind(this));\n case \"result\":\n return this.#authed(auth, body, ResultRequest, this.#result.bind(this));\n case \"release\":\n return this.#authed(\n auth,\n body,\n ReleaseRequest,\n this.#release.bind(this),\n );\n }\n }\n\n /**\n * Shared preamble for the four authenticated endpoints: verify the\n * signature, reject a revoked runner, and parse the body.\n *\n * Authentication happens before schema validation so a stranger probing the\n * endpoint learns nothing about the wire format.\n */\n async #authed<T>(\n auth: AuthContext,\n body: unknown,\n schema: { safeParse: (v: unknown) => { success: boolean; data?: T } },\n run: (request: T, runner: RunnerRecord) => Promise<HandlerResult>,\n options: { allowRevoked?: boolean } = {},\n ): Promise<HandlerResult> {\n const signature = RequestSignature.safeParse(auth.signature);\n if (!signature.success) {\n return fail(\"unauthorized\", \"this request is not signed\");\n }\n\n const runner = await this.#store.getRunner(signature.data.runnerId);\n if (!runner) {\n return fail(\"unauthorized\", \"this runner is not recognised\");\n }\n\n // Verified against the identity pinned when the user approved this\n // machine — not against anything the request carries. A signature that\n // authenticates itself authenticates nothing.\n const failure = verifyRequest({\n identityPublic: runner.device.identity,\n endpoint: auth.endpoint,\n body: auth.rawBody,\n signature: signature.data,\n now: this.#now(),\n });\n if (failure !== null) {\n // Deliberately one message for both causes. Telling a caller whether\n // their clock or their key is wrong tells an attacker which half of a\n // forgery already works.\n return fail(\"unauthorized\", \"this request's signature is not valid\");\n }\n if (runner.revokedAt !== null && options.allowRevoked !== true) {\n // A distinct truth from \"unauthorized\": the daemon should stop and say\n // so, not retry or re-pair silently.\n return fail(\"revoked\", \"this runner has been revoked by its owner\");\n }\n\n const parsed = schema.safeParse(body);\n if (!parsed.success || parsed.data === undefined) {\n return fail(\"bad-request\", \"request body failed schema validation\");\n }\n return run(parsed.data, runner);\n }\n\n /**\n * Hand over the payload for a lease this runner holds — byollm_009 §6.\n *\n * The second half of claim-then-fetch. A claim answers with a stub, and the\n * work itself is collected separately by the device that took it, because a\n * payload can only be sealed once its recipient is known.\n *\n * Scoped to the lease, not the job: answering for whatever lease happens to\n * exist would hand the work to a runner whose grant had already been\n * superseded.\n */\n async #fetch(\n request: FetchRequest,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n const job = await this.#store.get(request.jobId);\n if (\n !job ||\n job.lease?.runnerId !== runner.id ||\n job.lease.id !== request.leaseId\n ) {\n // One answer for \"no such job\", \"not yours\" and \"a lease you no longer\n // hold\". A caller who is allowed to know already knows which.\n return fail(\"not-found\", \"no such lease on this job\");\n }\n // One implementation of open-and-reseal, shared with the cloud lane: the\n // deadline and key ids are bound into a signature, and two copies of a\n // bound value is the bug this codebase keeps finding.\n const resealed = await resealForDevice({\n siteKeys: this.#siteKeys,\n job: { id: job.id, envelope: job.envelope, createdAt: job.createdAt },\n device: runner.device,\n });\n if (!resealed.ok) {\n return fail(\"server-error\", \"this job's payload could not be opened\");\n }\n return ok({ envelope: resealed.envelope } satisfies FetchResponse);\n }\n\n // -- 1. pair --------------------------------------------------------------\n\n async #pair(body: unknown): Promise<HandlerResult> {\n const parsed = PairRequest.safeParse(body);\n if (!parsed.success) {\n return fail(\"bad-request\", \"pair request failed schema validation\");\n }\n const request = parsed.data;\n const now = this.#now();\n\n if (request.action === \"start\") {\n const deviceCode = generateDeviceCode();\n const userCode = generateUserCode();\n const expiresAt = now + this.#pairingTtlMs;\n\n // The machine must prove its encryption key belongs to the identity it\n // is presenting, before either is stored. Otherwise a caller could pair\n // a real identity with an encryption key it holds the secret for, and\n // read everything later sealed to that runner.\n if (!verifyPublicIdentity(request.device)) {\n return fail(\n \"bad-request\",\n \"the device's encryption key is not signed by the identity it was presented with\",\n );\n }\n\n await this.#store.createPairing({\n device: request.device,\n deviceCodeHash: hashSecret(deviceCode),\n userCode,\n state: \"pending\",\n owner: null,\n runnerId: null,\n runnerTokenOnce: null,\n label: request.daemon.label,\n platform: request.daemon.platform,\n daemonVersion: request.daemon.version,\n capabilities: request.capabilities,\n expiresAt,\n createdAt: now,\n });\n\n const response: PairStartResponse = {\n deviceCode,\n userCode,\n verificationUrl: this.#verificationUrl,\n expiresAt,\n pollIntervalMs: this.#pollIntervalMs,\n };\n return ok(response);\n }\n\n // action === \"poll\"\n const pairing = await this.#store.getPairingByDeviceCodeHash(\n hashSecret(request.deviceCode),\n );\n if (!pairing) {\n return fail(\"not-found\", \"unknown device code\");\n }\n if (pairing.state === \"denied\") {\n return ok({ status: \"denied\" } satisfies PairPollResponse);\n }\n // Expiry is checked before approval state so a code approved after it\n // lapsed is still dead ({@link MUSTS.PAIR_CODE_EXPIRES}).\n if (pairing.expiresAt <= now && pairing.state === \"pending\") {\n return ok({ status: \"expired\" } satisfies PairPollResponse);\n }\n if (\n pairing.state === \"approved\" &&\n pairing.runnerTokenOnce !== null &&\n pairing.runnerId !== null &&\n pairing.owner !== null\n ) {\n const response: PairPollResponse = {\n status: \"approved\",\n runnerToken: pairing.runnerTokenOnce,\n runnerId: pairing.runnerId,\n owner: pairing.owner,\n // Only on approval: a pending or denied poll learns nothing, so an\n // unapproved code cannot be used to enumerate a site's keys.\n site: publicIdentityOf(this.#siteKeys),\n };\n // Delivered exactly once — a replayed device code gets nothing.\n await this.#store.consumePairingToken(pairing.deviceCodeHash);\n return ok(response);\n }\n if (pairing.state === \"approved\") {\n return fail(\"not-found\", \"this pairing has already been collected\");\n }\n return ok({ status: \"pending\" } satisfies PairPollResponse);\n }\n\n // -- 2. claim -------------------------------------------------------------\n\n async #claim(\n request: ClaimRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const now = this.#now();\n\n // Capabilities from *this* request, never the stored matrix — a daemon\n // that just lost a backend must not be handed work for it\n // ({@link MUSTS.CLAIM_REQUIRES_CAPABILITY}).\n const jobs = await this.#store.claim({\n runnerId: runner.id,\n runnerOwner: runner.owner,\n capabilities: request.capabilities,\n max: request.max,\n leaseMs: this.#leaseMs,\n now,\n });\n\n const response: ClaimResponse = {\n jobs: jobs.map((job) => ({\n id: job.id,\n kind: job.kind,\n audience: job.audience,\n owner: job.owner,\n // Bucketed, not measured: an exact size is a stronger fingerprint\n // than routing needs (byollm_009 §6).\n sizeClass: job.sizeClass,\n // Reserved for byollm_006; no job declares it yet.\n streaming: false,\n // The stub's deadline bounds how long a captured envelope is worth\n // keeping, so it is always present — falling back to the TTL window\n // when the app named no absolute one.\n deadlineAt: job.deadlineAt ?? (job.claimableAt ?? now) + job.ttlMs,\n ...(job.audienceAllow === undefined\n ? {}\n : { audienceAllow: [...job.audienceAllow] }),\n // No fallback. A job returned from `claim` holds a lease by\n // definition, and synthesising one here would hand the daemon a lease\n // id the store has never heard of — every later release naming it\n // would silently match nothing. A store that returns an unleased job\n // has broken its contract, and this says so.\n lease: leaseOf(job),\n })),\n leaseMs: this.#leaseMs,\n };\n return ok(response);\n }\n\n // -- 3. heartbeat ---------------------------------------------------------\n\n async #heartbeat(\n request: HeartbeatRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const now = this.#now();\n const revoked = runner.revokedAt !== null;\n\n if (revoked) {\n // Nothing is renewed for a revoked runner: every job it holds is\n // reported lost so it abandons the queue rather than finishing it.\n const held = await this.#store.listClaimedBy(runner.id);\n const response: HeartbeatResponse = {\n revoked: true,\n cancel: [],\n leases: [],\n lost: held.map((job) => job.id),\n serverTime: now,\n };\n return ok(response);\n }\n\n await this.#store.touchRunner({\n runnerId: runner.id,\n capabilities: request.capabilities,\n daemonVersion: request.daemonVersion,\n paused: request.paused,\n now,\n });\n\n const { renewed, lost } = await this.#store.renewLeases({\n runnerId: runner.id,\n leases: request.activeLeases,\n leaseMs: this.#leaseMs,\n now,\n });\n\n const cancel = await this.#store.listCancelRequests(runner.id);\n\n const response: HeartbeatResponse = {\n revoked: false,\n cancel,\n leases: renewed.map((r) => ({ jobId: r.jobId, expiresAt: r.expiresAt })),\n lost: [...lost],\n serverTime: now,\n };\n return ok(response);\n }\n\n // -- 4. result ------------------------------------------------------------\n\n async #result(\n request: ResultRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const now = this.#now();\n const job = await this.#store.get(request.jobId);\n if (!job) return fail(\"not-found\", \"unknown job\");\n\n const outcome = await this.#openResult(request, runner);\n if (!outcome.ok) return outcome.failure;\n\n // Provenance is built here, from the job's audience and the authenticated\n // runner — never from anything the daemon asserted\n // ({@link MUSTS.RESULT_PROVENANCE}).\n const provenance = provenanceFor({\n audience: job.audience,\n runnerId: runner.id,\n runnerOwner: runner.owner,\n backendClass: request.backendClass,\n model: request.model,\n });\n\n const { accepted, job: updated } = await this.#store.complete({\n jobId: request.jobId,\n holder: { by: \"runner\", runnerId: runner.id },\n outcome: outcome.value,\n provenance,\n now,\n });\n\n const response: ResultResponse = {\n accepted,\n state: updated?.state ?? job.state,\n };\n return ok(response);\n }\n\n /**\n * Open a sealed result, or refuse it.\n *\n * The mirror of the daemon's `#openPayload`, and refuses for the same\n * reason: an outcome that does not verify against the device's pinned key is\n * an assertion by whoever relayed it, and storing it would let an\n * intermediary write answers into the app.\n *\n * The clear-text `disposition` is checked here rather than trusted. It is on\n * the wire so a relay can route without opening anything, which means the\n * one thing it must not be is authoritative — a daemon that sealed an error\n * and declared `ok` would otherwise have its declaration believed by\n * everything upstream of this line.\n */\n async #openResult(\n request: ResultRequestType,\n runner: RunnerRecord,\n ): Promise<\n { ok: true; value: JobOutcome } | { ok: false; failure: HandlerResult }\n > {\n const refuse = (why: string) =>\n ({ ok: false as const, failure: fail(\"bad-request\", why) }) as const;\n\n const opened = await open({\n envelope: request.envelope,\n recipientKeys: this.#siteKeys,\n senderIdentityPublic: runner.device.identity,\n expected: {\n jobId: request.jobId,\n senderKeyId: keyId(runner.device.identity),\n recipientKeyId: keyId(publicIdentityOf(this.#siteKeys).identity),\n direction: \"result\",\n },\n });\n if (!opened.ok) {\n return refuse(\"the result did not verify as coming from this device\");\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(opened.plaintext);\n } catch {\n return refuse(\"the sealed result was not valid JSON\");\n }\n const outcome = JobOutcome.safeParse(parsed);\n if (!outcome.success) return refuse(\"the sealed result was not an outcome\");\n\n if (outcome.data.outcome !== request.disposition) {\n return refuse(\"the declared disposition is not the one that was sealed\");\n }\n return { ok: true, value: outcome.data };\n }\n\n // -- 5. release -----------------------------------------------------------\n\n async #release(\n request: ReleaseRequestType,\n runner: RunnerRecord,\n ): Promise<HandlerResult> {\n if (request.runnerId !== runner.id) {\n return fail(\"unauthorized\", \"runner id does not match the signing key\");\n }\n const released = await this.#store.release({\n runnerId: runner.id,\n leases: request.leases,\n reason: request.reason,\n now: this.#now(),\n });\n const response: ReleaseResponse = { released };\n return ok(response);\n }\n}\n\n/** The protocol version this build speaks. */\nexport const SERVED_PROTOCOL_VERSION = PROTOCOL_VERSION;\n\n/** The lease a claimed job must have, or a loud failure. */\nfunction leaseOf(job: JobRecord): NonNullable<JobRecord[\"lease\"]> {\n if (!job.lease) {\n throw new Error(\n `store returned job ${job.id} from claim with no lease — the store ` +\n `contract requires a claimed job to hold one`,\n );\n }\n return job.lease;\n}\n","import {\n ENVELOPE_MAX_AGE_MS,\n keyId,\n open,\n publicIdentityOf,\n seal,\n type PublicIdentity,\n type SealedEnvelope,\n type StoredKeys,\n} from \"@byollm/protocol\";\n\n/**\n * Open this site's own at-rest envelope and re-seal it to a claiming device.\n *\n * The single operation that makes byollm_009 §6 work, and it now has two\n * callers: {@link ByollmHandlers} answering `fetch` on the direct plane, and\n * the cloud lane answering the relay's \"who claimed it\" poll. Both do exactly\n * this, and the reason it lives in one file is the reason everything else in\n * this codebase does: the deadline, the key ids and the direction are all\n * bound into a signature, and two implementations of a bound value is the same\n * bug as two clock readings — it works until they disagree, and then nothing\n * opens.\n *\n * The plaintext exists for one statement and never reaches a wire, a store, or\n * a log. That is the whole guarantee: the site is an endpoint, so it is\n * entitled to read its own work, and it is the only party between the app and\n * the device that is.\n */\n\ntype ResealFailure = \"unopenable\";\n\nexport type ResealResult =\n | { readonly ok: true; readonly envelope: SealedEnvelope }\n | { readonly ok: false; readonly reason: ResealFailure };\n\nexport async function resealForDevice(input: {\n siteKeys: StoredKeys;\n /** The job's identity and its at-rest ciphertext. */\n job: {\n readonly id: string;\n readonly envelope: SealedEnvelope;\n readonly createdAt: number;\n };\n /** The device that claimed it, as the upstream reported. */\n device: PublicIdentity;\n}): Promise<ResealResult> {\n const senderKeyId = keyId(publicIdentityOf(input.siteKeys).identity);\n\n const opened = await open({\n envelope: input.job.envelope,\n recipientKeys: input.siteKeys,\n senderIdentityPublic: input.siteKeys.identityPublic,\n expected: {\n jobId: input.job.id,\n senderKeyId,\n recipientKeyId: senderKeyId,\n direction: \"payload\",\n },\n });\n if (!opened.ok) {\n // The store holds something this site cannot open: rotated keys, a\n // corrupted row, or someone else's envelope. Not the device's problem and\n // not something a retry fixes.\n return { ok: false, reason: \"unopenable\" };\n }\n\n const envelope = await seal({\n plaintext: opened.plaintext,\n senderKeys: input.siteKeys,\n recipientEncryptionPublic: input.device.encryption,\n context: {\n jobId: input.job.id,\n senderKeyId,\n recipientKeyId: keyId(input.device.identity),\n // From the record, never recomputed from a fresh clock read — the\n // envelope's own deadline is what the signature bound.\n deadlineAt: input.job.createdAt + ENVELOPE_MAX_AGE_MS,\n direction: \"payload\",\n },\n });\n return { ok: true, envelope };\n}\n","import {\n ENDPOINTS,\n ERROR_STATUS,\n PROTOCOL_PREFIX,\n checkProtocolVersion,\n type Endpoint,\n} from \"@byollm/protocol\";\nimport { ByollmHandlers, type HandlerConfig } from \"./handlers.js\";\n\n/**\n * Largest protocol request body accepted, before schema validation.\n *\n * A payload is capped at 4 MB of text by the protocol; this leaves room for\n * JSON overhead and a batch of results, and refuses anything wilder at the\n * door rather than after parsing it.\n */\nconst MAX_BODY_BYTES = 8 * 1024 * 1024;\n\n/**\n * Where the protocol endpoints are mounted.\n *\n * Defaults to {@link PROTOCOL_PREFIX}. Pass the real mount point when it is\n * anything else — a Next.js route at `app/api/byollm/[...route]/route.ts`\n * serves `/api/byollm/...`, so it needs `basePath: \"/api/byollm\"`.\n *\n * @throws if the path is not an absolute, single-segment-per-slash path. A\n * mount point is configuration, and a malformed one should fail at startup\n * rather than silently match nothing.\n */\nfunction normalizeBasePath(basePath: string): string {\n const trimmed = basePath.endsWith(\"/\") ? basePath.slice(0, -1) : basePath;\n if (!trimmed.startsWith(\"/\")) {\n throw new Error(`basePath must start with \"/\": got ${basePath}`);\n }\n if (trimmed.includes(\"//\") || /[?#*]/.test(trimmed)) {\n throw new Error(`basePath must be a plain path: got ${basePath}`);\n }\n return trimmed;\n}\n\n/**\n * Pull the endpoint name out of a URL path, or null if it isn't ours.\n *\n * The full path must match `<basePath>/<endpoint>` exactly. This used to\n * compare only the *last* segment, which meant `/anything/at/all/claim`\n * dispatched to `claim` and {@link PROTOCOL_PREFIX} was decorative — it\n * appeared in a 404 message and was never matched against. For the handler\n * that serves claim, result and heartbeat, dispatching on a suffix is a\n * looser rule than anyone reading the constant would assume, and loose\n * matching in a security surface should at least be a decision.\n *\n * The cost is that the mount point is now something a deployment has to state\n * rather than something that works by accident. That is the intended trade:\n * a 404 at startup naming the mount point beats a handler answering on paths\n * nobody meant to expose.\n */\nexport function routeEndpoint(\n pathname: string,\n basePath: string = PROTOCOL_PREFIX,\n): Endpoint | null {\n const base = normalizeBasePath(basePath);\n const path = pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n if (!path.startsWith(`${base}/`)) return null;\n const rest = path.slice(base.length + 1);\n return (ENDPOINTS as readonly string[]).includes(rest)\n ? (rest as Endpoint)\n : null;\n}\n\n/**\n * Read the request signature from headers (byollm_009 §4.2).\n *\n * In headers rather than the body so the signature covers the body whole,\n * with no field to exclude from its own hash — a scheme that signs a body\n * minus one field has to agree, byte for byte, on how that field is removed.\n */\nexport function signatureFrom(headers: Headers): unknown {\n const runnerId = headers.get(\"x-byollm-runner\");\n const rawIssuedAt = headers.get(\"x-byollm-issued-at\");\n const signature = headers.get(\"x-byollm-signature\");\n if (runnerId === null || signature === null || rawIssuedAt === null) {\n return undefined;\n }\n // Checked against null *before* Number(), because `Number(null)` is 0 —\n // finite, plausible-looking, and wrong. A missing timestamp would have\n // become a timestamp of the epoch, which the freshness check would then\n // reject for the wrong reason.\n const issuedAt = Number(rawIssuedAt);\n if (!Number.isFinite(issuedAt)) return undefined;\n return { runnerId, issuedAt, signature };\n}\n\n/**\n * A `Request` → `Response` handler for the whole protocol.\n *\n * Web-standard types, so this works unchanged in Next.js route handlers, Hono,\n * Bun, Deno, Cloudflare Workers, and anything else that speaks fetch.\n */\nexport function createFetchHandler(\n config: HandlerConfig & {\n /**\n * Where these endpoints are mounted. Defaults to\n * {@link PROTOCOL_PREFIX}; set it when the app serves them elsewhere.\n */\n readonly basePath?: string;\n },\n): (request: Request) => Promise<Response> {\n const handlers = new ByollmHandlers(config);\n // Validate once, at construction: a bad mount point is a deployment bug and\n // should surface when the server starts, not as a silent 404 per request.\n const basePath = normalizeBasePath(config.basePath ?? PROTOCOL_PREFIX);\n\n return async function handle(request: Request): Promise<Response> {\n if (request.method !== \"POST\") {\n return json(405, {\n error: \"bad-request\",\n message: \"protocol endpoints accept POST only\",\n });\n }\n\n const endpoint = routeEndpoint(new URL(request.url).pathname, basePath);\n if (endpoint === null) {\n return json(404, {\n error: \"not-found\",\n message: `not a ${basePath} endpoint`,\n });\n }\n\n const declared = request.headers.get(\"content-length\");\n if (declared !== null && Number(declared) > MAX_BODY_BYTES) {\n return json(400, {\n error: \"bad-request\",\n message: \"request body too large\",\n });\n }\n\n let body: unknown;\n let rawBody: string;\n try {\n rawBody = await request.text();\n const text = rawBody;\n if (text.length > MAX_BODY_BYTES) {\n return json(400, {\n error: \"bad-request\",\n message: \"request body too large\",\n });\n }\n body = JSON.parse(text);\n } catch {\n // Deliberately not echoing the parse error: it would quote attacker\n // input back into a response an operator later reads in a terminal.\n return json(400, {\n error: \"bad-request\",\n message: \"request body is not valid JSON\",\n });\n }\n\n // byollm_009 §4: version before anything else. A mismatch must name the\n // disagreement and the fix, not surface as a generic bad-request from a\n // schema literal buried in an endpoint — which is what happened before,\n // and is why \"the connection is versionless\" was listed as a defect.\n const refusal = checkProtocolVersion(body);\n if (refusal) {\n return json(ERROR_STATUS[refusal.error], refusal);\n }\n\n const result = await handlers.handle(endpoint, body, {\n endpoint,\n // The bytes as received. Re-serialising the parsed object would verify\n // a signature over something the sender never sent.\n rawBody,\n signature: signatureFrom(request.headers),\n });\n\n const headers: Record<string, string> = {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n };\n if (result.retryAfterSeconds !== undefined) {\n headers[\"retry-after\"] = String(result.retryAfterSeconds);\n }\n return new Response(JSON.stringify(result.body), {\n status: result.status,\n headers,\n });\n };\n}\n\nfunction json(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n \"content-type\": \"application/json\",\n \"cache-control\": \"no-store\",\n },\n });\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUP,IAAM,qBAAqB;AAGpB,SAAS,qBAA6B;AAC3C,SAAO,YAAY,EAAE,EAAE,SAAS,WAAW;AAC7C;AAGO,SAAS,sBAA8B;AAC5C,SAAO,YAAY,EAAE,EAAE,SAAS,WAAW;AAC7C;AAGO,SAAS,mBAA2B;AACzC,SAAO,UAAU,WAAW,CAAC;AAC/B;AAGO,SAAS,gBAAwB;AAStC,SAAO,WAAW;AACpB;AAMO,SAAS,mBAA2B;AACzC,QAAM,QAAkB,CAAC;AACzB,SAAO,MAAM,SAAS,GAAG;AACvB,eAAW,QAAQ,YAAY,EAAE,GAAG;AAGlC,YAAM,QAAQ,MAAO,MAAM,mBAAmB;AAC9C,UAAI,QAAQ,MAAO;AACnB,YAAM,SAAS,mBAAmB,OAAO,mBAAmB,MAAM;AAClE,UAAI,WAAW,OAAW;AAC1B,YAAM,KAAK,MAAM;AACjB,UAAI,MAAM,WAAW,EAAG;AAAA,IAC1B;AAAA,EACF;AACA,SAAO,GAAG,MAAM,MAAM,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC,IAAI,MAAM,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;AACjE;AAGO,SAAS,WAAW,QAAwB;AACjD,SAAO,WAAW,QAAQ,EAAE,OAAO,QAAQ,MAAM,EAAE,OAAO,KAAK;AACjE;AAMO,SAAS,aAAa,MAAc,MAAuB;AAChE,MAAI,KAAK,WAAW,KAAK,OAAQ,QAAO;AACxC,SAAO,gBAAgB,OAAO,KAAK,MAAM,KAAK,GAAG,OAAO,KAAK,MAAM,KAAK,CAAC;AAC3E;AAUO,IAAM,kBAAkB,MAAc,WAAW;;;ACxFxD;AA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AM,SAAS,MAAM,SAAS,OAAO,UAAU,MAAM;AAAA,MACnD;AAAA;AAAA;AAAA,MAGA;AAAA,MACA,WAAW,cAAc,QAAQ,OAAO;AAAA,IAC1C,CAAC;AAED,UAAM,UAAkC;AAAA,MACtC,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,IACnB;AACA,QAAI,OAAO,sBAAsB,QAAW;AAC1C,cAAQ,aAAa,IAAI,OAAO,OAAO,iBAAiB;AAAA,IAC1D;AACA,WAAO,IAAI,SAAS,KAAK,UAAU,OAAO,IAAI,GAAG;AAAA,MAC/C,QAAQ,OAAO;AAAA,MACf;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAEA,SAAS,KAAK,QAAgB,MAAyB;AACrD,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACxC;AAAA,IACA,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,iBAAiB;AAAA,IACnB;AAAA,EACF,CAAC;AACH;","names":["keyId","open","publicIdentityOf","publicIdentityOf","response","open","keyId","ERROR_STATUS","ERROR_STATUS"]}
@@ -1,5 +1,5 @@
1
1
  import { StoredKeys, Endpoint } from '@byollm/protocol';
2
- import { B as ByollmStore } from './store-gFEEN1Dt.js';
2
+ import { B as ByollmStore } from './store-Cj5b6A9j.js';
3
3
 
4
4
  /** Everything a mount needs to serve the protocol. */
5
5
  /**
package/dist/index.d.ts CHANGED
@@ -1,10 +1,94 @@
1
- import { JobKind, StoredKeys, DeliveredResult, Endpoint, Capability } from '@byollm/protocol';
1
+ import { StoredKeys, JobKind, DeliveredResult, Endpoint, Capability } from '@byollm/protocol';
2
2
  import { P as PollingDeliveryDeps, R as ResultDelivery, W as WaitOptions } from './delivery-36nIe-b3.js';
3
3
  export { N as NoRunnerAvailableError, a as PollingDelivery, b as ResultTimeoutError } from './delivery-36nIe-b3.js';
4
- import { B as ByollmStore, E as EnqueueInput, J as JobRecord, R as RunnerRecord, S as StoredJobInput, C as ClaimArgs, a as RenewArgs, b as RenewResult, c as CompleteArgs, d as CompleteResult, e as ReleaseArgs, P as PairingRecord, A as ApproveArgs, T as TouchArgs } from './store-gFEEN1Dt.js';
5
- export { f as JobStore, g as RunnerStore } from './store-gFEEN1Dt.js';
6
- import { H as HandlerConfig } from './handlers-CF3yE-t2.js';
7
- export { B as ByollmHandlers, a as HandlerResult, S as SERVED_PROTOCOL_VERSION } from './handlers-CF3yE-t2.js';
4
+ import { B as ByollmStore, J as JobRecord, E as EnqueueInput, R as RunnerRecord, S as StoredJobInput, C as ClaimArgs, a as RenewArgs, b as RenewResult, A as AdoptArgs, c as CompleteArgs, d as CompleteResult, e as ReleaseArgs, P as PairingRecord, f as ApproveArgs, T as TouchArgs } from './store-Cj5b6A9j.js';
5
+ export { g as CompleteHolder, h as JobStore, i as RunnerStore } from './store-Cj5b6A9j.js';
6
+ import { H as HandlerConfig } from './handlers-DgW0QNTf.js';
7
+ export { B as ByollmHandlers, a as HandlerResult, S as SERVED_PROTOCOL_VERSION } from './handlers-DgW0QNTf.js';
8
+
9
+ /**
10
+ * The cloud lane — cloud_004 §9.4.
11
+ *
12
+ * `app.enqueue(...)` is identical in every lane; the lane picks the connection
13
+ * plane. In `direct` mode a daemon reaches the site's own handlers. In `cloud`
14
+ * mode it reaches a relay instead, and the site's side of that is this file.
15
+ *
16
+ * ## What actually changes, and what deliberately does not
17
+ *
18
+ * Enqueue does not change at all. The job is validated, sealed at rest to the
19
+ * site's own key and stored, exactly as before — jobs-at-rest encryption is a
20
+ * direct-mode property that the cloud lane inherits rather than replaces.
21
+ *
22
+ * What changes is *who asks for the payload and when*. On the direct plane the
23
+ * daemon asks, and the site answers synchronously because it is the upstream.
24
+ * Through a relay the site is not the upstream, so nobody asks: the site has to
25
+ * find out that a device claimed its job, and seal to that device. Hence a
26
+ * pump rather than a handler.
27
+ *
28
+ * ```
29
+ * enqueue ──stub──▶ relay (payload stays here, sealed at rest)
30
+ * │
31
+ * pump ◀──who claimed it, and what key?
32
+ * ──payload sealed to that device──▶
33
+ * pump ◀──sealed result── ──▶ store.complete → the app's delivery channel
34
+ * ```
35
+ *
36
+ * ## Why the site polls
37
+ *
38
+ * Everything in this product is outbound. A relay that called site webhooks
39
+ * would need every site publicly reachable, which is the connectivity problem
40
+ * the hub exists to remove — and a serverless site has nowhere to receive a
41
+ * webhook anyway. So the site polls, exactly as a daemon does.
42
+ */
43
+ interface CloudLaneOptions {
44
+ /** Where the relay lives, e.g. `https://relay.byollm.cloud`. */
45
+ readonly relayOrigin: string;
46
+ /** This site's id at the relay. */
47
+ readonly siteId: string;
48
+ /** Injectable fetch, for tests and for proxies. */
49
+ readonly fetch?: typeof fetch;
50
+ }
51
+ /** What one pump cycle did, for logging and for tests. */
52
+ interface PumpReport {
53
+ /** Jobs sealed to a claiming device this cycle. */
54
+ readonly sealed: string[];
55
+ /** Results opened, verified and written to the store. */
56
+ readonly completed: string[];
57
+ /**
58
+ * Jobs the relay offered that this site refused to seal for.
59
+ *
60
+ * Never silent: a site that cannot open its own at-rest envelope has a key
61
+ * problem, and a device waiting on a payload that will never come is
62
+ * exactly the case `awaiting-payload` exists to bound.
63
+ */
64
+ readonly refused: string[];
65
+ }
66
+ declare class CloudLane {
67
+ #private;
68
+ constructor(deps: {
69
+ options: CloudLaneOptions;
70
+ store: ByollmStore;
71
+ siteKeys: StoredKeys;
72
+ now: () => number;
73
+ });
74
+ /**
75
+ * Publish a job's stub for routing.
76
+ *
77
+ * The stub and nothing else — byollm_009 §6 makes that exhaustive by
78
+ * construction, so this cannot leak a payload even by mistake: there is no
79
+ * field on `JobStub` to put one in.
80
+ */
81
+ publish(record: JobRecord): Promise<void>;
82
+ /**
83
+ * One cycle: seal for anything claimed, collect anything finished.
84
+ *
85
+ * Idempotent and safe to call as often as you like. Exposed as a single
86
+ * cycle rather than hidden behind a timer so a caller decides its own
87
+ * cadence — a serverless site runs it on a cron, a long-lived one on an
88
+ * interval, and a test runs it exactly when it means to.
89
+ */
90
+ pump(): Promise<PumpReport>;
91
+ }
8
92
 
9
93
  /** Why a job cannot presently run. */
10
94
  type NoRunnerReason = "no-runner-paired" | "no-runner-online" | "no-matching-capability" | "audience-admits-nobody";
@@ -53,6 +137,15 @@ interface ByollmAppOptions {
53
137
  * holds plaintext (byollm_009 §10).
54
138
  */
55
139
  readonly siteKeys: StoredKeys;
140
+ /**
141
+ * Which connection plane this site uses — cloud_004 §9.4.
142
+ *
143
+ * Omitted means `direct`: a daemon reaches this site's own handlers, and
144
+ * everything works as it always has. Supplying a relay switches the plane
145
+ * and nothing else — `enqueue` is identical in every lane, which is the
146
+ * property that lets the same app move between them by config.
147
+ */
148
+ readonly lane?: CloudLaneOptions;
56
149
  }
57
150
  /**
58
151
  * An enqueued job, with the delivery channel attached.
@@ -80,6 +173,8 @@ interface JobHandle {
80
173
  */
81
174
  declare class ByollmApp {
82
175
  #private;
176
+ /** Present only in the cloud lane; the site's side of the relay. */
177
+ readonly cloud: CloudLane | undefined;
83
178
  constructor(options: ByollmAppOptions);
84
179
  /**
85
180
  * Enqueue a job.
@@ -264,6 +359,7 @@ declare class MemoryStore implements ByollmStore {
264
359
  get(jobId: string): Promise<JobRecord | null>;
265
360
  claim(args: ClaimArgs): Promise<JobRecord[]>;
266
361
  renewLeases(args: RenewArgs): Promise<RenewResult>;
362
+ adopt(args: AdoptArgs): Promise<JobRecord | null>;
267
363
  complete(args: CompleteArgs): Promise<CompleteResult>;
268
364
  subscribe(jobId: string, onChange: () => void): () => void;
269
365
  release(args: ReleaseArgs): Promise<string[]>;
@@ -288,4 +384,4 @@ declare class MemoryStore implements ByollmStore {
288
384
  /** The capability that would serve a kind, if any. */
289
385
  declare function capabilityFor(capabilities: readonly Capability[], kind: string): Capability | undefined;
290
386
 
291
- export { ApproveArgs, type AvailabilityQuery, ByollmApp, type ByollmAppOptions, ByollmStore, ClaimArgs, CompleteArgs, CompleteResult, EnqueueInput, HandlerConfig, type JobHandle, JobRecord, MemoryStore, type MemoryStoreOptions, type NoRunnerReason, PairingRecord, PollingDeliveryDeps, ReleaseArgs, RenewArgs, RenewResult, ResultDelivery, type RunnerAvailability, RunnerRecord, TouchArgs, WaitOptions, capabilityFor, createFetchHandler, formatSiteKeys, generateDeviceCode, generateJobId, generateRunnerId, generateRunnerToken, generateSiteKeys, generateUserCode, hashSecret, normalizeUserCode, routeEndpoint, secretsMatch, signatureFrom, siteKeysFromEnv };
387
+ export { AdoptArgs, ApproveArgs, type AvailabilityQuery, ByollmApp, type ByollmAppOptions, ByollmStore, ClaimArgs, CloudLane, type CloudLaneOptions, CompleteArgs, CompleteResult, EnqueueInput, HandlerConfig, type JobHandle, JobRecord, MemoryStore, type MemoryStoreOptions, type NoRunnerReason, PairingRecord, PollingDeliveryDeps, type PumpReport, ReleaseArgs, RenewArgs, RenewResult, ResultDelivery, type RunnerAvailability, RunnerRecord, TouchArgs, WaitOptions, capabilityFor, createFetchHandler, formatSiteKeys, generateDeviceCode, generateJobId, generateRunnerId, generateRunnerToken, generateSiteKeys, generateUserCode, hashSecret, normalizeUserCode, routeEndpoint, secretsMatch, signatureFrom, siteKeysFromEnv };