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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,17 +1,18 @@
1
1
  import {
2
2
  ByollmHandlers,
3
3
  SERVED_PROTOCOL_VERSION,
4
- bearerFrom,
5
4
  createFetchHandler,
6
5
  generateDeviceCode,
7
6
  generateJobId,
7
+ generateLeaseId,
8
8
  generateRunnerId,
9
9
  generateRunnerToken,
10
10
  generateUserCode,
11
11
  hashSecret,
12
12
  routeEndpoint,
13
- secretsMatch
14
- } from "./chunk-HL6EYHQ7.js";
13
+ secretsMatch,
14
+ signatureFrom
15
+ } from "./chunk-MGJX6626.js";
15
16
  import {
16
17
  NoRunnerAvailableError,
17
18
  PollingDelivery,
@@ -20,17 +21,26 @@ import {
20
21
 
21
22
  // src/app.ts
22
23
  import {
24
+ ENVELOPE_MAX_AGE_MS,
25
+ KindedPayload,
26
+ keyId,
27
+ payloadTextLength,
28
+ publicIdentityOf,
29
+ seal,
30
+ sizeClassOf,
23
31
  backendDescriptor,
24
32
  matchAudience
25
33
  } from "@byollm/protocol";
26
34
  var DEFAULT_LIVENESS_MS = 35e3;
27
35
  var ByollmApp = class {
28
36
  #store;
37
+ #siteKeys;
29
38
  #now;
30
39
  #livenessMs;
31
40
  #delivery;
32
41
  constructor(options) {
33
42
  this.#store = options.store;
43
+ this.#siteKeys = options.siteKeys;
34
44
  this.#now = options.now ?? Date.now;
35
45
  this.#livenessMs = options.livenessMs ?? DEFAULT_LIVENESS_MS;
36
46
  const deps = {
@@ -66,7 +76,44 @@ var ByollmApp = class {
66
76
  * the app is obliged to disclose that to whoever reads it.
67
77
  */
68
78
  async enqueue(input) {
69
- const record = await this.#store.create(input, this.#now());
79
+ const parsed = KindedPayload.safeParse({
80
+ kind: input.kind,
81
+ payload: input.payload
82
+ });
83
+ if (!parsed.success) {
84
+ const detail = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ");
85
+ throw new Error(`invalid ${input.kind} payload \u2014 ${detail}`);
86
+ }
87
+ const createdAt = this.#now();
88
+ const envelopeDeadlineAt = createdAt + ENVELOPE_MAX_AGE_MS;
89
+ const jobId = input.id ?? generateJobId();
90
+ const senderKeyId = keyId(publicIdentityOf(this.#siteKeys).identity);
91
+ const envelope = await seal({
92
+ plaintext: JSON.stringify(parsed.data.payload),
93
+ senderKeys: this.#siteKeys,
94
+ recipientEncryptionPublic: this.#siteKeys.encryptionPublic,
95
+ context: {
96
+ jobId,
97
+ senderKeyId,
98
+ recipientKeyId: senderKeyId,
99
+ deadlineAt: envelopeDeadlineAt,
100
+ direction: "payload"
101
+ }
102
+ });
103
+ const record = await this.#store.create(
104
+ {
105
+ ...input,
106
+ id: jobId,
107
+ envelope,
108
+ sizeClass: sizeClassOf(
109
+ payloadTextLength({
110
+ kind: input.kind,
111
+ payload: parsed.data.payload
112
+ })
113
+ )
114
+ },
115
+ createdAt
116
+ );
70
117
  return {
71
118
  id: record.id,
72
119
  record,
@@ -136,7 +183,18 @@ var ByollmApp = class {
136
183
  {
137
184
  owner: runner.owner,
138
185
  offerScope: capability.offerScope,
139
- account: backendDescriptor(capability.backendId).account,
186
+ // A generic backend's cost depends on its base URL, which the
187
+ // server never sees; assume the expensive reading (byollm_007 §4).
188
+ cost: backendDescriptor(capability.backendId).cost ?? "metered",
189
+ // Consent is the daemon's to hold, and it has already applied it:
190
+ // the offer scope arriving here is the *effective* one, so a
191
+ // metered backend nobody agreed to share advertises `self` and is
192
+ // refused by the scope rule above. Re-deriving consent from
193
+ // `false` here would instead refuse every backend an owner
194
+ // deliberately shared, because the server has no way to learn they
195
+ // did — the signal would be wrong in the direction that breaks
196
+ // working setups.
197
+ spend: { acknowledged: true },
140
198
  // Same conservative assumption the claim path makes: the server
141
199
  // cannot see a remote daemon's local allowlist (protocol §4.2).
142
200
  locallyAllows: () => true
@@ -218,6 +276,45 @@ function normalizeUserCode(input) {
218
276
  return bare.length === 8 ? `${bare.slice(0, 4)}-${bare.slice(4)}` : bare;
219
277
  }
220
278
 
279
+ // src/keys.ts
280
+ import { StoredKeys, generateKeys, publicIdentityOf as publicIdentityOf2 } from "@byollm/protocol";
281
+ import { fingerprint } from "@byollm/protocol";
282
+ var generateSiteKeys = (now = Date.now()) => generateKeys(now);
283
+ function siteKeysFromEnv(variable = "BYOLLM_SITE_KEYS", env = process.env) {
284
+ const raw = env[variable];
285
+ if (raw === void 0 || raw === "") {
286
+ throw new Error(
287
+ `${variable} is not set. Generate a site identity once with \`npx @byollm/server keygen\` and set it as ${variable}. Do not generate keys at startup: every instance would get a different identity and daemons would pin one and be refused by another.`
288
+ );
289
+ }
290
+ let parsed;
291
+ try {
292
+ parsed = JSON.parse(Buffer.from(raw, "base64").toString("utf8"));
293
+ } catch {
294
+ throw new Error(
295
+ `${variable} is not base64-encoded JSON. It should be exactly what \`npx @byollm/server keygen\` printed.`
296
+ );
297
+ }
298
+ const result = StoredKeys.safeParse(parsed);
299
+ if (!result.success) {
300
+ throw new Error(
301
+ `${variable} does not contain a valid site identity. Regenerate it with \`npx @byollm/server keygen\` \u2014 and if this site has already paired daemons, they will need to pair again.`
302
+ );
303
+ }
304
+ return result.data;
305
+ }
306
+ function formatSiteKeys(keys) {
307
+ const encoded = Buffer.from(JSON.stringify(keys)).toString("base64");
308
+ return `# Set this as BYOLLM_SITE_KEYS. It is a secret: it is this site's
309
+ # identity, and anything holding it can be this site.
310
+ BYOLLM_SITE_KEYS=${encoded}
311
+
312
+ # Fingerprint (not secret \u2014 show it to users so they can check what
313
+ # their daemon pinned):
314
+ # ${fingerprint(publicIdentityOf2(keys).identity)}
315
+ `;
316
+ }
317
+
221
318
  // src/memory.ts
222
319
  import {
223
320
  backendDescriptor as backendDescriptor2,
@@ -236,7 +333,7 @@ var MemoryStore = class {
236
333
  }
237
334
  // -- jobs ---------------------------------------------------------------
238
335
  create(input, now) {
239
- const id = input.id ?? generateJobId();
336
+ const id = input.id;
240
337
  const existing = this.#jobs.get(id);
241
338
  if (existing) return Promise.resolve(existing);
242
339
  const dependsOn = [...input.dependsOn ?? []];
@@ -246,7 +343,8 @@ var MemoryStore = class {
246
343
  const job = {
247
344
  id,
248
345
  kind: input.kind,
249
- payload: input.payload,
346
+ envelope: input.envelope,
347
+ sizeClass: input.sizeClass,
250
348
  audience: input.audience ?? "self",
251
349
  owner: input.owner,
252
350
  audienceAllow: input.audienceAllow ? [...input.audienceAllow] : void 0,
@@ -264,7 +362,7 @@ var MemoryStore = class {
264
362
  provenance: null,
265
363
  updatedAt: now
266
364
  };
267
- this.#jobs.set(id, job);
365
+ this.#write(id, job);
268
366
  return Promise.resolve(job);
269
367
  }
270
368
  get(jobId) {
@@ -283,13 +381,16 @@ var MemoryStore = class {
283
381
  ...job,
284
382
  state: "claimed",
285
383
  lease: {
384
+ // A fresh id per grant. Two claims of the same job by the same
385
+ // runner are two different leases, and must be distinguishable.
386
+ id: generateLeaseId(),
286
387
  runnerId: args.runnerId,
287
388
  expiresAt: args.now + args.leaseMs
288
389
  },
289
390
  attempts: job.attempts + 1,
290
391
  updatedAt: args.now
291
392
  };
292
- this.#jobs.set(job.id, updated);
393
+ this.#write(job.id, updated);
293
394
  claimed.push(updated);
294
395
  }
295
396
  return Promise.resolve(claimed);
@@ -313,9 +414,16 @@ var MemoryStore = class {
313
414
  {
314
415
  owner: args.runnerOwner,
315
416
  offerScope: capability.offerScope,
316
- // From the registry, not a local guess — the subscription self-lock
317
- // must mean the same thing on both sides of the wire.
318
- account: backendDescriptor2(capability.backendId).account,
417
+ // From the registry, not a local guess — the cost rules must mean the
418
+ // same thing on both sides of the wire. The server cannot see a
419
+ // remote daemon's base URL, so a generic backend with no declared
420
+ // cost is treated as metered: the expensive side, and the daemon
421
+ // refuses anyway if it disagrees (byollm_007 §2).
422
+ cost: backendDescriptor2(capability.backendId).cost ?? "metered",
423
+ // Nor can it see the owner's spend consent. It offers; the daemon is
424
+ // the enforcing side and releases with `refused` if its own rules say
425
+ // no — the same shape as the `named` allowlist.
426
+ spend: { acknowledged: true },
319
427
  // The server cannot see a remote daemon's local allowlist and must
320
428
  // not pretend to (protocol §4.2). It admits the job here; the daemon
321
429
  // is the enforcing side and releases with `refused` if its own list
@@ -329,9 +437,9 @@ var MemoryStore = class {
329
437
  this.#expireDueSync(args.now);
330
438
  const renewed = [];
331
439
  const lost = [];
332
- for (const jobId of args.jobIds) {
440
+ for (const { jobId, leaseId } of args.leases) {
333
441
  const job = this.#jobs.get(jobId);
334
- if (!job || job.lease?.runnerId !== args.runnerId) {
442
+ if (!job || job.lease?.runnerId !== args.runnerId || job.lease.id !== leaseId) {
335
443
  lost.push(jobId);
336
444
  continue;
337
445
  }
@@ -340,10 +448,11 @@ var MemoryStore = class {
340
448
  continue;
341
449
  }
342
450
  const expiresAt = args.now + args.leaseMs;
343
- this.#jobs.set(jobId, {
451
+ this.#write(jobId, {
344
452
  ...job,
345
453
  state: "running",
346
- lease: { runnerId: args.runnerId, expiresAt },
454
+ // Renewal extends the existing grant; it does not mint a new one.
455
+ lease: { ...job.lease, expiresAt },
347
456
  updatedAt: args.now
348
457
  });
349
458
  renewed.push({ jobId, expiresAt });
@@ -371,7 +480,7 @@ var MemoryStore = class {
371
480
  provenance: args.provenance,
372
481
  updatedAt: args.now
373
482
  };
374
- this.#jobs.set(job.id, updated);
483
+ this.#write(job.id, updated);
375
484
  this.#cancelRequests.delete(job.id);
376
485
  if (state === "ok") this.#unblockDependents(job.id, args.now);
377
486
  return Promise.resolve({ accepted: true, job: updated });
@@ -392,16 +501,66 @@ var MemoryStore = class {
392
501
  (depId) => this.#jobs.get(depId)?.state === "ok"
393
502
  );
394
503
  if (ready) {
395
- this.#jobs.set(job.id, { ...job, claimableAt: now, updatedAt: now });
504
+ this.#write(job.id, { ...job, claimableAt: now, updatedAt: now });
505
+ }
506
+ }
507
+ }
508
+ /**
509
+ * Watchers, by job id (byollm_009 §8.3).
510
+ *
511
+ * A `Set` per job so an unsubscribe removes exactly the handler it
512
+ * registered — two waiters on the same job are ordinary, and removing by
513
+ * job id alone would silently cancel someone else's wait.
514
+ */
515
+ #watchers = /* @__PURE__ */ new Map();
516
+ subscribe(jobId, onChange) {
517
+ const existing = this.#watchers.get(jobId) ?? /* @__PURE__ */ new Set();
518
+ existing.add(onChange);
519
+ this.#watchers.set(jobId, existing);
520
+ let live = true;
521
+ return () => {
522
+ if (!live) return;
523
+ live = false;
524
+ const set = this.#watchers.get(jobId);
525
+ set?.delete(onChange);
526
+ if (set?.size === 0) this.#watchers.delete(jobId);
527
+ };
528
+ }
529
+ /**
530
+ * The single write path for a job.
531
+ *
532
+ * Every mutation goes through here so notification cannot be forgotten by
533
+ * a future one. Nine call sites existed when the push seam was added, and
534
+ * "remember to notify" is not a property nine call sites keep.
535
+ */
536
+ #write(jobId, record) {
537
+ this.#jobs.set(jobId, record);
538
+ this.#notify(jobId);
539
+ }
540
+ /**
541
+ * Tell anyone watching that a job changed.
542
+ *
543
+ * A throwing watcher must not corrupt the store's own bookkeeping, so each
544
+ * is isolated: this runs inside write paths, and one bad listener taking
545
+ * out an unrelated write would be a far worse failure than a missed
546
+ * notification.
547
+ */
548
+ #notify(jobId) {
549
+ for (const watcher of this.#watchers.get(jobId) ?? []) {
550
+ try {
551
+ watcher();
552
+ } catch {
396
553
  }
397
554
  }
398
555
  }
399
556
  release(args) {
400
557
  const released = [];
401
- for (const jobId of args.jobIds) {
558
+ for (const { jobId, leaseId } of args.leases) {
402
559
  const job = this.#jobs.get(jobId);
403
- if (!job || job.lease?.runnerId !== args.runnerId) continue;
404
- this.#jobs.set(jobId, {
560
+ if (!job || job.lease?.runnerId !== args.runnerId || job.lease.id !== leaseId) {
561
+ continue;
562
+ }
563
+ this.#write(jobId, {
405
564
  ...job,
406
565
  state: "queued",
407
566
  lease: null,
@@ -443,7 +602,7 @@ var MemoryStore = class {
443
602
  claimableAt: now,
444
603
  updatedAt: now
445
604
  };
446
- this.#jobs.set(job.id, requeued);
605
+ this.#write(job.id, requeued);
447
606
  changed.push(requeued);
448
607
  }
449
608
  }
@@ -458,7 +617,7 @@ var MemoryStore = class {
458
617
  lease: null,
459
618
  updatedAt: now
460
619
  };
461
- this.#jobs.set(job.id, expired);
620
+ this.#write(job.id, expired);
462
621
  changed.push(expired);
463
622
  }
464
623
  return changed;
@@ -473,7 +632,7 @@ var MemoryStore = class {
473
632
  lease: null,
474
633
  updatedAt: now
475
634
  };
476
- this.#jobs.set(jobId, canceled);
635
+ this.#write(jobId, canceled);
477
636
  return Promise.resolve(canceled);
478
637
  }
479
638
  if (job.state === "claimed" || job.state === "running") {
@@ -525,6 +684,9 @@ var MemoryStore = class {
525
684
  id: args.runnerId,
526
685
  owner: args.owner,
527
686
  tokenHash: args.tokenHash,
687
+ // Carried from the pairing, not re-supplied at approval: the user
688
+ // approved a specific machine, and the runner must be that machine.
689
+ device: pairing.device,
528
690
  label: pairing.label,
529
691
  platform: pairing.platform,
530
692
  daemonVersion: pairing.daemonVersion,
@@ -618,17 +780,20 @@ export {
618
780
  PollingDelivery,
619
781
  ResultTimeoutError,
620
782
  SERVED_PROTOCOL_VERSION,
621
- bearerFrom,
622
783
  capabilityFor,
623
784
  createFetchHandler,
785
+ formatSiteKeys,
624
786
  generateDeviceCode,
625
787
  generateJobId,
626
788
  generateRunnerId,
627
789
  generateRunnerToken,
790
+ generateSiteKeys,
628
791
  generateUserCode,
629
792
  hashSecret,
630
793
  normalizeUserCode,
631
794
  routeEndpoint,
632
- secretsMatch
795
+ secretsMatch,
796
+ signatureFrom,
797
+ siteKeysFromEnv
633
798
  };
634
799
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/app.ts","../src/memory.ts"],"sourcesContent":["import {\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 { generateRunnerId, generateRunnerToken, hashSecret } from \"./ids.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\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 #now: () => number;\n readonly #livenessMs: number;\n readonly #delivery: ResultDelivery;\n\n constructor(options: ByollmAppOptions) {\n this.#store = options.store;\n this.#now = options.now ?? Date.now;\n this.#livenessMs = options.livenessMs ?? DEFAULT_LIVENESS_MS;\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 const record = await this.#store.create(input, this.#now());\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 account: backendDescriptor(capability.backendId).account,\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 backendDescriptor,\n matchAudience,\n type Capability,\n} from \"@byollm/protocol\";\nimport { generateJobId } from \"./ids.js\";\nimport type {\n EnqueueInput,\n JobRecord,\n PairingRecord,\n RunnerRecord,\n} from \"./records.js\";\nimport type {\n ApproveArgs,\n ByollmStore,\n ClaimArgs,\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: EnqueueInput, now: number): Promise<JobRecord> {\n const id = input.id ?? generateJobId();\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 payload: input.payload,\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.#jobs.set(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 runnerId: args.runnerId,\n expiresAt: args.now + args.leaseMs,\n },\n attempts: job.attempts + 1,\n updatedAt: args.now,\n };\n this.#jobs.set(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 subscription self-lock\n // must mean the same thing on both sides of the wire.\n account: backendDescriptor(capability.backendId).account,\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 of args.jobIds) {\n const job = this.#jobs.get(jobId);\n if (!job || job.lease?.runnerId !== args.runnerId) {\n // Either reclaimed by someone else or terminal — either way this\n // runner must stop working on it.\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.#jobs.set(jobId, {\n ...job,\n state: \"running\",\n lease: { runnerId: args.runnerId, expiresAt },\n updatedAt: args.now,\n });\n renewed.push({ jobId, expiresAt });\n }\n return Promise.resolve({ renewed, lost });\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}).\n if (job.lease?.runnerId !== args.runnerId) {\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.#jobs.set(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.#jobs.set(job.id, { ...job, claimableAt: now, updatedAt: now });\n }\n }\n }\n\n release(args: ReleaseArgs): Promise<string[]> {\n const released: string[] = [];\n for (const jobId of args.jobIds) {\n const job = this.#jobs.get(jobId);\n if (!job || job.lease?.runnerId !== args.runnerId) continue;\n\n this.#jobs.set(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.#jobs.set(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.#jobs.set(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.#jobs.set(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 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;A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matchAudience","backendDescriptor"]}
1
+ {"version":3,"sources":["../src/app.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 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\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\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\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 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 { 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 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 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}).\n if (job.lease?.runnerId !== args.runnerId) {\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;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,OAGK;AAoBP,IAAM,sBAAsB;AAmFrB,IAAM,YAAN,MAAgB;AAAA,EACZ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,SAA2B;AACrC,SAAK,SAAS,QAAQ;AACtB,SAAK,YAAY,QAAQ;AACzB,SAAK,OAAO,QAAQ,OAAO,KAAK;AAChC,SAAK,cAAc,QAAQ,cAAc;AAEzC,UAAM,OAA4B;AAAA,MAChC,GAAI,QAAQ,oBAAoB,SAC5B,CAAC,IACD,EAAE,SAAS,QAAQ,gBAAgB;AAAA,MACvC,MAAM,CAAC,UAAU,KAAK,OAAO,KAAK;AAAA,MAClC,cAAc,OAAO,UAAU;AAC7B,cAAM,MAAM,MAAM,KAAK,OAAO,IAAI,KAAK;AACvC,YAAI,CAAC;AACH,iBAAO,EAAE,WAAW,OAAO,QAAQ,eAAe,SAAS,MAAM;AAEnE,YAAI,IAAI,gBAAgB,MAAM;AAC5B,iBAAO,EAAE,WAAW,MAAM,SAAS,KAAK;AAAA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