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

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.7`) — under active development. Don't use this yet.**
2
+ > **Alpha (`0.1.0-alpha.9`) — under active development. Don't use this yet.**
3
3
  >
4
4
  > Install it deliberately: `npm install @byollm/server@alpha`.
5
5
  >
package/dist/index.js CHANGED
@@ -39,7 +39,8 @@ import {
39
39
  keyId,
40
40
  open,
41
41
  publicIdentityOf,
42
- provenanceFor
42
+ provenanceFor,
43
+ signSiteRequest
43
44
  } from "@byollm/protocol";
44
45
  var CloudLane = class {
45
46
  #options;
@@ -75,7 +76,7 @@ var CloudLane = class {
75
76
  // is worth carrying — never longer than the work could possibly matter.
76
77
  deadlineAt: record.deadlineAt ?? record.createdAt + ENVELOPE_TTL_FALLBACK
77
78
  };
78
- await this.#post("/relay/site/enqueue", {
79
+ await this.#post("enqueue", {
79
80
  siteId: this.#options.siteId,
80
81
  stub
81
82
  });
@@ -92,7 +93,7 @@ var CloudLane = class {
92
93
  const sealed = [];
93
94
  const refused = [];
94
95
  const completed = [];
95
- const pending = await this.#get("/relay/site/pending");
96
+ const pending = await this.#get("pending");
96
97
  for (const claim of pending.jobs) {
97
98
  const record = await this.#store.get(claim.jobId);
98
99
  if (!record) continue;
@@ -115,14 +116,14 @@ var CloudLane = class {
115
116
  expiresAt: claim.awaitingUntil,
116
117
  now: this.#now()
117
118
  });
118
- await this.#post("/relay/site/payload", {
119
+ await this.#post("payload", {
119
120
  siteId: this.#options.siteId,
120
121
  jobId: claim.jobId,
121
122
  envelope: resealed.envelope
122
123
  });
123
124
  sealed.push(claim.jobId);
124
125
  }
125
- const finished = await this.#get("/relay/site/results");
126
+ const finished = await this.#get("results");
126
127
  for (const done of finished.jobs) {
127
128
  const record = await this.#store.get(done.jobId);
128
129
  if (!record || record.state === "ok" || record.state === "error") {
@@ -185,17 +186,48 @@ var CloudLane = class {
185
186
  if (outcome.data.outcome !== done.disposition) return null;
186
187
  return outcome.data;
187
188
  }
188
- async #post(path, body) {
189
- const response = await this.#fetch(`${this.#options.relayOrigin}${path}`, {
190
- method: "POST",
191
- headers: { "content-type": "application/json" },
192
- body: JSON.stringify(body)
189
+ /**
190
+ * Sign a site-plane call with this site's identity key.
191
+ *
192
+ * The same scheme the daemon uses against an upstream, because the site is
193
+ * in the same position: an outbound caller whose key the relay already holds
194
+ * for other reasons. Nothing else authenticates this plane — a relay that
195
+ * took the `siteId` in a body at face value would let anyone enqueue work in
196
+ * a site's name and read who claimed it.
197
+ */
198
+ #headers(endpoint, rawBody) {
199
+ const signature = signSiteRequest(this.#siteKeys, {
200
+ endpoint,
201
+ siteId: this.#options.siteId,
202
+ issuedAt: this.#now(),
203
+ body: rawBody
193
204
  });
205
+ return {
206
+ "x-byollm-site": this.#options.siteId,
207
+ "x-byollm-issued-at": String(signature.issuedAt),
208
+ "x-byollm-signature": signature.signature
209
+ };
210
+ }
211
+ async #post(endpoint, body) {
212
+ const rawBody = JSON.stringify(body);
213
+ const response = await this.#fetch(
214
+ `${this.#options.relayOrigin}/relay/site/${endpoint}`,
215
+ {
216
+ method: "POST",
217
+ headers: {
218
+ "content-type": "application/json",
219
+ ...this.#headers(endpoint, rawBody)
220
+ },
221
+ body: rawBody
222
+ }
223
+ );
194
224
  return response.json();
195
225
  }
196
- async #get(path) {
197
- const url = `${this.#options.relayOrigin}${path}?siteId=${encodeURIComponent(this.#options.siteId)}`;
198
- const response = await this.#fetch(url);
226
+ async #get(endpoint) {
227
+ const url = `${this.#options.relayOrigin}/relay/site/${endpoint}?siteId=${encodeURIComponent(this.#options.siteId)}`;
228
+ const response = await this.#fetch(url, {
229
+ headers: this.#headers(endpoint, "")
230
+ });
199
231
  return response.json();
200
232
  }
201
233
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/app.ts","../src/cloud.ts","../src/keys.ts","../src/memory.ts"],"sourcesContent":["import {\n ENVELOPE_MAX_AGE_MS,\n KindedPayload,\n keyId,\n payloadTextLength,\n publicIdentityOf,\n seal,\n sizeClassOf,\n type StoredKeys,\n backendDescriptor,\n matchAudience,\n type DeliveredResult,\n type JobKind,\n} from \"@byollm/protocol\";\nimport {\n PollingDelivery,\n type PollingDeliveryDeps,\n type ResultDelivery,\n type WaitOptions,\n} from \"./delivery.js\";\nimport {\n generateJobId,\n generateRunnerId,\n generateRunnerToken,\n hashSecret,\n} from \"./ids.js\";\nimport { CloudLane, type CloudLaneOptions } from \"./cloud.js\";\nimport type { EnqueueInput, JobRecord, RunnerRecord } from \"./records.js\";\nimport type { ByollmStore } from \"./store.js\";\n\n/**\n * How long since a runner's last heartbeat before it stops counting as live.\n * Three heartbeats of slack at the daemon's ~10s cadence.\n */\nconst DEFAULT_LIVENESS_MS = 35_000;\n\n/** Why a job cannot presently run. */\nexport type NoRunnerReason =\n | \"no-runner-paired\"\n | \"no-runner-online\"\n | \"no-matching-capability\"\n | \"audience-admits-nobody\";\n\n/**\n * The no-runner signal (byollm_001 Rev 1 §D).\n *\n * `available: false` means an app should fall back — hosted model, \"start\n * your runner\" prompt — rather than awaiting something that will never\n * resolve. A job still blocked on dependencies is **not** unavailable; it is\n * waiting, and saying otherwise would make every multi-job flow look broken\n * ({@link MUSTS.NO_RUNNER_SIGNAL}).\n */\nexport interface RunnerAvailability {\n readonly available: boolean;\n readonly reason?: NoRunnerReason;\n /** Live runners that could take work of this shape. */\n readonly candidates: number;\n}\n\nexport interface AvailabilityQuery {\n readonly kind: JobKind;\n readonly owner: string;\n readonly audience?: \"self\" | \"named\" | \"public\";\n readonly audienceAllow?: readonly string[];\n}\n\nexport interface ByollmAppOptions {\n readonly store: ByollmStore;\n /** Injectable clock. */\n readonly now?: () => number;\n /** Liveness window for the no-runner signal. */\n readonly livenessMs?: number;\n /**\n * How the app learns a job finished. Defaults to polling the store, which\n * is correct everywhere; the Supabase adapter substitutes Realtime.\n */\n readonly delivery?: (deps: PollingDeliveryDeps) => ResultDelivery;\n /**\n * How long a sustained no-runner signal must persist before `result()`\n * gives up. Longer tolerates a daemon restarting; shorter fails faster.\n */\n readonly noRunnerGraceMs?: number;\n /**\n * This site's keypairs — the same ones the handlers use.\n *\n * The app needs them because it is the *endpoint*: it seals work on the way\n * in and opens results on the way out. Nothing between those two points\n * holds plaintext (byollm_009 §10).\n */\n readonly siteKeys: StoredKeys;\n /**\n * Which connection plane this site uses — cloud_004 §9.4.\n *\n * Omitted means `direct`: a daemon reaches this site's own handlers, and\n * everything works as it always has. Supplying a relay switches the plane\n * and nothing else — `enqueue` is identical in every lane, which is the\n * property that lets the same app move between them by config.\n */\n readonly lane?: CloudLaneOptions;\n}\n\n/**\n * An enqueued job, with the delivery channel attached.\n *\n * `result()` is sugar over the channel — with a timeout and a\n * `noRunnerAvailable` path — never a bare promise that can hang forever\n * (byollm_003 Rev 1).\n */\nexport interface JobHandle {\n readonly id: string;\n /** The job as stored at enqueue time. */\n readonly record: JobRecord;\n /** Wait for a terminal outcome. */\n result(options?: WaitOptions): Promise<DeliveredResult>;\n /** Ask the runner to stop. */\n cancel(): Promise<void>;\n}\n\n/**\n * The app-facing half of `@byollm/server`.\n *\n * The daemon talks to {@link ByollmHandlers}; the app talks to this. Keeping\n * them separate is what makes \"one door per state write\" hold — an app\n * enqueues and cancels through these methods and never writes job rows by\n * hand.\n */\nexport class ByollmApp {\n readonly #store: ByollmStore;\n readonly #siteKeys: StoredKeys;\n readonly #now: () => number;\n readonly #livenessMs: number;\n readonly #delivery: ResultDelivery;\n /** Present only in the cloud lane; the site's side of the relay. */\n readonly cloud: CloudLane | undefined;\n\n constructor(options: ByollmAppOptions) {\n this.#store = options.store;\n this.#siteKeys = options.siteKeys;\n this.#now = options.now ?? Date.now;\n this.#livenessMs = options.livenessMs ?? DEFAULT_LIVENESS_MS;\n this.cloud =\n options.lane === undefined\n ? undefined\n : new CloudLane({\n options: options.lane,\n store: options.store,\n siteKeys: options.siteKeys,\n now: this.#now,\n });\n\n const deps: PollingDeliveryDeps = {\n ...(options.noRunnerGraceMs === undefined\n ? {}\n : { graceMs: options.noRunnerGraceMs }),\n read: (jobId) => this.result(jobId),\n availability: async (jobId) => {\n const job = await this.#store.get(jobId);\n if (!job)\n return { available: false, reason: \"unknown-job\", blocked: false };\n // A job waiting on a dependency is waiting, not unavailable.\n if (job.claimableAt === null) {\n return { available: true, blocked: true };\n }\n const availability = await this.runnerAvailability({\n kind: job.kind,\n owner: job.owner,\n audience: job.audience,\n ...(job.audienceAllow === undefined\n ? {}\n : { audienceAllow: job.audienceAllow }),\n });\n return {\n available: availability.available,\n ...(availability.reason === undefined\n ? {}\n : { reason: availability.reason }),\n blocked: false,\n };\n },\n };\n this.#delivery = options.delivery?.(deps) ?? new PollingDelivery(deps);\n }\n\n /**\n * Enqueue a job.\n *\n * `audience` defaults to `self` — the safe direction. Widening it means the\n * result comes back marked untrusted (see {@link ByollmApp.result}), and\n * the app is obliged to disclose that to whoever reads it.\n */\n async enqueue(input: EnqueueInput): Promise<JobHandle> {\n // Validate the payload against its kind before anything stores it.\n //\n // The schemas are `.strict()`, so this drops a payload carrying fields\n // the kind does not define — `command`, `argv`, `model`, `baseUrl`. Types\n // do not survive a JSON boundary, and an app assembling a payload from\n // user input is the ordinary case, so \"the caller is typed\" is not a\n // check ({@link MUSTS.KIND_NO_CODE}, {@link MUSTS.NO_PAYLOAD_ROUTING}).\n //\n // Refusing here rather than relying on the daemon is deliberate. The\n // daemon does re-validate and would reject this — but it parses a whole\n // claim response at once, so one malformed job would fail the batch it\n // arrived in and stall unrelated work. Rejecting at enqueue puts the\n // error where the app can act on it.\n const parsed = KindedPayload.safeParse({\n kind: input.kind,\n payload: input.payload,\n });\n if (!parsed.success) {\n const detail = parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n .join(\"; \");\n throw new Error(`invalid ${input.kind} payload — ${detail}`);\n }\n\n // Sealed before it is stored, to this site's own key. The app is the\n // endpoint, so it can open its own work later; the store, its backups and\n // anything reading them cannot.\n // Two different deadlines, deliberately not conflated:\n //\n // - the *job's* deadline is the app's business, may be absent, and for a\n // dependent job its TTL clock does not even start until the job becomes\n // claimable (`TTL_EXPIRY`). Setting one here broke exactly that.\n // - the *envelope's* deadline bounds how long a captured ciphertext is\n // worth keeping. It is bound into the signature, so it has to be\n // recomputable at open time from what the record stores — hence\n // creation plus TTL, which never moves.\n // Resolved *here*, once, and passed to the store — because the envelope\n // binds it. Letting the app default one value and the store default\n // another produced a job whose seal and record disagreed, and therefore\n // work nobody could open.\n // One reading of the clock, used for both the seal and the record.\n //\n // Two readings passed every fake-clock test and failed against a real\n // one: the envelope bound `createdAt + ttlMs` from the first call and the\n // record stored `createdAt` from the second, a millisecond later, so\n // nothing could be opened. A fixed clock returns the same number twice\n // and hides it completely.\n const createdAt = this.#now();\n // Independent of the job's TTL, deliberately. Binding the envelope to\n // `createdAt + ttl` meant the app had to decide a TTL in order to seal —\n // which overrode the store's own default and broke every expiry test.\n // The two answer different questions: how long the work is worth doing,\n // and how long the ciphertext is worth keeping.\n const envelopeDeadlineAt = createdAt + ENVELOPE_MAX_AGE_MS;\n const jobId = input.id ?? generateJobId();\n const senderKeyId = keyId(publicIdentityOf(this.#siteKeys).identity);\n const envelope = await seal({\n plaintext: JSON.stringify(parsed.data.payload),\n senderKeys: this.#siteKeys,\n recipientEncryptionPublic: this.#siteKeys.encryptionPublic,\n context: {\n jobId,\n senderKeyId,\n recipientKeyId: senderKeyId,\n deadlineAt: envelopeDeadlineAt,\n direction: \"payload\",\n },\n });\n\n const record = await this.#store.create(\n {\n ...input,\n id: jobId,\n envelope,\n sizeClass: sizeClassOf(\n payloadTextLength({\n kind: input.kind,\n payload: parsed.data.payload,\n } as Parameters<typeof payloadTextLength>[0]),\n ),\n },\n createdAt,\n );\n // The lane's only intrusion into enqueue, and it is additive: the record\n // is already stored and sealed at rest before anything is published, so a\n // relay that is down costs a routing delay rather than a lost job.\n await this.cloud?.publish(record);\n\n return {\n id: record.id,\n record,\n result: (options?: WaitOptions) =>\n this.#delivery.waitFor(record.id, options),\n cancel: async () => {\n await this.cancel(record.id);\n },\n };\n }\n\n /** Read a job's current state. */\n async job(jobId: string): Promise<JobRecord | null> {\n await this.#store.expireDue(this.#now());\n return this.#store.get(jobId);\n }\n\n /**\n * A job's result with its provenance attached.\n *\n * Check `provenance.untrusted` before rendering. It is true for every\n * `named`/`public` job, because that text came from someone else's machine\n * and the app must not present it as its own AI's answer\n * ({@link MUSTS.RESULT_PROVENANCE}).\n */\n async result(jobId: string): Promise<DeliveredResult | null> {\n const job = await this.job(jobId);\n if (!job) return null;\n return {\n jobId: job.id,\n state: job.state,\n ...(job.outcome === null ? {} : { outcome: job.outcome }),\n ...(job.provenance === null ? {} : { provenance: job.provenance }),\n };\n }\n\n /** Ask a runner to stop. Queued jobs cancel at once; held jobs at the next heartbeat. */\n async cancel(jobId: string): Promise<JobRecord | null> {\n return this.#store.cancel(jobId, this.#now());\n }\n\n /**\n * Is there a live runner that could take a job of this shape?\n *\n * Runs the identical {@link matchAudience} rule the claim path uses, so the\n * signal cannot promise a runner the claim would then refuse.\n */\n async runnerAvailability(\n query: AvailabilityQuery,\n ): Promise<RunnerAvailability> {\n const now = this.#now();\n const all = await this.#store.listRunners();\n const live = all.filter(\n (runner) =>\n runner.revokedAt === null &&\n !runner.paused &&\n now - runner.lastHeartbeatAt <= this.#livenessMs,\n );\n\n if (all.length === 0) {\n return { available: false, reason: \"no-runner-paired\", candidates: 0 };\n }\n if (live.length === 0) {\n return { available: false, reason: \"no-runner-online\", candidates: 0 };\n }\n\n let capable = 0;\n let admitted = 0;\n for (const runner of live) {\n const capability = runner.capabilities.find((c) => c.kind === query.kind);\n if (!capability) continue;\n capable += 1;\n\n const match = matchAudience(\n {\n owner: query.owner,\n audience: query.audience ?? \"self\",\n audienceAllow: query.audienceAllow,\n },\n {\n owner: runner.owner,\n offerScope: capability.offerScope,\n // A generic backend's cost depends on its base URL, which the\n // server never sees; assume the expensive reading (byollm_007 §4).\n cost: backendDescriptor(capability.backendId).cost ?? \"metered\",\n // Consent is the daemon's to hold, and it has already applied it:\n // the offer scope arriving here is the *effective* one, so a\n // metered backend nobody agreed to share advertises `self` and is\n // refused by the scope rule above. Re-deriving consent from\n // `false` here would instead refuse every backend an owner\n // deliberately shared, because the server has no way to learn they\n // did — the signal would be wrong in the direction that breaks\n // working setups.\n spend: { acknowledged: true },\n // Same conservative assumption the claim path makes: the server\n // cannot see a remote daemon's local allowlist (protocol §4.2).\n locallyAllows: () => true,\n },\n );\n if (match.ok) admitted += 1;\n }\n\n if (capable === 0) {\n return {\n available: false,\n reason: \"no-matching-capability\",\n candidates: 0,\n };\n }\n if (admitted === 0) {\n return {\n available: false,\n reason: \"audience-admits-nobody\",\n candidates: 0,\n };\n }\n return { available: true, candidates: admitted };\n }\n\n /**\n * Approve a pairing on behalf of an authenticated user.\n *\n * `owner` MUST come from the approving user's own session. A daemon can\n * never assert who it is — that is the whole reason pairing is interactive\n * ({@link MUSTS.PAIR_ONE_USER}, {@link MUSTS.PAIR_INTERACTIVE}).\n */\n async approvePairing(args: {\n userCode: string;\n owner: string;\n }): Promise<RunnerRecord> {\n const token = generateRunnerToken();\n return this.#store.approvePairing({\n userCode: normalizeUserCode(args.userCode),\n owner: args.owner,\n runnerId: generateRunnerId(),\n runnerToken: token,\n tokenHash: hashSecret(token),\n now: this.#now(),\n });\n }\n\n /** Deny a pairing the user did not initiate. */\n async denyPairing(userCode: string): Promise<void> {\n return this.#store.denyPairing(normalizeUserCode(userCode), this.#now());\n }\n\n /** What a pairing code refers to, for the approval page to show. */\n async pendingPairing(userCode: string): Promise<{\n label: string;\n platform: string;\n daemonVersion: string;\n capabilities: readonly { kind: string; model: string }[];\n expiresAt: number;\n } | null> {\n const pairing = await this.#store.getPairingByUserCode(\n normalizeUserCode(userCode),\n );\n if (pairing?.state !== \"pending\") return null;\n if (pairing.expiresAt <= this.#now()) return null;\n return {\n label: pairing.label,\n platform: pairing.platform,\n daemonVersion: pairing.daemonVersion,\n capabilities: pairing.capabilities.map((c) => ({\n kind: c.kind,\n model: c.model,\n })),\n expiresAt: pairing.expiresAt,\n };\n }\n\n /** The user's paired runners, for a settings page. */\n async runners(owner: string): Promise<RunnerRecord[]> {\n return this.#store.listRunners(owner);\n }\n\n /** Revoke a runner. It stops at its next heartbeat, mid-queue. */\n async revokeRunner(runnerId: string): Promise<void> {\n return this.#store.revokeRunner(runnerId, this.#now());\n }\n\n /** Run the expiry sweep. Idempotent; safe to call on a timer or a request. */\n async sweep(): Promise<JobRecord[]> {\n return this.#store.expireDue(this.#now());\n }\n}\n\n/**\n * Accept a pairing code however the user typed it — lowercase, spaces, no\n * dash. The code is displayed as `XXXX-XXXX`; refusing `xxxxxxxx` would fail\n * a user for a formatting detail they were never told mattered.\n */\nexport function normalizeUserCode(input: string): string {\n const bare = input.toUpperCase().replace(/[^A-Z0-9]/g, \"\");\n return bare.length === 8 ? `${bare.slice(0, 4)}-${bare.slice(4)}` : bare;\n}\n","import {\n JobOutcome,\n type SealedEnvelope,\n keyId,\n open,\n publicIdentityOf,\n provenanceFor,\n type JobStub,\n type PublicIdentity,\n type StoredKeys,\n} from \"@byollm/protocol\";\nimport type { JobRecord } from \"./records.js\";\nimport { resealForDevice } from \"./reseal.js\";\nimport type { ByollmStore } from \"./store.js\";\n\n/**\n * The cloud lane — cloud_004 §9.4.\n *\n * `app.enqueue(...)` is identical in every lane; the lane picks the connection\n * plane. In `direct` mode a daemon reaches the site's own handlers. In `cloud`\n * mode it reaches a relay instead, and the site's side of that is this file.\n *\n * ## What actually changes, and what deliberately does not\n *\n * Enqueue does not change at all. The job is validated, sealed at rest to the\n * site's own key and stored, exactly as before — jobs-at-rest encryption is a\n * direct-mode property that the cloud lane inherits rather than replaces.\n *\n * What changes is *who asks for the payload and when*. On the direct plane the\n * daemon asks, and the site answers synchronously because it is the upstream.\n * Through a relay the site is not the upstream, so nobody asks: the site has to\n * find out that a device claimed its job, and seal to that device. Hence a\n * pump rather than a handler.\n *\n * ```\n * enqueue ──stub──▶ relay (payload stays here, sealed at rest)\n * │\n * pump ◀──who claimed it, and what key?\n * ──payload sealed to that device──▶\n * pump ◀──sealed result── ──▶ store.complete → the app's delivery channel\n * ```\n *\n * ## Why the site polls\n *\n * Everything in this product is outbound. A relay that called site webhooks\n * would need every site publicly reachable, which is the connectivity problem\n * the hub exists to remove — and a serverless site has nowhere to receive a\n * webhook anyway. So the site polls, exactly as a daemon does.\n */\n\nexport interface CloudLaneOptions {\n /** Where the relay lives, e.g. `https://relay.byollm.cloud`. */\n readonly relayOrigin: string;\n /** This site's id at the relay. */\n readonly siteId: string;\n /** Injectable fetch, for tests and for proxies. */\n readonly fetch?: typeof fetch;\n}\n\n/** What one pump cycle did, for logging and for tests. */\nexport interface PumpReport {\n /** Jobs sealed to a claiming device this cycle. */\n readonly sealed: string[];\n /** Results opened, verified and written to the store. */\n readonly completed: string[];\n /**\n * Jobs the relay offered that this site refused to seal for.\n *\n * Never silent: a site that cannot open its own at-rest envelope has a key\n * problem, and a device waiting on a payload that will never come is\n * exactly the case `awaiting-payload` exists to bound.\n */\n readonly refused: string[];\n}\n\nexport class CloudLane {\n readonly #options: CloudLaneOptions;\n readonly #store: ByollmStore;\n readonly #siteKeys: StoredKeys;\n readonly #now: () => number;\n readonly #fetch: typeof fetch;\n\n constructor(deps: {\n options: CloudLaneOptions;\n store: ByollmStore;\n siteKeys: StoredKeys;\n now: () => number;\n }) {\n this.#options = deps.options;\n this.#store = deps.store;\n this.#siteKeys = deps.siteKeys;\n this.#now = deps.now;\n this.#fetch = deps.options.fetch ?? globalThis.fetch;\n }\n\n /**\n * Publish a job's stub for routing.\n *\n * The stub and nothing else — byollm_009 §6 makes that exhaustive by\n * construction, so this cannot leak a payload even by mistake: there is no\n * field on `JobStub` to put one in.\n */\n async publish(record: JobRecord): Promise<void> {\n const stub: JobStub = {\n id: record.id,\n kind: record.kind,\n owner: record.owner,\n audience: record.audience,\n ...(record.audienceAllow === undefined\n ? {}\n : { audienceAllow: [...record.audienceAllow] }),\n sizeClass: record.sizeClass,\n streaming: false,\n // The relay needs *a* deadline to bound routing. A job without one gets\n // the envelope's, which is the outer bound on how long the ciphertext\n // is worth carrying — never longer than the work could possibly matter.\n deadlineAt: record.deadlineAt ?? record.createdAt + ENVELOPE_TTL_FALLBACK,\n };\n await this.#post(\"/relay/site/enqueue\", {\n siteId: this.#options.siteId,\n stub,\n });\n }\n\n /**\n * One cycle: seal for anything claimed, collect anything finished.\n *\n * Idempotent and safe to call as often as you like. Exposed as a single\n * cycle rather than hidden behind a timer so a caller decides its own\n * cadence — a serverless site runs it on a cron, a long-lived one on an\n * interval, and a test runs it exactly when it means to.\n */\n async pump(): Promise<PumpReport> {\n const sealed: string[] = [];\n const refused: string[] = [];\n const completed: string[] = [];\n\n const pending = (await this.#get(\"/relay/site/pending\")) as {\n jobs: {\n jobId: string;\n device: PublicIdentity;\n runnerId: string;\n leaseId: string;\n awaitingUntil: number;\n }[];\n };\n for (const claim of pending.jobs) {\n const record = await this.#store.get(claim.jobId);\n if (!record) continue;\n const resealed = await resealForDevice({\n siteKeys: this.#siteKeys,\n job: {\n id: record.id,\n envelope: record.envelope,\n createdAt: record.createdAt,\n },\n device: claim.device,\n });\n if (!resealed.ok) {\n refused.push(claim.jobId);\n continue;\n }\n // Record the lease the relay granted, before handing over the work.\n //\n // The site is not the upstream here and does not decide who holds what\n // — but its own row has to know, or two things break that are not\n // cosmetic: `complete` refuses the result for want of a matching lease,\n // and the expiry sweep expires a job a device is in the middle of.\n // Adopting first means the worst case is a lease recorded for work that\n // never gets sealed, which the relay's own timeout already resolves.\n await this.#store.adopt({\n jobId: claim.jobId,\n leaseId: claim.leaseId,\n expiresAt: claim.awaitingUntil,\n now: this.#now(),\n });\n await this.#post(\"/relay/site/payload\", {\n siteId: this.#options.siteId,\n jobId: claim.jobId,\n envelope: resealed.envelope,\n });\n sealed.push(claim.jobId);\n }\n\n const finished = (await this.#get(\"/relay/site/results\")) as {\n jobs: {\n jobId: string;\n envelope: SealedEnvelope;\n disposition: string;\n runnerId: string;\n leaseId: string;\n device: PublicIdentity;\n }[];\n };\n for (const done of finished.jobs) {\n const record = await this.#store.get(done.jobId);\n if (!record || record.state === \"ok\" || record.state === \"error\") {\n continue;\n }\n const outcome = await this.#openResult(done);\n if (!outcome) {\n refused.push(done.jobId);\n continue;\n }\n // Provenance is built here, from the job's audience and the device the\n // relay named — never from anything the daemon asserted. Identical to\n // the direct plane's rule, and it has to be: a result arriving via a\n // relay is not more trustworthy for having travelled further.\n await this.#store.complete({\n jobId: done.jobId,\n // The grant, not the machine: this site never paired with the device\n // that ran it, and the signature it verified above is the stronger\n // claim about who did.\n holder: { by: \"lease\", leaseId: done.leaseId },\n outcome,\n provenance: provenanceFor({\n audience: record.audience,\n runnerId: done.runnerId,\n runnerOwner: keyId(done.device.identity),\n backendClass: \"http\",\n model: \"unknown\",\n }),\n now: this.#now(),\n });\n completed.push(done.jobId);\n }\n\n return { sealed, completed, refused };\n }\n\n /**\n * Open a sealed result and verify it came from the device that claimed it.\n *\n * The relay says which device ran the job; this checks that claim against a\n * signature the relay cannot produce. A relay that named the wrong device\n * gets a refusal, not a stored result — which is what keeps `RELAY_BLIND`\n * from quietly becoming `RELAY_TRUSTED`.\n */\n async #openResult(done: {\n jobId: string;\n envelope: SealedEnvelope;\n disposition: string;\n device: PublicIdentity;\n }): Promise<JobOutcome | null> {\n const opened = await open({\n envelope: done.envelope,\n recipientKeys: this.#siteKeys,\n senderIdentityPublic: done.device.identity,\n expected: {\n jobId: done.jobId,\n senderKeyId: keyId(done.device.identity),\n recipientKeyId: keyId(publicIdentityOf(this.#siteKeys).identity),\n direction: \"result\",\n },\n });\n if (!opened.ok) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(opened.plaintext);\n } catch {\n return null;\n }\n const outcome = JobOutcome.safeParse(parsed);\n if (!outcome.success) return null;\n // The clear-text disposition is a routing hint the relay acted on. This\n // is the only place it can be checked, because this is the only party\n // that can open the envelope (byollm_009 §6.1).\n if (outcome.data.outcome !== done.disposition) return null;\n return outcome.data;\n }\n\n async #post(path: string, body: unknown): Promise<unknown> {\n const response = await this.#fetch(`${this.#options.relayOrigin}${path}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n return response.json();\n }\n\n async #get(path: string): Promise<unknown> {\n const url = `${this.#options.relayOrigin}${path}?siteId=${encodeURIComponent(this.#options.siteId)}`;\n const response = await this.#fetch(url);\n return response.json();\n }\n}\n\n/** Only used when a job carries no deadline of its own. */\nconst ENVELOPE_TTL_FALLBACK = 24 * 60 * 60_000;\n","import { StoredKeys, generateKeys, publicIdentityOf } from \"@byollm/protocol\";\nimport { fingerprint } from \"@byollm/protocol\";\n\n/**\n * A site's keypairs — byollm_009 §5.\n *\n * **Generate once, store, supply.** Not at startup, and not per process.\n *\n * A site is usually more than one process: several instances behind a load\n * balancer, or a serverless function whose module is evaluated per cold\n * start. Keys generated at startup would give each of those a different\n * identity. A daemon pins whichever one approved its pairing, and then every\n * request routed to a different instance fails a signature check with nothing\n * in the error explaining why — a failure that appears only under\n * horizontal scale, which is to say only in production.\n *\n * So the library takes keys as an input and never invents them. That is the\n * whole reason this module is three functions rather than a lazy singleton.\n */\n\n/** Make a fresh site identity. Call this once, ever, and keep the result. */\nexport const generateSiteKeys = (now: number = Date.now()): StoredKeys =>\n generateKeys(now);\n\n/**\n * Read site keys from an environment variable holding base64 JSON.\n *\n * The shape a deployment actually wants: one opaque secret, set the way every\n * other secret is set, with no file to mount and no key material in the\n * repository.\n *\n * @throws with a message naming the variable and the fix, because this fails\n * at boot and the person reading the log is the person who can fix it.\n */\nexport function siteKeysFromEnv(\n variable = \"BYOLLM_SITE_KEYS\",\n env: NodeJS.ProcessEnv = process.env,\n): StoredKeys {\n const raw = env[variable];\n if (raw === undefined || raw === \"\") {\n throw new Error(\n `${variable} is not set. Generate a site identity once with ` +\n `\\`npx @byollm/server keygen\\` and set it as ${variable}. ` +\n `Do not generate keys at startup: every instance would get a ` +\n `different identity and daemons would pin one and be refused by ` +\n `another.`,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(raw, \"base64\").toString(\"utf8\"));\n } catch {\n throw new Error(\n `${variable} is not base64-encoded JSON. It should be exactly what ` +\n `\\`npx @byollm/server keygen\\` printed.`,\n );\n }\n\n const result = StoredKeys.safeParse(parsed);\n if (!result.success) {\n throw new Error(\n `${variable} does not contain a valid site identity. Regenerate it ` +\n `with \\`npx @byollm/server keygen\\` — and if this site has already ` +\n `paired daemons, they will need to pair again.`,\n );\n }\n return result.data;\n}\n\n/** What to print from `keygen`: the secret to store, and how to check it. */\nexport function formatSiteKeys(keys: StoredKeys): string {\n const encoded = Buffer.from(JSON.stringify(keys)).toString(\"base64\");\n return (\n `# Set this as BYOLLM_SITE_KEYS. It is a secret: it is this site's\\n` +\n `# identity, and anything holding it can be this site.\\n` +\n `BYOLLM_SITE_KEYS=${encoded}\\n` +\n `\\n` +\n `# Fingerprint (not secret — show it to users so they can check what\\n` +\n `# their daemon pinned):\\n` +\n `# ${fingerprint(publicIdentityOf(keys).identity)}\\n`\n );\n}\n","import {\n backendDescriptor,\n matchAudience,\n type Capability,\n} from \"@byollm/protocol\";\nimport { generateLeaseId } from \"./ids.js\";\nimport type {\n StoredJobInput,\n JobRecord,\n PairingRecord,\n RunnerRecord,\n} from \"./records.js\";\nimport type {\n ApproveArgs,\n ByollmStore,\n ClaimArgs,\n AdoptArgs,\n CompleteArgs,\n CompleteResult,\n ReleaseArgs,\n RenewArgs,\n RenewResult,\n TouchArgs,\n} from \"./store.js\";\n\n/** Tunables an embedder may want to override in tests. */\nexport interface MemoryStoreOptions {\n /** Default TTL for a job once claimable. */\n readonly defaultTtlMs?: number;\n}\n\nconst DEFAULT_TTL_MS = 15 * 60_000;\n\n/**\n * The reference store: everything in one process, no persistence.\n *\n * This is not a toy — it is the implementation the conformance kit certifies\n * first, so its semantics *are* the specification's semantics for anything\n * the prose leaves implicit. A SQL adapter is correct when the same kit\n * passes against it.\n *\n * Concurrency: JavaScript's single-threaded turn is the atomicity primitive.\n * `claim` performs its read-decide-write with no `await` inside the critical\n * section, which is what makes {@link MUSTS.CLAIM_ATOMIC} hold here. A SQL\n * adapter gets the same property from `FOR UPDATE SKIP LOCKED`.\n */\nexport class MemoryStore implements ByollmStore {\n readonly #jobs = new Map<string, JobRecord>();\n readonly #runners = new Map<string, RunnerRecord>();\n readonly #pairings = new Map<string, PairingRecord>();\n /** Job ids the app has asked to cancel, not yet acknowledged by a runner. */\n readonly #cancelRequests = new Set<string>();\n readonly #defaultTtlMs: number;\n\n constructor(options: MemoryStoreOptions = {}) {\n this.#defaultTtlMs = options.defaultTtlMs ?? DEFAULT_TTL_MS;\n }\n\n // -- jobs ---------------------------------------------------------------\n\n create(input: StoredJobInput, now: number): Promise<JobRecord> {\n // Required now: the app mints the id before sealing, because the\n // envelope binds it.\n const id = input.id;\n const existing = this.#jobs.get(id);\n // Idempotent by caller-supplied id: re-enqueueing the same id is a no-op,\n // so an app's retry cannot duplicate work (the house \"one door\" rule).\n if (existing) return Promise.resolve(existing);\n\n const dependsOn = [...(input.dependsOn ?? [])];\n const blocked = dependsOn.some(\n (depId) => this.#jobs.get(depId)?.state !== \"ok\",\n );\n\n const job: JobRecord = {\n id,\n kind: input.kind,\n envelope: input.envelope,\n sizeClass: input.sizeClass,\n audience: input.audience ?? \"self\",\n owner: input.owner,\n audienceAllow: input.audienceAllow ? [...input.audienceAllow] : undefined,\n dependsOn,\n state: \"queued\",\n lease: null,\n createdAt: now,\n // The TTL clock starts here only if nothing blocks the job.\n claimableAt: blocked ? null : now,\n ttlMs: input.ttlMs ?? this.#defaultTtlMs,\n deadlineAt: input.deadlineAt ?? null,\n refusedBy: [],\n attempts: 0,\n outcome: null,\n provenance: null,\n updatedAt: now,\n };\n this.#write(id, job);\n return Promise.resolve(job);\n }\n\n get(jobId: string): Promise<JobRecord | null> {\n return Promise.resolve(this.#jobs.get(jobId) ?? null);\n }\n\n claim(args: ClaimArgs): Promise<JobRecord[]> {\n // Sweep first so an expired job is never handed out.\n this.#expireDueSync(args.now);\n\n const claimed: JobRecord[] = [];\n // Oldest-claimable first: a job that has waited longest goes next.\n const candidates = [...this.#jobs.values()].sort(\n (a, b) => (a.claimableAt ?? Infinity) - (b.claimableAt ?? Infinity),\n );\n\n for (const job of candidates) {\n if (claimed.length >= args.max) break;\n if (!this.#isClaimable(job, args)) continue;\n\n const updated: JobRecord = {\n ...job,\n state: \"claimed\",\n lease: {\n // A fresh id per grant. Two claims of the same job by the same\n // runner are two different leases, and must be distinguishable.\n id: generateLeaseId(),\n runnerId: args.runnerId,\n expiresAt: args.now + args.leaseMs,\n },\n attempts: job.attempts + 1,\n updatedAt: args.now,\n };\n this.#write(job.id, updated);\n claimed.push(updated);\n }\n return Promise.resolve(claimed);\n }\n\n /**\n * The claim predicate, shared by `claim` and the no-runner signal so the\n * two can never disagree about what \"a runner that could take this\" means.\n */\n #isClaimable(\n job: JobRecord,\n args: Pick<ClaimArgs, \"runnerId\" | \"runnerOwner\" | \"capabilities\" | \"now\">,\n ): boolean {\n if (job.state !== \"queued\") return false;\n if (job.claimableAt === null || job.claimableAt > args.now) return false;\n if (job.refusedBy.includes(args.runnerId)) return false;\n\n const capability = capabilityFor(args.capabilities, job.kind);\n if (!capability) return false;\n\n const match = matchAudience(\n {\n owner: job.owner,\n audience: job.audience,\n audienceAllow: job.audienceAllow,\n },\n {\n owner: args.runnerOwner,\n offerScope: capability.offerScope,\n // From the registry, not a local guess — the cost rules must mean the\n // same thing on both sides of the wire. The server cannot see a\n // remote daemon's base URL, so a generic backend with no declared\n // cost is treated as metered: the expensive side, and the daemon\n // refuses anyway if it disagrees (byollm_007 §2).\n cost: backendDescriptor(capability.backendId).cost ?? \"metered\",\n // Nor can it see the owner's spend consent. It offers; the daemon is\n // the enforcing side and releases with `refused` if its own rules say\n // no — the same shape as the `named` allowlist.\n spend: { acknowledged: true },\n // The server cannot see a remote daemon's local allowlist and must\n // not pretend to (protocol §4.2). It admits the job here; the daemon\n // is the enforcing side and releases with `refused` if its own list\n // says no.\n locallyAllows: () => true,\n },\n );\n return match.ok;\n }\n\n renewLeases(args: RenewArgs): Promise<RenewResult> {\n this.#expireDueSync(args.now);\n\n const renewed: { jobId: string; expiresAt: number }[] = [];\n const lost: string[] = [];\n\n for (const { jobId, leaseId } of args.leases) {\n const job = this.#jobs.get(jobId);\n if (\n !job ||\n job.lease?.runnerId !== args.runnerId ||\n job.lease.id !== leaseId\n ) {\n // Reclaimed by someone else, terminal, or a different grant than the\n // one being renewed — either way this runner must stop.\n lost.push(jobId);\n continue;\n }\n if (job.state !== \"claimed\" && job.state !== \"running\") {\n lost.push(jobId);\n continue;\n }\n const expiresAt = args.now + args.leaseMs;\n this.#write(jobId, {\n ...job,\n state: \"running\",\n // Renewal extends the existing grant; it does not mint a new one.\n lease: { ...job.lease, expiresAt },\n updatedAt: args.now,\n });\n renewed.push({ jobId, expiresAt });\n }\n return Promise.resolve({ renewed, lost });\n }\n\n adopt(args: AdoptArgs): Promise<JobRecord | null> {\n const job = this.#jobs.get(args.jobId);\n if (!job) return Promise.resolve(null);\n // Only a job that is genuinely available can be adopted. A terminal or\n // already-leased job means the relay and this store disagree about\n // reality, and the store's row is not the place to resolve that.\n if (job.state !== \"queued\" && job.state !== \"claimed\") {\n return Promise.resolve(null);\n }\n if (job.lease && job.lease.id !== args.leaseId) {\n return Promise.resolve(null);\n }\n const updated: JobRecord = {\n ...job,\n state: \"claimed\",\n lease: {\n id: args.leaseId,\n // No runner: this site never paired with the machine holding it.\n runnerId: \"\",\n expiresAt: args.expiresAt,\n },\n updatedAt: args.now,\n };\n this.#write(updated.id, updated);\n return Promise.resolve(updated);\n }\n\n complete(args: CompleteArgs): Promise<CompleteResult> {\n const job = this.#jobs.get(args.jobId);\n if (!job) return Promise.resolve({ accepted: false, job: null });\n\n // First terminal outcome wins; a later submission is discarded, not\n // applied ({@link MUSTS.RESULT_IDEMPOTENT}).\n if (\n job.state === \"ok\" ||\n job.state === \"error\" ||\n job.state === \"canceled\"\n ) {\n return Promise.resolve({ accepted: false, job });\n }\n if (job.state === \"expired\") {\n return Promise.resolve({ accepted: false, job });\n }\n // A runner that lost its lease may not write a result\n // ({@link MUSTS.LEASE_HONORED}). Named by lease id when the caller has\n // one — off the direct plane there is no runner this site knows.\n const holds =\n args.holder.by === \"runner\"\n ? job.lease?.runnerId === args.holder.runnerId\n : job.lease?.id === args.holder.leaseId;\n if (!holds) {\n return Promise.resolve({ accepted: false, job });\n }\n\n const state =\n args.outcome.outcome === \"ok\"\n ? \"ok\"\n : args.outcome.outcome === \"canceled\"\n ? \"canceled\"\n : \"error\";\n\n const updated: JobRecord = {\n ...job,\n state,\n lease: null,\n outcome: args.outcome,\n provenance: args.provenance,\n updatedAt: args.now,\n };\n this.#write(job.id, updated);\n this.#cancelRequests.delete(job.id);\n\n if (state === \"ok\") this.#unblockDependents(job.id, args.now);\n\n return Promise.resolve({ accepted: true, job: updated });\n }\n\n /**\n * Start the TTL clock on anything this job was blocking.\n *\n * Deliberately only on `ok`: a dependency that errored leaves its dependents\n * blocked forever rather than releasing them into a run whose input never\n * arrived. They expire at their absolute deadline if one was set, and the\n * app sees a chain that stopped where it broke.\n */\n #unblockDependents(completedId: string, now: number): void {\n for (const job of this.#jobs.values()) {\n if (job.claimableAt !== null) continue;\n if (!job.dependsOn.includes(completedId)) continue;\n const ready = job.dependsOn.every(\n (depId) => this.#jobs.get(depId)?.state === \"ok\",\n );\n if (ready) {\n this.#write(job.id, { ...job, claimableAt: now, updatedAt: now });\n }\n }\n }\n\n /**\n * Watchers, by job id (byollm_009 §8.3).\n *\n * A `Set` per job so an unsubscribe removes exactly the handler it\n * registered — two waiters on the same job are ordinary, and removing by\n * job id alone would silently cancel someone else's wait.\n */\n readonly #watchers = new Map<string, Set<() => void>>();\n\n subscribe(jobId: string, onChange: () => void): () => void {\n const existing = this.#watchers.get(jobId) ?? new Set<() => void>();\n existing.add(onChange);\n this.#watchers.set(jobId, existing);\n let live = true;\n return () => {\n // Idempotent: the contract says calling twice is safe, and a `finally`\n // that unsubscribes after an error path already did is the normal way\n // this gets called twice.\n if (!live) return;\n live = false;\n const set = this.#watchers.get(jobId);\n set?.delete(onChange);\n if (set?.size === 0) this.#watchers.delete(jobId);\n };\n }\n\n /**\n * The single write path for a job.\n *\n * Every mutation goes through here so notification cannot be forgotten by\n * a future one. Nine call sites existed when the push seam was added, and\n * \"remember to notify\" is not a property nine call sites keep.\n */\n #write(jobId: string, record: JobRecord): void {\n this.#jobs.set(jobId, record);\n this.#notify(jobId);\n }\n\n /**\n * Tell anyone watching that a job changed.\n *\n * A throwing watcher must not corrupt the store's own bookkeeping, so each\n * is isolated: this runs inside write paths, and one bad listener taking\n * out an unrelated write would be a far worse failure than a missed\n * notification.\n */\n #notify(jobId: string): void {\n for (const watcher of this.#watchers.get(jobId) ?? []) {\n try {\n watcher();\n } catch {\n // A watcher is a signal handler; the caller re-reads regardless.\n }\n }\n }\n\n release(args: ReleaseArgs): Promise<string[]> {\n const released: string[] = [];\n for (const { jobId, leaseId } of args.leases) {\n const job = this.#jobs.get(jobId);\n // The *grant*, not just its holder. Matching on runner id alone let a\n // replayed release from an earlier lease drop a later one, returning a\n // job to the queue while the daemon was still executing it.\n if (\n !job ||\n job.lease?.runnerId !== args.runnerId ||\n job.lease.id !== leaseId\n ) {\n continue;\n }\n\n this.#write(jobId, {\n ...job,\n state: \"queued\",\n lease: null,\n // Newly available again, so the TTL clock restarts here too.\n claimableAt: args.now,\n // A refusal is remembered, or the pair spins between claim and\n // release forever ({@link MUSTS.REFUSAL_NOT_REOFFERED}).\n refusedBy:\n args.reason === \"refused\"\n ? [...new Set([...job.refusedBy, args.runnerId])]\n : job.refusedBy,\n updatedAt: args.now,\n });\n released.push(jobId);\n }\n return Promise.resolve(released);\n }\n\n expireDue(now: number): Promise<JobRecord[]> {\n return Promise.resolve(this.#expireDueSync(now));\n }\n\n /**\n * Lease expiry and TTL expiry in one idempotent sweep.\n *\n * Order matters: a lease is reclaimed *before* the TTL is judged, so a job\n * whose runner died is offered again rather than being expired for having\n * sat in `claimed` too long.\n */\n #expireDueSync(now: number): JobRecord[] {\n const changed: JobRecord[] = [];\n\n for (const job of this.#jobs.values()) {\n if (\n (job.state === \"claimed\" || job.state === \"running\") &&\n job.lease !== null &&\n job.lease.expiresAt <= now\n ) {\n const requeued: JobRecord = {\n ...job,\n state: \"queued\",\n lease: null,\n // The TTL clock restarts: it measures how long a job has waited\n // *unclaimed*, and this job has just become available again. Without\n // this, a job whose runner died would expire for time it spent being\n // actively worked on — losing exactly the work `kill -9` recovery\n // exists to save. Total lifetime is bounded by `deadlineAt`, which\n // is absolute and unaffected by reclaim.\n claimableAt: now,\n updatedAt: now,\n };\n this.#write(job.id, requeued);\n changed.push(requeued);\n }\n }\n\n for (const job of this.#jobs.values()) {\n if (job.state !== \"queued\") continue;\n const pastDeadline = job.deadlineAt !== null && job.deadlineAt <= now;\n const pastTtl =\n job.claimableAt !== null && job.claimableAt + job.ttlMs <= now;\n if (!pastDeadline && !pastTtl) continue;\n\n const expired: JobRecord = {\n ...job,\n state: \"expired\",\n lease: null,\n updatedAt: now,\n };\n this.#write(job.id, expired);\n changed.push(expired);\n }\n return changed;\n }\n\n cancel(jobId: string, now: number): Promise<JobRecord | null> {\n const job = this.#jobs.get(jobId);\n if (!job) return Promise.resolve(null);\n if (job.state === \"queued\") {\n const canceled: JobRecord = {\n ...job,\n state: \"canceled\",\n lease: null,\n updatedAt: now,\n };\n this.#write(jobId, canceled);\n return Promise.resolve(canceled);\n }\n if (job.state === \"claimed\" || job.state === \"running\") {\n // Held by a runner: the cancel travels on the next heartbeat and the\n // runner reports `canceled` itself, so the job's own state waits.\n this.#cancelRequests.add(jobId);\n return Promise.resolve(job);\n }\n return Promise.resolve(job);\n }\n\n listClaimedBy(runnerId: string): Promise<JobRecord[]> {\n return Promise.resolve(\n [...this.#jobs.values()].filter(\n (job) => job.lease?.runnerId === runnerId,\n ),\n );\n }\n\n listCancelRequests(runnerId: string): Promise<string[]> {\n return Promise.resolve(\n [...this.#cancelRequests].filter(\n (jobId) => this.#jobs.get(jobId)?.lease?.runnerId === runnerId,\n ),\n );\n }\n\n // -- pairing and runners -------------------------------------------------\n\n createPairing(record: PairingRecord): Promise<void> {\n this.#pairings.set(record.deviceCodeHash, record);\n return Promise.resolve();\n }\n\n getPairingByDeviceCodeHash(hash: string): Promise<PairingRecord | null> {\n return Promise.resolve(this.#pairings.get(hash) ?? null);\n }\n\n getPairingByUserCode(userCode: string): Promise<PairingRecord | null> {\n for (const pairing of this.#pairings.values()) {\n if (pairing.userCode === userCode) return Promise.resolve(pairing);\n }\n return Promise.resolve(null);\n }\n\n approvePairing(args: ApproveArgs): Promise<RunnerRecord> {\n const pairing = [...this.#pairings.values()].find(\n (p) => p.userCode === args.userCode,\n );\n if (!pairing) throw new Error(`unknown pairing code: ${args.userCode}`);\n if (pairing.expiresAt <= args.now) {\n throw new Error(\"pairing code has expired\");\n }\n if (pairing.state !== \"pending\") {\n throw new Error(`pairing is already ${pairing.state}`);\n }\n\n const runner: RunnerRecord = {\n id: args.runnerId,\n owner: args.owner,\n tokenHash: args.tokenHash,\n // Carried from the pairing, not re-supplied at approval: the user\n // approved a specific machine, and the runner must be that machine.\n device: pairing.device,\n label: pairing.label,\n platform: pairing.platform,\n daemonVersion: pairing.daemonVersion,\n capabilities: pairing.capabilities,\n paused: false,\n revokedAt: null,\n lastHeartbeatAt: args.now,\n createdAt: args.now,\n };\n this.#runners.set(runner.id, runner);\n this.#pairings.set(pairing.deviceCodeHash, {\n ...pairing,\n state: \"approved\",\n owner: args.owner,\n runnerId: runner.id,\n runnerTokenOnce: args.runnerToken,\n });\n return Promise.resolve(runner);\n }\n\n denyPairing(userCode: string, _now: number): Promise<void> {\n const pairing = [...this.#pairings.values()].find(\n (p) => p.userCode === userCode,\n );\n if (pairing) {\n this.#pairings.set(pairing.deviceCodeHash, {\n ...pairing,\n state: \"denied\",\n });\n }\n return Promise.resolve();\n }\n\n consumePairingToken(deviceCodeHash: string): Promise<void> {\n const pairing = this.#pairings.get(deviceCodeHash);\n if (pairing) {\n this.#pairings.set(deviceCodeHash, {\n ...pairing,\n runnerTokenOnce: null,\n });\n }\n return Promise.resolve();\n }\n\n getRunnerByTokenHash(hash: string): Promise<RunnerRecord | null> {\n for (const runner of this.#runners.values()) {\n if (runner.tokenHash === hash) return Promise.resolve(runner);\n }\n return Promise.resolve(null);\n }\n\n getRunner(runnerId: string): Promise<RunnerRecord | null> {\n return Promise.resolve(this.#runners.get(runnerId) ?? null);\n }\n\n touchRunner(args: TouchArgs): Promise<RunnerRecord | null> {\n const runner = this.#runners.get(args.runnerId);\n if (!runner) return Promise.resolve(null);\n const updated: RunnerRecord = {\n ...runner,\n capabilities: args.capabilities,\n daemonVersion: args.daemonVersion,\n paused: args.paused,\n lastHeartbeatAt: args.now,\n };\n this.#runners.set(runner.id, updated);\n return Promise.resolve(updated);\n }\n\n revokeRunner(runnerId: string, now: number): Promise<void> {\n const runner = this.#runners.get(runnerId);\n // Revocation is one-way: an already-revoked runner keeps its first\n // revocation time rather than being re-stamped.\n if (runner?.revokedAt === null) {\n this.#runners.set(runnerId, { ...runner, revokedAt: now });\n }\n return Promise.resolve();\n }\n\n listRunners(owner?: string): Promise<RunnerRecord[]> {\n const all = [...this.#runners.values()];\n return Promise.resolve(\n owner === undefined ? all : all.filter((r) => r.owner === owner),\n );\n }\n\n // -- test/demo helpers ---------------------------------------------------\n\n /** All jobs, for demos and assertions. Not part of the store interface. */\n allJobs(): JobRecord[] {\n return [...this.#jobs.values()];\n }\n}\n\n/** The capability that would serve a kind, if any. */\nexport function capabilityFor(\n capabilities: readonly Capability[],\n kind: string,\n): Capability | undefined {\n return capabilities.find((c) => c.kind === kind);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AAK,SAAS,OAAO,CAAC;AACtC,WAAO,QAAQ;AAAA,MACb,UAAU,SAAY,MAAM,IAAI,OAAO,CAAC,MAAM,EAAE,UAAU,KAAK;AAAA,IACjE;AAAA,EACF;AAAA;AAAA;AAAA,EAKA,UAAuB;AACrB,WAAO,CAAC,GAAG,KAAK,MAAM,OAAO,CAAC;AAAA,EAChC;AACF;AAGO,SAAS,cACd,cACA,MACwB;AACxB,SAAO,aAAa,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI;AACjD;","names":["keyId","publicIdentityOf","keyId","publicIdentityOf","publicIdentityOf","backendDescriptor","matchAudience","matchAudience","backendDescriptor"]}
1
+ {"version":3,"sources":["../src/app.ts","../src/cloud.ts","../src/keys.ts","../src/memory.ts"],"sourcesContent":["import {\n ENVELOPE_MAX_AGE_MS,\n KindedPayload,\n keyId,\n payloadTextLength,\n publicIdentityOf,\n seal,\n sizeClassOf,\n type StoredKeys,\n backendDescriptor,\n matchAudience,\n type DeliveredResult,\n type JobKind,\n} from \"@byollm/protocol\";\nimport {\n PollingDelivery,\n type PollingDeliveryDeps,\n type ResultDelivery,\n type WaitOptions,\n} from \"./delivery.js\";\nimport {\n generateJobId,\n generateRunnerId,\n generateRunnerToken,\n hashSecret,\n} from \"./ids.js\";\nimport { CloudLane, type CloudLaneOptions } from \"./cloud.js\";\nimport type { EnqueueInput, JobRecord, RunnerRecord } from \"./records.js\";\nimport type { ByollmStore } from \"./store.js\";\n\n/**\n * How long since a runner's last heartbeat before it stops counting as live.\n * Three heartbeats of slack at the daemon's ~10s cadence.\n */\nconst DEFAULT_LIVENESS_MS = 35_000;\n\n/** Why a job cannot presently run. */\nexport type NoRunnerReason =\n | \"no-runner-paired\"\n | \"no-runner-online\"\n | \"no-matching-capability\"\n | \"audience-admits-nobody\";\n\n/**\n * The no-runner signal (byollm_001 Rev 1 §D).\n *\n * `available: false` means an app should fall back — hosted model, \"start\n * your runner\" prompt — rather than awaiting something that will never\n * resolve. A job still blocked on dependencies is **not** unavailable; it is\n * waiting, and saying otherwise would make every multi-job flow look broken\n * ({@link MUSTS.NO_RUNNER_SIGNAL}).\n */\nexport interface RunnerAvailability {\n readonly available: boolean;\n readonly reason?: NoRunnerReason;\n /** Live runners that could take work of this shape. */\n readonly candidates: number;\n}\n\nexport interface AvailabilityQuery {\n readonly kind: JobKind;\n readonly owner: string;\n readonly audience?: \"self\" | \"named\" | \"public\";\n readonly audienceAllow?: readonly string[];\n}\n\nexport interface ByollmAppOptions {\n readonly store: ByollmStore;\n /** Injectable clock. */\n readonly now?: () => number;\n /** Liveness window for the no-runner signal. */\n readonly livenessMs?: number;\n /**\n * How the app learns a job finished. Defaults to polling the store, which\n * is correct everywhere; the Supabase adapter substitutes Realtime.\n */\n readonly delivery?: (deps: PollingDeliveryDeps) => ResultDelivery;\n /**\n * How long a sustained no-runner signal must persist before `result()`\n * gives up. Longer tolerates a daemon restarting; shorter fails faster.\n */\n readonly noRunnerGraceMs?: number;\n /**\n * This site's keypairs — the same ones the handlers use.\n *\n * The app needs them because it is the *endpoint*: it seals work on the way\n * in and opens results on the way out. Nothing between those two points\n * holds plaintext (byollm_009 §10).\n */\n readonly siteKeys: StoredKeys;\n /**\n * Which connection plane this site uses — cloud_004 §9.4.\n *\n * Omitted means `direct`: a daemon reaches this site's own handlers, and\n * everything works as it always has. Supplying a relay switches the plane\n * and nothing else — `enqueue` is identical in every lane, which is the\n * property that lets the same app move between them by config.\n */\n readonly lane?: CloudLaneOptions;\n}\n\n/**\n * An enqueued job, with the delivery channel attached.\n *\n * `result()` is sugar over the channel — with a timeout and a\n * `noRunnerAvailable` path — never a bare promise that can hang forever\n * (byollm_003 Rev 1).\n */\nexport interface JobHandle {\n readonly id: string;\n /** The job as stored at enqueue time. */\n readonly record: JobRecord;\n /** Wait for a terminal outcome. */\n result(options?: WaitOptions): Promise<DeliveredResult>;\n /** Ask the runner to stop. */\n cancel(): Promise<void>;\n}\n\n/**\n * The app-facing half of `@byollm/server`.\n *\n * The daemon talks to {@link ByollmHandlers}; the app talks to this. Keeping\n * them separate is what makes \"one door per state write\" hold — an app\n * enqueues and cancels through these methods and never writes job rows by\n * hand.\n */\nexport class ByollmApp {\n readonly #store: ByollmStore;\n readonly #siteKeys: StoredKeys;\n readonly #now: () => number;\n readonly #livenessMs: number;\n readonly #delivery: ResultDelivery;\n /** Present only in the cloud lane; the site's side of the relay. */\n readonly cloud: CloudLane | undefined;\n\n constructor(options: ByollmAppOptions) {\n this.#store = options.store;\n this.#siteKeys = options.siteKeys;\n this.#now = options.now ?? Date.now;\n this.#livenessMs = options.livenessMs ?? DEFAULT_LIVENESS_MS;\n this.cloud =\n options.lane === undefined\n ? undefined\n : new CloudLane({\n options: options.lane,\n store: options.store,\n siteKeys: options.siteKeys,\n now: this.#now,\n });\n\n const deps: PollingDeliveryDeps = {\n ...(options.noRunnerGraceMs === undefined\n ? {}\n : { graceMs: options.noRunnerGraceMs }),\n read: (jobId) => this.result(jobId),\n availability: async (jobId) => {\n const job = await this.#store.get(jobId);\n if (!job)\n return { available: false, reason: \"unknown-job\", blocked: false };\n // A job waiting on a dependency is waiting, not unavailable.\n if (job.claimableAt === null) {\n return { available: true, blocked: true };\n }\n const availability = await this.runnerAvailability({\n kind: job.kind,\n owner: job.owner,\n audience: job.audience,\n ...(job.audienceAllow === undefined\n ? {}\n : { audienceAllow: job.audienceAllow }),\n });\n return {\n available: availability.available,\n ...(availability.reason === undefined\n ? {}\n : { reason: availability.reason }),\n blocked: false,\n };\n },\n };\n this.#delivery = options.delivery?.(deps) ?? new PollingDelivery(deps);\n }\n\n /**\n * Enqueue a job.\n *\n * `audience` defaults to `self` — the safe direction. Widening it means the\n * result comes back marked untrusted (see {@link ByollmApp.result}), and\n * the app is obliged to disclose that to whoever reads it.\n */\n async enqueue(input: EnqueueInput): Promise<JobHandle> {\n // Validate the payload against its kind before anything stores it.\n //\n // The schemas are `.strict()`, so this drops a payload carrying fields\n // the kind does not define — `command`, `argv`, `model`, `baseUrl`. Types\n // do not survive a JSON boundary, and an app assembling a payload from\n // user input is the ordinary case, so \"the caller is typed\" is not a\n // check ({@link MUSTS.KIND_NO_CODE}, {@link MUSTS.NO_PAYLOAD_ROUTING}).\n //\n // Refusing here rather than relying on the daemon is deliberate. The\n // daemon does re-validate and would reject this — but it parses a whole\n // claim response at once, so one malformed job would fail the batch it\n // arrived in and stall unrelated work. Rejecting at enqueue puts the\n // error where the app can act on it.\n const parsed = KindedPayload.safeParse({\n kind: input.kind,\n payload: input.payload,\n });\n if (!parsed.success) {\n const detail = parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"(root)\"}: ${issue.message}`)\n .join(\"; \");\n throw new Error(`invalid ${input.kind} payload — ${detail}`);\n }\n\n // Sealed before it is stored, to this site's own key. The app is the\n // endpoint, so it can open its own work later; the store, its backups and\n // anything reading them cannot.\n // Two different deadlines, deliberately not conflated:\n //\n // - the *job's* deadline is the app's business, may be absent, and for a\n // dependent job its TTL clock does not even start until the job becomes\n // claimable (`TTL_EXPIRY`). Setting one here broke exactly that.\n // - the *envelope's* deadline bounds how long a captured ciphertext is\n // worth keeping. It is bound into the signature, so it has to be\n // recomputable at open time from what the record stores — hence\n // creation plus TTL, which never moves.\n // Resolved *here*, once, and passed to the store — because the envelope\n // binds it. Letting the app default one value and the store default\n // another produced a job whose seal and record disagreed, and therefore\n // work nobody could open.\n // One reading of the clock, used for both the seal and the record.\n //\n // Two readings passed every fake-clock test and failed against a real\n // one: the envelope bound `createdAt + ttlMs` from the first call and the\n // record stored `createdAt` from the second, a millisecond later, so\n // nothing could be opened. A fixed clock returns the same number twice\n // and hides it completely.\n const createdAt = this.#now();\n // Independent of the job's TTL, deliberately. Binding the envelope to\n // `createdAt + ttl` meant the app had to decide a TTL in order to seal —\n // which overrode the store's own default and broke every expiry test.\n // The two answer different questions: how long the work is worth doing,\n // and how long the ciphertext is worth keeping.\n const envelopeDeadlineAt = createdAt + ENVELOPE_MAX_AGE_MS;\n const jobId = input.id ?? generateJobId();\n const senderKeyId = keyId(publicIdentityOf(this.#siteKeys).identity);\n const envelope = await seal({\n plaintext: JSON.stringify(parsed.data.payload),\n senderKeys: this.#siteKeys,\n recipientEncryptionPublic: this.#siteKeys.encryptionPublic,\n context: {\n jobId,\n senderKeyId,\n recipientKeyId: senderKeyId,\n deadlineAt: envelopeDeadlineAt,\n direction: \"payload\",\n },\n });\n\n const record = await this.#store.create(\n {\n ...input,\n id: jobId,\n envelope,\n sizeClass: sizeClassOf(\n payloadTextLength({\n kind: input.kind,\n payload: parsed.data.payload,\n } as Parameters<typeof payloadTextLength>[0]),\n ),\n },\n createdAt,\n );\n // The lane's only intrusion into enqueue, and it is additive: the record\n // is already stored and sealed at rest before anything is published, so a\n // relay that is down costs a routing delay rather than a lost job.\n await this.cloud?.publish(record);\n\n return {\n id: record.id,\n record,\n result: (options?: WaitOptions) =>\n this.#delivery.waitFor(record.id, options),\n cancel: async () => {\n await this.cancel(record.id);\n },\n };\n }\n\n /** Read a job's current state. */\n async job(jobId: string): Promise<JobRecord | null> {\n await this.#store.expireDue(this.#now());\n return this.#store.get(jobId);\n }\n\n /**\n * A job's result with its provenance attached.\n *\n * Check `provenance.untrusted` before rendering. It is true for every\n * `named`/`public` job, because that text came from someone else's machine\n * and the app must not present it as its own AI's answer\n * ({@link MUSTS.RESULT_PROVENANCE}).\n */\n async result(jobId: string): Promise<DeliveredResult | null> {\n const job = await this.job(jobId);\n if (!job) return null;\n return {\n jobId: job.id,\n state: job.state,\n ...(job.outcome === null ? {} : { outcome: job.outcome }),\n ...(job.provenance === null ? {} : { provenance: job.provenance }),\n };\n }\n\n /** Ask a runner to stop. Queued jobs cancel at once; held jobs at the next heartbeat. */\n async cancel(jobId: string): Promise<JobRecord | null> {\n return this.#store.cancel(jobId, this.#now());\n }\n\n /**\n * Is there a live runner that could take a job of this shape?\n *\n * Runs the identical {@link matchAudience} rule the claim path uses, so the\n * signal cannot promise a runner the claim would then refuse.\n */\n async runnerAvailability(\n query: AvailabilityQuery,\n ): Promise<RunnerAvailability> {\n const now = this.#now();\n const all = await this.#store.listRunners();\n const live = all.filter(\n (runner) =>\n runner.revokedAt === null &&\n !runner.paused &&\n now - runner.lastHeartbeatAt <= this.#livenessMs,\n );\n\n if (all.length === 0) {\n return { available: false, reason: \"no-runner-paired\", candidates: 0 };\n }\n if (live.length === 0) {\n return { available: false, reason: \"no-runner-online\", candidates: 0 };\n }\n\n let capable = 0;\n let admitted = 0;\n for (const runner of live) {\n const capability = runner.capabilities.find((c) => c.kind === query.kind);\n if (!capability) continue;\n capable += 1;\n\n const match = matchAudience(\n {\n owner: query.owner,\n audience: query.audience ?? \"self\",\n audienceAllow: query.audienceAllow,\n },\n {\n owner: runner.owner,\n offerScope: capability.offerScope,\n // A generic backend's cost depends on its base URL, which the\n // server never sees; assume the expensive reading (byollm_007 §4).\n cost: backendDescriptor(capability.backendId).cost ?? \"metered\",\n // Consent is the daemon's to hold, and it has already applied it:\n // the offer scope arriving here is the *effective* one, so a\n // metered backend nobody agreed to share advertises `self` and is\n // refused by the scope rule above. Re-deriving consent from\n // `false` here would instead refuse every backend an owner\n // deliberately shared, because the server has no way to learn they\n // did — the signal would be wrong in the direction that breaks\n // working setups.\n spend: { acknowledged: true },\n // Same conservative assumption the claim path makes: the server\n // cannot see a remote daemon's local allowlist (protocol §4.2).\n locallyAllows: () => true,\n },\n );\n if (match.ok) admitted += 1;\n }\n\n if (capable === 0) {\n return {\n available: false,\n reason: \"no-matching-capability\",\n candidates: 0,\n };\n }\n if (admitted === 0) {\n return {\n available: false,\n reason: \"audience-admits-nobody\",\n candidates: 0,\n };\n }\n return { available: true, candidates: admitted };\n }\n\n /**\n * Approve a pairing on behalf of an authenticated user.\n *\n * `owner` MUST come from the approving user's own session. A daemon can\n * never assert who it is — that is the whole reason pairing is interactive\n * ({@link MUSTS.PAIR_ONE_USER}, {@link MUSTS.PAIR_INTERACTIVE}).\n */\n async approvePairing(args: {\n userCode: string;\n owner: string;\n }): Promise<RunnerRecord> {\n const token = generateRunnerToken();\n return this.#store.approvePairing({\n userCode: normalizeUserCode(args.userCode),\n owner: args.owner,\n runnerId: generateRunnerId(),\n runnerToken: token,\n tokenHash: hashSecret(token),\n now: this.#now(),\n });\n }\n\n /** Deny a pairing the user did not initiate. */\n async denyPairing(userCode: string): Promise<void> {\n return this.#store.denyPairing(normalizeUserCode(userCode), this.#now());\n }\n\n /** What a pairing code refers to, for the approval page to show. */\n async pendingPairing(userCode: string): Promise<{\n label: string;\n platform: string;\n daemonVersion: string;\n capabilities: readonly { kind: string; model: string }[];\n expiresAt: number;\n } | null> {\n const pairing = await this.#store.getPairingByUserCode(\n normalizeUserCode(userCode),\n );\n if (pairing?.state !== \"pending\") return null;\n if (pairing.expiresAt <= this.#now()) return null;\n return {\n label: pairing.label,\n platform: pairing.platform,\n daemonVersion: pairing.daemonVersion,\n capabilities: pairing.capabilities.map((c) => ({\n kind: c.kind,\n model: c.model,\n })),\n expiresAt: pairing.expiresAt,\n };\n }\n\n /** The user's paired runners, for a settings page. */\n async runners(owner: string): Promise<RunnerRecord[]> {\n return this.#store.listRunners(owner);\n }\n\n /** Revoke a runner. It stops at its next heartbeat, mid-queue. */\n async revokeRunner(runnerId: string): Promise<void> {\n return this.#store.revokeRunner(runnerId, this.#now());\n }\n\n /** Run the expiry sweep. Idempotent; safe to call on a timer or a request. */\n async sweep(): Promise<JobRecord[]> {\n return this.#store.expireDue(this.#now());\n }\n}\n\n/**\n * Accept a pairing code however the user typed it — lowercase, spaces, no\n * dash. The code is displayed as `XXXX-XXXX`; refusing `xxxxxxxx` would fail\n * a user for a formatting detail they were never told mattered.\n */\nexport function normalizeUserCode(input: string): string {\n const bare = input.toUpperCase().replace(/[^A-Z0-9]/g, \"\");\n return bare.length === 8 ? `${bare.slice(0, 4)}-${bare.slice(4)}` : bare;\n}\n","import {\n JobOutcome,\n type SealedEnvelope,\n keyId,\n open,\n publicIdentityOf,\n provenanceFor,\n signSiteRequest,\n type JobStub,\n type PublicIdentity,\n type StoredKeys,\n} from \"@byollm/protocol\";\nimport type { JobRecord } from \"./records.js\";\nimport { resealForDevice } from \"./reseal.js\";\nimport type { ByollmStore } from \"./store.js\";\n\n/**\n * The cloud lane — cloud_004 §9.4.\n *\n * `app.enqueue(...)` is identical in every lane; the lane picks the connection\n * plane. In `direct` mode a daemon reaches the site's own handlers. In `cloud`\n * mode it reaches a relay instead, and the site's side of that is this file.\n *\n * ## What actually changes, and what deliberately does not\n *\n * Enqueue does not change at all. The job is validated, sealed at rest to the\n * site's own key and stored, exactly as before — jobs-at-rest encryption is a\n * direct-mode property that the cloud lane inherits rather than replaces.\n *\n * What changes is *who asks for the payload and when*. On the direct plane the\n * daemon asks, and the site answers synchronously because it is the upstream.\n * Through a relay the site is not the upstream, so nobody asks: the site has to\n * find out that a device claimed its job, and seal to that device. Hence a\n * pump rather than a handler.\n *\n * ```\n * enqueue ──stub──▶ relay (payload stays here, sealed at rest)\n * │\n * pump ◀──who claimed it, and what key?\n * ──payload sealed to that device──▶\n * pump ◀──sealed result── ──▶ store.complete → the app's delivery channel\n * ```\n *\n * ## Why the site polls\n *\n * Everything in this product is outbound. A relay that called site webhooks\n * would need every site publicly reachable, which is the connectivity problem\n * the hub exists to remove — and a serverless site has nowhere to receive a\n * webhook anyway. So the site polls, exactly as a daemon does.\n */\n\nexport interface CloudLaneOptions {\n /** Where the relay lives, e.g. `https://relay.byollm.cloud`. */\n readonly relayOrigin: string;\n /** This site's id at the relay. */\n readonly siteId: string;\n /** Injectable fetch, for tests and for proxies. */\n readonly fetch?: typeof fetch;\n}\n\n/** What one pump cycle did, for logging and for tests. */\nexport interface PumpReport {\n /** Jobs sealed to a claiming device this cycle. */\n readonly sealed: string[];\n /** Results opened, verified and written to the store. */\n readonly completed: string[];\n /**\n * Jobs the relay offered that this site refused to seal for.\n *\n * Never silent: a site that cannot open its own at-rest envelope has a key\n * problem, and a device waiting on a payload that will never come is\n * exactly the case `awaiting-payload` exists to bound.\n */\n readonly refused: string[];\n}\n\nexport class CloudLane {\n readonly #options: CloudLaneOptions;\n readonly #store: ByollmStore;\n readonly #siteKeys: StoredKeys;\n readonly #now: () => number;\n readonly #fetch: typeof fetch;\n\n constructor(deps: {\n options: CloudLaneOptions;\n store: ByollmStore;\n siteKeys: StoredKeys;\n now: () => number;\n }) {\n this.#options = deps.options;\n this.#store = deps.store;\n this.#siteKeys = deps.siteKeys;\n this.#now = deps.now;\n this.#fetch = deps.options.fetch ?? globalThis.fetch;\n }\n\n /**\n * Publish a job's stub for routing.\n *\n * The stub and nothing else — byollm_009 §6 makes that exhaustive by\n * construction, so this cannot leak a payload even by mistake: there is no\n * field on `JobStub` to put one in.\n */\n async publish(record: JobRecord): Promise<void> {\n const stub: JobStub = {\n id: record.id,\n kind: record.kind,\n owner: record.owner,\n audience: record.audience,\n ...(record.audienceAllow === undefined\n ? {}\n : { audienceAllow: [...record.audienceAllow] }),\n sizeClass: record.sizeClass,\n streaming: false,\n // The relay needs *a* deadline to bound routing. A job without one gets\n // the envelope's, which is the outer bound on how long the ciphertext\n // is worth carrying — never longer than the work could possibly matter.\n deadlineAt: record.deadlineAt ?? record.createdAt + ENVELOPE_TTL_FALLBACK,\n };\n await this.#post(\"enqueue\", {\n siteId: this.#options.siteId,\n stub,\n });\n }\n\n /**\n * One cycle: seal for anything claimed, collect anything finished.\n *\n * Idempotent and safe to call as often as you like. Exposed as a single\n * cycle rather than hidden behind a timer so a caller decides its own\n * cadence — a serverless site runs it on a cron, a long-lived one on an\n * interval, and a test runs it exactly when it means to.\n */\n async pump(): Promise<PumpReport> {\n const sealed: string[] = [];\n const refused: string[] = [];\n const completed: string[] = [];\n\n const pending = (await this.#get(\"pending\")) as {\n jobs: {\n jobId: string;\n device: PublicIdentity;\n runnerId: string;\n leaseId: string;\n awaitingUntil: number;\n }[];\n };\n for (const claim of pending.jobs) {\n const record = await this.#store.get(claim.jobId);\n if (!record) continue;\n const resealed = await resealForDevice({\n siteKeys: this.#siteKeys,\n job: {\n id: record.id,\n envelope: record.envelope,\n createdAt: record.createdAt,\n },\n device: claim.device,\n });\n if (!resealed.ok) {\n refused.push(claim.jobId);\n continue;\n }\n // Record the lease the relay granted, before handing over the work.\n //\n // The site is not the upstream here and does not decide who holds what\n // — but its own row has to know, or two things break that are not\n // cosmetic: `complete` refuses the result for want of a matching lease,\n // and the expiry sweep expires a job a device is in the middle of.\n // Adopting first means the worst case is a lease recorded for work that\n // never gets sealed, which the relay's own timeout already resolves.\n await this.#store.adopt({\n jobId: claim.jobId,\n leaseId: claim.leaseId,\n expiresAt: claim.awaitingUntil,\n now: this.#now(),\n });\n await this.#post(\"payload\", {\n siteId: this.#options.siteId,\n jobId: claim.jobId,\n envelope: resealed.envelope,\n });\n sealed.push(claim.jobId);\n }\n\n const finished = (await this.#get(\"results\")) as {\n jobs: {\n jobId: string;\n envelope: SealedEnvelope;\n disposition: string;\n runnerId: string;\n leaseId: string;\n device: PublicIdentity;\n }[];\n };\n for (const done of finished.jobs) {\n const record = await this.#store.get(done.jobId);\n if (!record || record.state === \"ok\" || record.state === \"error\") {\n continue;\n }\n const outcome = await this.#openResult(done);\n if (!outcome) {\n refused.push(done.jobId);\n continue;\n }\n // Provenance is built here, from the job's audience and the device the\n // relay named — never from anything the daemon asserted. Identical to\n // the direct plane's rule, and it has to be: a result arriving via a\n // relay is not more trustworthy for having travelled further.\n await this.#store.complete({\n jobId: done.jobId,\n // The grant, not the machine: this site never paired with the device\n // that ran it, and the signature it verified above is the stronger\n // claim about who did.\n holder: { by: \"lease\", leaseId: done.leaseId },\n outcome,\n provenance: provenanceFor({\n audience: record.audience,\n runnerId: done.runnerId,\n runnerOwner: keyId(done.device.identity),\n backendClass: \"http\",\n model: \"unknown\",\n }),\n now: this.#now(),\n });\n completed.push(done.jobId);\n }\n\n return { sealed, completed, refused };\n }\n\n /**\n * Open a sealed result and verify it came from the device that claimed it.\n *\n * The relay says which device ran the job; this checks that claim against a\n * signature the relay cannot produce. A relay that named the wrong device\n * gets a refusal, not a stored result — which is what keeps `RELAY_BLIND`\n * from quietly becoming `RELAY_TRUSTED`.\n */\n async #openResult(done: {\n jobId: string;\n envelope: SealedEnvelope;\n disposition: string;\n device: PublicIdentity;\n }): Promise<JobOutcome | null> {\n const opened = await open({\n envelope: done.envelope,\n recipientKeys: this.#siteKeys,\n senderIdentityPublic: done.device.identity,\n expected: {\n jobId: done.jobId,\n senderKeyId: keyId(done.device.identity),\n recipientKeyId: keyId(publicIdentityOf(this.#siteKeys).identity),\n direction: \"result\",\n },\n });\n if (!opened.ok) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(opened.plaintext);\n } catch {\n return null;\n }\n const outcome = JobOutcome.safeParse(parsed);\n if (!outcome.success) return null;\n // The clear-text disposition is a routing hint the relay acted on. This\n // is the only place it can be checked, because this is the only party\n // that can open the envelope (byollm_009 §6.1).\n if (outcome.data.outcome !== done.disposition) return null;\n return outcome.data;\n }\n\n /**\n * Sign a site-plane call with this site's identity key.\n *\n * The same scheme the daemon uses against an upstream, because the site is\n * in the same position: an outbound caller whose key the relay already holds\n * for other reasons. Nothing else authenticates this plane — a relay that\n * took the `siteId` in a body at face value would let anyone enqueue work in\n * a site's name and read who claimed it.\n */\n #headers(endpoint: string, rawBody: string): Record<string, string> {\n const signature = signSiteRequest(this.#siteKeys, {\n endpoint,\n siteId: this.#options.siteId,\n issuedAt: this.#now(),\n body: rawBody,\n });\n return {\n \"x-byollm-site\": this.#options.siteId,\n \"x-byollm-issued-at\": String(signature.issuedAt),\n \"x-byollm-signature\": signature.signature,\n };\n }\n\n async #post(endpoint: string, body: unknown): Promise<unknown> {\n const rawBody = JSON.stringify(body);\n const response = await this.#fetch(\n `${this.#options.relayOrigin}/relay/site/${endpoint}`,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...this.#headers(endpoint, rawBody),\n },\n body: rawBody,\n },\n );\n return response.json();\n }\n\n async #get(endpoint: string): Promise<unknown> {\n const url = `${this.#options.relayOrigin}/relay/site/${endpoint}?siteId=${encodeURIComponent(this.#options.siteId)}`;\n // A read signs an empty body: the site id is in the query and in the\n // signed caller slot, and the relay refuses the request unless they agree.\n const response = await this.#fetch(url, {\n headers: this.#headers(endpoint, \"\"),\n });\n return response.json();\n }\n}\n\n/** Only used when a job carries no deadline of its own. */\nconst ENVELOPE_TTL_FALLBACK = 24 * 60 * 60_000;\n","import { StoredKeys, generateKeys, publicIdentityOf } from \"@byollm/protocol\";\nimport { fingerprint } from \"@byollm/protocol\";\n\n/**\n * A site's keypairs — byollm_009 §5.\n *\n * **Generate once, store, supply.** Not at startup, and not per process.\n *\n * A site is usually more than one process: several instances behind a load\n * balancer, or a serverless function whose module is evaluated per cold\n * start. Keys generated at startup would give each of those a different\n * identity. A daemon pins whichever one approved its pairing, and then every\n * request routed to a different instance fails a signature check with nothing\n * in the error explaining why — a failure that appears only under\n * horizontal scale, which is to say only in production.\n *\n * So the library takes keys as an input and never invents them. That is the\n * whole reason this module is three functions rather than a lazy singleton.\n */\n\n/** Make a fresh site identity. Call this once, ever, and keep the result. */\nexport const generateSiteKeys = (now: number = Date.now()): StoredKeys =>\n generateKeys(now);\n\n/**\n * Read site keys from an environment variable holding base64 JSON.\n *\n * The shape a deployment actually wants: one opaque secret, set the way every\n * other secret is set, with no file to mount and no key material in the\n * repository.\n *\n * @throws with a message naming the variable and the fix, because this fails\n * at boot and the person reading the log is the person who can fix it.\n */\nexport function siteKeysFromEnv(\n variable = \"BYOLLM_SITE_KEYS\",\n env: NodeJS.ProcessEnv = process.env,\n): StoredKeys {\n const raw = env[variable];\n if (raw === undefined || raw === \"\") {\n throw new Error(\n `${variable} is not set. Generate a site identity once with ` +\n `\\`npx @byollm/server keygen\\` and set it as ${variable}. ` +\n `Do not generate keys at startup: every instance would get a ` +\n `different identity and daemons would pin one and be refused by ` +\n `another.`,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(Buffer.from(raw, \"base64\").toString(\"utf8\"));\n } catch {\n throw new Error(\n `${variable} is not base64-encoded JSON. It should be exactly what ` +\n `\\`npx @byollm/server keygen\\` printed.`,\n );\n }\n\n const result = StoredKeys.safeParse(parsed);\n if (!result.success) {\n throw new Error(\n `${variable} does not contain a valid site identity. Regenerate it ` +\n `with \\`npx @byollm/server keygen\\` — and if this site has already ` +\n `paired daemons, they will need to pair again.`,\n );\n }\n return result.data;\n}\n\n/** What to print from `keygen`: the secret to store, and how to check it. */\nexport function formatSiteKeys(keys: StoredKeys): string {\n const encoded = Buffer.from(JSON.stringify(keys)).toString(\"base64\");\n return (\n `# Set this as BYOLLM_SITE_KEYS. It is a secret: it is this site's\\n` +\n `# identity, and anything holding it can be this site.\\n` +\n `BYOLLM_SITE_KEYS=${encoded}\\n` +\n `\\n` +\n `# Fingerprint (not secret — show it to users so they can check what\\n` +\n `# their daemon pinned):\\n` +\n `# ${fingerprint(publicIdentityOf(keys).identity)}\\n`\n );\n}\n","import {\n backendDescriptor,\n matchAudience,\n type Capability,\n} from \"@byollm/protocol\";\nimport { generateLeaseId } from \"./ids.js\";\nimport type {\n StoredJobInput,\n JobRecord,\n PairingRecord,\n RunnerRecord,\n} from \"./records.js\";\nimport type {\n ApproveArgs,\n ByollmStore,\n ClaimArgs,\n AdoptArgs,\n CompleteArgs,\n CompleteResult,\n ReleaseArgs,\n RenewArgs,\n RenewResult,\n TouchArgs,\n} from \"./store.js\";\n\n/** Tunables an embedder may want to override in tests. */\nexport interface MemoryStoreOptions {\n /** Default TTL for a job once claimable. */\n readonly defaultTtlMs?: number;\n}\n\nconst DEFAULT_TTL_MS = 15 * 60_000;\n\n/**\n * The reference store: everything in one process, no persistence.\n *\n * This is not a toy — it is the implementation the conformance kit certifies\n * first, so its semantics *are* the specification's semantics for anything\n * the prose leaves implicit. A SQL adapter is correct when the same kit\n * passes against it.\n *\n * Concurrency: JavaScript's single-threaded turn is the atomicity primitive.\n * `claim` performs its read-decide-write with no `await` inside the critical\n * section, which is what makes {@link MUSTS.CLAIM_ATOMIC} hold here. A SQL\n * adapter gets the same property from `FOR UPDATE SKIP LOCKED`.\n */\nexport class MemoryStore implements ByollmStore {\n readonly #jobs = new Map<string, JobRecord>();\n readonly #runners = new Map<string, RunnerRecord>();\n readonly #pairings = new Map<string, PairingRecord>();\n /** Job ids the app has asked to cancel, not yet acknowledged by a runner. */\n readonly #cancelRequests = new Set<string>();\n readonly #defaultTtlMs: number;\n\n constructor(options: MemoryStoreOptions = {}) {\n this.#defaultTtlMs = options.defaultTtlMs ?? DEFAULT_TTL_MS;\n }\n\n // -- jobs ---------------------------------------------------------------\n\n create(input: StoredJobInput, now: number): Promise<JobRecord> {\n // Required now: the app mints the id before sealing, because the\n // envelope binds it.\n const id = input.id;\n const existing = this.#jobs.get(id);\n // Idempotent by caller-supplied id: re-enqueueing the same id is a no-op,\n // so an app's retry cannot duplicate work (the house \"one door\" rule).\n if (existing) return Promise.resolve(existing);\n\n const dependsOn = [...(input.dependsOn ?? [])];\n const blocked = dependsOn.some(\n (depId) => this.#jobs.get(depId)?.state !== \"ok\",\n );\n\n const job: JobRecord = {\n id,\n kind: input.kind,\n envelope: input.envelope,\n sizeClass: input.sizeClass,\n audience: input.audience ?? \"self\",\n owner: input.owner,\n audienceAllow: input.audienceAllow ? [...input.audienceAllow] : undefined,\n dependsOn,\n state: \"queued\",\n lease: null,\n createdAt: now,\n // The TTL clock starts here only if nothing blocks the job.\n claimableAt: blocked ? null : now,\n ttlMs: input.ttlMs ?? this.#defaultTtlMs,\n deadlineAt: input.deadlineAt ?? null,\n refusedBy: [],\n attempts: 0,\n outcome: null,\n provenance: null,\n updatedAt: now,\n };\n this.#write(id, job);\n return Promise.resolve(job);\n }\n\n get(jobId: string): Promise<JobRecord | null> {\n return Promise.resolve(this.#jobs.get(jobId) ?? null);\n }\n\n claim(args: ClaimArgs): Promise<JobRecord[]> {\n // Sweep first so an expired job is never handed out.\n this.#expireDueSync(args.now);\n\n const claimed: JobRecord[] = [];\n // Oldest-claimable first: a job that has waited longest goes next.\n const candidates = [...this.#jobs.values()].sort(\n (a, b) => (a.claimableAt ?? Infinity) - (b.claimableAt ?? Infinity),\n );\n\n for (const job of candidates) {\n if (claimed.length >= args.max) break;\n if (!this.#isClaimable(job, args)) continue;\n\n const updated: JobRecord = {\n ...job,\n state: \"claimed\",\n lease: {\n // A fresh id per grant. Two claims of the same job by the same\n // runner are two different leases, and must be distinguishable.\n id: generateLeaseId(),\n runnerId: args.runnerId,\n expiresAt: args.now + args.leaseMs,\n },\n attempts: job.attempts + 1,\n updatedAt: args.now,\n };\n this.#write(job.id, updated);\n claimed.push(updated);\n }\n return Promise.resolve(claimed);\n }\n\n /**\n * The claim predicate, shared by `claim` and the no-runner signal so the\n * two can never disagree about what \"a runner that could take this\" means.\n */\n #isClaimable(\n job: JobRecord,\n args: Pick<ClaimArgs, \"runnerId\" | \"runnerOwner\" | \"capabilities\" | \"now\">,\n ): boolean {\n if (job.state !== \"queued\") return false;\n if (job.claimableAt === null || job.claimableAt > args.now) return false;\n if (job.refusedBy.includes(args.runnerId)) return false;\n\n const capability = capabilityFor(args.capabilities, job.kind);\n if (!capability) return false;\n\n const match = matchAudience(\n {\n owner: job.owner,\n audience: job.audience,\n audienceAllow: job.audienceAllow,\n },\n {\n owner: args.runnerOwner,\n offerScope: capability.offerScope,\n // From the registry, not a local guess — the cost rules must mean the\n // same thing on both sides of the wire. The server cannot see a\n // remote daemon's base URL, so a generic backend with no declared\n // cost is treated as metered: the expensive side, and the daemon\n // refuses anyway if it disagrees (byollm_007 §2).\n cost: backendDescriptor(capability.backendId).cost ?? \"metered\",\n // Nor can it see the owner's spend consent. It offers; the daemon is\n // the enforcing side and releases with `refused` if its own rules say\n // no — the same shape as the `named` allowlist.\n spend: { acknowledged: true },\n // The server cannot see a remote daemon's local allowlist and must\n // not pretend to (protocol §4.2). It admits the job here; the daemon\n // is the enforcing side and releases with `refused` if its own list\n // says no.\n locallyAllows: () => true,\n },\n );\n return match.ok;\n }\n\n renewLeases(args: RenewArgs): Promise<RenewResult> {\n this.#expireDueSync(args.now);\n\n const renewed: { jobId: string; expiresAt: number }[] = [];\n const lost: string[] = [];\n\n for (const { jobId, leaseId } of args.leases) {\n const job = this.#jobs.get(jobId);\n if (\n !job ||\n job.lease?.runnerId !== args.runnerId ||\n job.lease.id !== leaseId\n ) {\n // Reclaimed by someone else, terminal, or a different grant than the\n // one being renewed — either way this runner must stop.\n lost.push(jobId);\n continue;\n }\n if (job.state !== \"claimed\" && job.state !== \"running\") {\n lost.push(jobId);\n continue;\n }\n const expiresAt = args.now + args.leaseMs;\n this.#write(jobId, {\n ...job,\n state: \"running\",\n // Renewal extends the existing grant; it does not mint a new one.\n lease: { ...job.lease, expiresAt },\n updatedAt: args.now,\n });\n renewed.push({ jobId, expiresAt });\n }\n return Promise.resolve({ renewed, lost });\n }\n\n adopt(args: AdoptArgs): Promise<JobRecord | null> {\n const job = this.#jobs.get(args.jobId);\n if (!job) return Promise.resolve(null);\n // Only a job that is genuinely available can be adopted. A terminal or\n // already-leased job means the relay and this store disagree about\n // reality, and the store's row is not the place to resolve that.\n if (job.state !== \"queued\" && job.state !== \"claimed\") {\n return Promise.resolve(null);\n }\n if (job.lease && job.lease.id !== args.leaseId) {\n return Promise.resolve(null);\n }\n const updated: JobRecord = {\n ...job,\n state: \"claimed\",\n lease: {\n id: args.leaseId,\n // No runner: this site never paired with the machine holding it.\n runnerId: \"\",\n expiresAt: args.expiresAt,\n },\n updatedAt: args.now,\n };\n this.#write(updated.id, updated);\n return Promise.resolve(updated);\n }\n\n complete(args: CompleteArgs): Promise<CompleteResult> {\n const job = this.#jobs.get(args.jobId);\n if (!job) return Promise.resolve({ accepted: false, job: null });\n\n // First terminal outcome wins; a later submission is discarded, not\n // applied ({@link MUSTS.RESULT_IDEMPOTENT}).\n if (\n job.state === \"ok\" ||\n job.state === \"error\" ||\n job.state === \"canceled\"\n ) {\n return Promise.resolve({ accepted: false, job });\n }\n if (job.state === \"expired\") {\n return Promise.resolve({ accepted: false, job });\n }\n // A runner that lost its lease may not write a result\n // ({@link MUSTS.LEASE_HONORED}). Named by lease id when the caller has\n // one — off the direct plane there is no runner this site knows.\n const holds =\n args.holder.by === \"runner\"\n ? job.lease?.runnerId === args.holder.runnerId\n : job.lease?.id === args.holder.leaseId;\n if (!holds) {\n return Promise.resolve({ accepted: false, job });\n }\n\n const state =\n args.outcome.outcome === \"ok\"\n ? \"ok\"\n : args.outcome.outcome === \"canceled\"\n ? \"canceled\"\n : \"error\";\n\n const updated: JobRecord = {\n ...job,\n state,\n lease: null,\n outcome: args.outcome,\n provenance: args.provenance,\n updatedAt: args.now,\n };\n this.#write(job.id, updated);\n this.#cancelRequests.delete(job.id);\n\n if (state === \"ok\") this.#unblockDependents(job.id, args.now);\n\n return Promise.resolve({ accepted: true, job: updated });\n }\n\n /**\n * Start the TTL clock on anything this job was blocking.\n *\n * Deliberately only on `ok`: a dependency that errored leaves its dependents\n * blocked forever rather than releasing them into a run whose input never\n * arrived. They expire at their absolute deadline if one was set, and the\n * app sees a chain that stopped where it broke.\n */\n #unblockDependents(completedId: string, now: number): void {\n for (const job of this.#jobs.values()) {\n if (job.claimableAt !== null) continue;\n if (!job.dependsOn.includes(completedId)) continue;\n const ready = job.dependsOn.every(\n (depId) => this.#jobs.get(depId)?.state === \"ok\",\n );\n if (ready) {\n this.#write(job.id, { ...job, claimableAt: now, updatedAt: now });\n }\n }\n }\n\n /**\n * Watchers, by job id (byollm_009 §8.3).\n *\n * A `Set` per job so an unsubscribe removes exactly the handler it\n * registered — two waiters on the same job are ordinary, and removing by\n * job id alone would silently cancel someone else's wait.\n */\n readonly #watchers = new Map<string, Set<() => void>>();\n\n subscribe(jobId: string, onChange: () => void): () => void {\n const existing = this.#watchers.get(jobId) ?? new Set<() => void>();\n existing.add(onChange);\n this.#watchers.set(jobId, existing);\n let live = true;\n return () => {\n // Idempotent: the contract says calling twice is safe, and a `finally`\n // that unsubscribes after an error path already did is the normal way\n // this gets called twice.\n if (!live) return;\n live = false;\n const set = this.#watchers.get(jobId);\n set?.delete(onChange);\n if (set?.size === 0) this.#watchers.delete(jobId);\n };\n }\n\n /**\n * The single write path for a job.\n *\n * Every mutation goes through here so notification cannot be forgotten by\n * a future one. Nine call sites existed when the push seam was added, and\n * \"remember to notify\" is not a property nine call sites keep.\n */\n #write(jobId: string, record: JobRecord): void {\n this.#jobs.set(jobId, record);\n this.#notify(jobId);\n }\n\n /**\n * Tell anyone watching that a job changed.\n *\n * A throwing watcher must not corrupt the store's own bookkeeping, so each\n * is isolated: this runs inside write paths, and one bad listener taking\n * out an unrelated write would be a far worse failure than a missed\n * notification.\n */\n #notify(jobId: string): void {\n for (const watcher of this.#watchers.get(jobId) ?? []) {\n try {\n watcher();\n } catch {\n // A watcher is a signal handler; the caller re-reads regardless.\n }\n }\n }\n\n release(args: ReleaseArgs): Promise<string[]> {\n const released: string[] = [];\n for (const { jobId, leaseId } of args.leases) {\n const job = this.#jobs.get(jobId);\n // The *grant*, not just its holder. Matching on runner id alone let a\n // replayed release from an earlier lease drop a later one, returning a\n // job to the queue while the daemon was still executing it.\n if (\n !job ||\n job.lease?.runnerId !== args.runnerId ||\n job.lease.id !== leaseId\n ) {\n continue;\n }\n\n this.#write(jobId, {\n ...job,\n state: \"queued\",\n lease: null,\n // Newly available again, so the TTL clock restarts here too.\n claimableAt: args.now,\n // A refusal is remembered, or the pair spins between claim and\n // release forever ({@link MUSTS.REFUSAL_NOT_REOFFERED}).\n refusedBy:\n args.reason === \"refused\"\n ? [...new Set([...job.refusedBy, args.runnerId])]\n : job.refusedBy,\n updatedAt: args.now,\n });\n released.push(jobId);\n }\n return Promise.resolve(released);\n }\n\n expireDue(now: number): Promise<JobRecord[]> {\n return Promise.resolve(this.#expireDueSync(now));\n }\n\n /**\n * Lease expiry and TTL expiry in one idempotent sweep.\n *\n * Order matters: a lease is reclaimed *before* the TTL is judged, so a job\n * whose runner died is offered again rather than being expired for having\n * sat in `claimed` too long.\n */\n #expireDueSync(now: number): JobRecord[] {\n const changed: JobRecord[] = [];\n\n for (const job of this.#jobs.values()) {\n if (\n (job.state === \"claimed\" || job.state === \"running\") &&\n job.lease !== null &&\n job.lease.expiresAt <= now\n ) {\n const requeued: JobRecord = {\n ...job,\n state: \"queued\",\n lease: null,\n // The TTL clock restarts: it measures how long a job has waited\n // *unclaimed*, and this job has just become available again. Without\n // this, a job whose runner died would expire for time it spent being\n // actively worked on — losing exactly the work `kill -9` recovery\n // exists to save. Total lifetime is bounded by `deadlineAt`, which\n // is absolute and unaffected by reclaim.\n claimableAt: now,\n updatedAt: now,\n };\n this.#write(job.id, requeued);\n changed.push(requeued);\n }\n }\n\n for (const job of this.#jobs.values()) {\n if (job.state !== \"queued\") continue;\n const pastDeadline = job.deadlineAt !== null && job.deadlineAt <= now;\n const pastTtl =\n job.claimableAt !== null && job.claimableAt + job.ttlMs <= now;\n if (!pastDeadline && !pastTtl) continue;\n\n const expired: JobRecord = {\n ...job,\n state: \"expired\",\n lease: null,\n updatedAt: now,\n };\n this.#write(job.id, expired);\n changed.push(expired);\n }\n return changed;\n }\n\n cancel(jobId: string, now: number): Promise<JobRecord | null> {\n const job = this.#jobs.get(jobId);\n if (!job) return Promise.resolve(null);\n if (job.state === \"queued\") {\n const canceled: JobRecord = {\n ...job,\n state: \"canceled\",\n lease: null,\n updatedAt: now,\n };\n this.#write(jobId, canceled);\n return Promise.resolve(canceled);\n }\n if (job.state === \"claimed\" || job.state === \"running\") {\n // Held by a runner: the cancel travels on the next heartbeat and the\n // runner reports `canceled` itself, so the job's own state waits.\n this.#cancelRequests.add(jobId);\n return Promise.resolve(job);\n }\n return Promise.resolve(job);\n }\n\n listClaimedBy(runnerId: string): Promise<JobRecord[]> {\n return Promise.resolve(\n [...this.#jobs.values()].filter(\n (job) => job.lease?.runnerId === runnerId,\n ),\n );\n }\n\n listCancelRequests(runnerId: string): Promise<string[]> {\n return Promise.resolve(\n [...this.#cancelRequests].filter(\n (jobId) => this.#jobs.get(jobId)?.lease?.runnerId === runnerId,\n ),\n );\n }\n\n // -- pairing and runners -------------------------------------------------\n\n createPairing(record: PairingRecord): Promise<void> {\n this.#pairings.set(record.deviceCodeHash, record);\n return Promise.resolve();\n }\n\n getPairingByDeviceCodeHash(hash: string): Promise<PairingRecord | null> {\n return Promise.resolve(this.#pairings.get(hash) ?? null);\n }\n\n getPairingByUserCode(userCode: string): Promise<PairingRecord | null> {\n for (const pairing of this.#pairings.values()) {\n if (pairing.userCode === userCode) return Promise.resolve(pairing);\n }\n return Promise.resolve(null);\n }\n\n approvePairing(args: ApproveArgs): Promise<RunnerRecord> {\n const pairing = [...this.#pairings.values()].find(\n (p) => p.userCode === args.userCode,\n );\n if (!pairing) throw new Error(`unknown pairing code: ${args.userCode}`);\n if (pairing.expiresAt <= args.now) {\n throw new Error(\"pairing code has expired\");\n }\n if (pairing.state !== \"pending\") {\n throw new Error(`pairing is already ${pairing.state}`);\n }\n\n const runner: RunnerRecord = {\n id: args.runnerId,\n owner: args.owner,\n tokenHash: args.tokenHash,\n // Carried from the pairing, not re-supplied at approval: the user\n // approved a specific machine, and the runner must be that machine.\n device: pairing.device,\n label: pairing.label,\n platform: pairing.platform,\n daemonVersion: pairing.daemonVersion,\n capabilities: pairing.capabilities,\n paused: false,\n revokedAt: null,\n lastHeartbeatAt: args.now,\n createdAt: args.now,\n };\n this.#runners.set(runner.id, runner);\n this.#pairings.set(pairing.deviceCodeHash, {\n ...pairing,\n state: \"approved\",\n owner: args.owner,\n runnerId: runner.id,\n runnerTokenOnce: args.runnerToken,\n });\n return Promise.resolve(runner);\n }\n\n denyPairing(userCode: string, _now: number): Promise<void> {\n const pairing = [...this.#pairings.values()].find(\n (p) => p.userCode === userCode,\n );\n if (pairing) {\n this.#pairings.set(pairing.deviceCodeHash, {\n ...pairing,\n state: \"denied\",\n });\n }\n return Promise.resolve();\n }\n\n consumePairingToken(deviceCodeHash: string): Promise<void> {\n const pairing = this.#pairings.get(deviceCodeHash);\n if (pairing) {\n this.#pairings.set(deviceCodeHash, {\n ...pairing,\n runnerTokenOnce: null,\n });\n }\n return Promise.resolve();\n }\n\n getRunnerByTokenHash(hash: string): Promise<RunnerRecord | null> {\n for (const runner of this.#runners.values()) {\n if (runner.tokenHash === hash) return Promise.resolve(runner);\n }\n return Promise.resolve(null);\n }\n\n getRunner(runnerId: string): Promise<RunnerRecord | null> {\n return Promise.resolve(this.#runners.get(runnerId) ?? null);\n }\n\n touchRunner(args: TouchArgs): Promise<RunnerRecord | null> {\n const runner = this.#runners.get(args.runnerId);\n if (!runner) return Promise.resolve(null);\n const updated: RunnerRecord = {\n ...runner,\n capabilities: args.capabilities,\n daemonVersion: args.daemonVersion,\n paused: args.paused,\n lastHeartbeatAt: args.now,\n };\n this.#runners.set(runner.id, updated);\n return Promise.resolve(updated);\n }\n\n revokeRunner(runnerId: string, now: number): Promise<void> {\n const runner = this.#runners.get(runnerId);\n // Revocation is one-way: an already-revoked runner keeps its first\n // revocation time rather than being re-stamped.\n if (runner?.revokedAt === null) {\n this.#runners.set(runnerId, { ...runner, revokedAt: now });\n }\n return Promise.resolve();\n }\n\n listRunners(owner?: string): Promise<RunnerRecord[]> {\n const all = [...this.#runners.values()];\n return Promise.resolve(\n owner === undefined ? all : all.filter((r) => r.owner === owner),\n );\n }\n\n // -- test/demo helpers ---------------------------------------------------\n\n /** All jobs, for demos and assertions. Not part of the store interface. */\n allJobs(): JobRecord[] {\n return [...this.#jobs.values()];\n }\n}\n\n/** The capability that would serve a kind, if any. */\nexport function capabilityFor(\n capabilities: readonly Capability[],\n kind: string,\n): Capability | undefined {\n return capabilities.find((c) => c.kind === kind);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA,SAAAA;AAAA,EACA;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OAGK;;;ACbP;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AAiEA,IAAM,YA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,SAAS,KAAK,SAAS,IAAI,QAAQ;AAGzC,QAAI,QAAQ,cAAc,MAAM;AAC9B,WAAK,SAAS,IAAI,UAAU,EAAE,GAAG,QAAQ,WAAW,IAAI,CAAC;AAAA,IAC3D;AACA,WAAO,QAAQ,QAAQ;AAAA,EACzB;AAAA,EAEA,YAAY,OAAyC;AACnD,UAAM,MAAM,CAAC,GAAG,KAAK,SAAS,OAAO,CAAC;AACtC,WAAO,QAAQ;AAAA,MACb,UAAU,SAAY,MAAM,IAAI,OAAO,CAAC,MAAM,EAAE,UAAU,KAAK;AAAA,IACjE;AAAA,EACF;AAAA;AAAA;AAAA,EAKA,UAAuB;AACrB,WAAO,CAAC,GAAG,KAAK,MAAM,OAAO,CAAC;AAAA,EAChC;AACF;AAGO,SAAS,cACd,cACA,MACwB;AACxB,SAAO,aAAa,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI;AACjD;","names":["keyId","publicIdentityOf","keyId","publicIdentityOf","publicIdentityOf","backendDescriptor","matchAudience","matchAudience","backendDescriptor"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@byollm/server",
3
- "version": "0.1.0-alpha.7",
3
+ "version": "0.1.0-alpha.9",
4
4
  "description": "Framework-agnostic BYOLLM protocol handlers, a reference in-memory store, a Next.js mount, and a Supabase adapter.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -30,7 +30,7 @@
30
30
  "node": ">=22.14"
31
31
  },
32
32
  "dependencies": {
33
- "@byollm/protocol": "0.1.0-alpha.7"
33
+ "@byollm/protocol": "0.1.0-alpha.9"
34
34
  },
35
35
  "peerDependencies": {
36
36
  "@supabase/supabase-js": "^2.58.0"