@byollm/relay 0.1.4 → 0.1.5-beta.2

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
  <!-- release-note 0.1.1 -->
2
- > **`0.1.4` is documentation only — nothing to upgrade.** `PROTOCOL_VERSION`
2
+ > **`0.1.5-beta.2` is documentation only — nothing to upgrade.** `PROTOCOL_VERSION`
3
3
  > is still `2`, so a 0.1.0 party and a 0.1.1 party talk to each other in both
4
4
  > directions. No dependency, schema, wire field or on-disk shape moved.
5
5
  >
@@ -96,6 +96,57 @@ for every site its projection holds, and refuses a caller that names a site the
96
96
  projection does not (cloud_009 §3). Job state is keyed by the pair, so two sites
97
97
  may use the same job id without either seeing the other.
98
98
 
99
+ ## Images: give it a blob store
100
+
101
+ `llm.vision` and `llm.image` carry images by reference (byollm_021 §2). The
102
+ bytes are encrypted blobs in object storage, uploaded and downloaded straight
103
+ to it through short-lived URLs this relay issues. They never pass through this
104
+ process, and it holds no key that opens one.
105
+
106
+ A relay carries images only when its host gives it somewhere to keep them:
107
+
108
+ ```ts
109
+ import { MemoryBlobStore, Relay } from "@byollm/relay";
110
+
111
+ const relay = new Relay({
112
+ fixture,
113
+ blobs: { store: new MemoryBlobStore({ origin: "http://127.0.0.1:8787" }) },
114
+ });
115
+ ```
116
+
117
+ `MemoryBlobStore` is for the reference relay and tests. A deployment
118
+ implements `BlobStore` over its own bucket: a signed upload, a signed
119
+ download, an object's stored size, a job's objects by name, every object with
120
+ the time it was stored, and a delete. With
121
+ more than one replica it also supplies a shared `BlobLedger`, for the reason
122
+ it supplies a shared `RoutingStore`.
123
+
124
+ **Without `blobs`, this relay carries no images.** Its blob routes answer 404
125
+ and it refuses `llm.vision` and `llm.image` at enqueue, so no device is paid
126
+ to make an image it then cannot hand back.
127
+
128
+ What the package decides, whatever the store:
129
+
130
+ - **No lease, no URL.** A device gets a download URL or an upload slot only
131
+ for a job it holds right now, under the lease it names.
132
+ - **The job is in the object name**, `blobs/<site>/<job>/<in|out>/<blob>`
133
+ (`blobObjectName`). A caller names a blob id and nothing else; the site and
134
+ the job come from what the relay already verified. The uploader sends
135
+ ciphertext and its length, with no header to copy.
136
+ - **Sizes are read, not trusted.** A slot's size is in the blob id the relay
137
+ mints. A job is queued only if every input it was issued a slot for is
138
+ stored at that size, and an `ok` result is accepted only if its outputs
139
+ are.
140
+ - **Blobs go with the job.** Inputs when the result is accepted; outputs when
141
+ the site says it holds them, or an hour after it collected the result; and
142
+ whatever is left a day after the job's deadline. `Relay.sweep()` runs the
143
+ last two. Set a lifecycle rule on the bucket as the floor under it.
144
+ - **A lost ledger delays deletion; it does not stop it.** `Relay.sweep()` also
145
+ lists the whole store and deletes any object no ledger record covers once it
146
+ is 48 hours old (`ORPHAN_BLOB_AGE_MS`). The two earlier deletions, at the
147
+ result and an hour after collection, need the record: keep the ledger
148
+ somewhere that survives a restart if you want them kept across one.
149
+
99
150
  ## Breaking before `0.1.0`: `RelayState` is async
100
151
 
101
152
  Every method on `RelayState` now returns a `Promise`, and `Relay.sweep()` and
@@ -1,9 +1,21 @@
1
1
  // src/state.ts
2
+ import {
3
+ TOOL_LIMITS
4
+ } from "@byollm/protocol";
2
5
  import { randomUUID } from "crypto";
3
6
  var AWAITING_PAYLOAD_MS = 1e4;
4
7
  var UNSEALED_PER_PAIR = 2;
5
8
  var SEAL_ATTEMPTS_BEFORE_EVICTION = 3;
6
9
  var RETRY_AFTER_MS = 3e4;
10
+ function subStateOf(job, now) {
11
+ if (job.state !== "running") return void 0;
12
+ const lease = job.claimedBy?.leaseId;
13
+ const waiting = (job.toolCalls ?? []).some(
14
+ (call) => call.leaseId === lease && call.result === void 0 && call.expiresAt > now
15
+ );
16
+ return waiting ? "waiting-on-site" : void 0;
17
+ }
18
+ var sameEnvelope = (a, b) => JSON.stringify(a) === JSON.stringify(b);
7
19
  var routeKey = (siteId, owner) => `${siteId}\0${owner}`;
8
20
  var CHURN_EXPIRIES = 6;
9
21
  var CHURN_WINDOW_MS = 5 * 6e4;
@@ -170,7 +182,8 @@ var RelayState = class {
170
182
  siteId: input.siteId,
171
183
  stub: input.stub,
172
184
  state: "queued",
173
- refusedBy: []
185
+ refusedBy: [],
186
+ ...input.maxToolCalls === void 0 ? {} : { maxToolCalls: input.maxToolCalls }
174
187
  };
175
188
  this.#jobs.set(keyOf(job.siteId, job.id), job);
176
189
  this.#index(job);
@@ -303,6 +316,7 @@ var RelayState = class {
303
316
  job.result = input.envelope;
304
317
  job.disposition = input.disposition;
305
318
  job.state = "done";
319
+ delete job.toolCalls;
306
320
  return Promise.resolve({ accepted: true, state: job.state });
307
321
  }
308
322
  /** Give back leases this runner holds, naming each grant it means. */
@@ -383,6 +397,134 @@ var RelayState = class {
383
397
  }
384
398
  return { renewed, lost };
385
399
  }
400
+ /**
401
+ * {@link RoutingStore.recordToolCall} — one sealed call, counted and kept.
402
+ *
403
+ * The holder checks are `takePayload`'s, in the same order, because a
404
+ * tool call is the same claim ("this grant, held by me") made mid-job.
405
+ * Then the two only this endpoint has: the job must be `llm.tools`, and
406
+ * the call must fit the budget. Counted **before** it is written, so the
407
+ * call that would exceed the budget is the one refused (`TOOLS_BUDGETED`).
408
+ */
409
+ async recordToolCall(input) {
410
+ const now = await this.now();
411
+ const job = this.#grantFor(input.jobId, input.runnerId, input.leaseId);
412
+ if (!job) return { refused: "not-found" };
413
+ if (job.claimedBy?.runnerId !== input.runnerId) {
414
+ return { refused: "not-holder" };
415
+ }
416
+ if (job.state === "done" || job.cancelled === true) {
417
+ return { refused: "terminal" };
418
+ }
419
+ if (job.claimedBy.leaseId !== input.leaseId) {
420
+ return { refused: "stale-lease" };
421
+ }
422
+ if (job.state !== "running") return { refused: "not-ready" };
423
+ if (job.stub.kind !== "llm.tools") return { refused: "not-tools" };
424
+ const calls = job.toolCalls ?? [];
425
+ const known = calls.find((call) => call.callId === input.callId);
426
+ if (known) {
427
+ return sameEnvelope(known.envelope, input.envelope) ? { callId: known.callId, expiresAt: known.expiresAt, duplicate: true } : { refused: "call-conflict" };
428
+ }
429
+ const limit = job.maxToolCalls ?? TOOL_LIMITS.maxToolCalls;
430
+ if ((job.toolCallsMade ?? 0) >= limit) return { refused: "budget" };
431
+ const row = {
432
+ callId: input.callId,
433
+ leaseId: input.leaseId,
434
+ envelope: input.envelope,
435
+ expiresAt: now + TOOL_LIMITS.callTimeoutMs
436
+ };
437
+ job.toolCalls = [...calls, row];
438
+ job.toolCallsMade = (job.toolCallsMade ?? 0) + 1;
439
+ return { callId: row.callId, expiresAt: row.expiresAt };
440
+ }
441
+ /**
442
+ * {@link RoutingStore.toolCalls} — what is waiting on this site.
443
+ *
444
+ * Outstanding only: the current grant's, unanswered, inside the timeout.
445
+ * A call that timed out is gone from here because the daemon has already
446
+ * told the model the site did not answer, and running the tool now would
447
+ * spend the site's tools on an answer nobody will read.
448
+ */
449
+ async toolCalls(siteId) {
450
+ const now = await this.now();
451
+ const out = [];
452
+ for (const job of this.#jobs.values()) {
453
+ if (job.siteId !== siteId || job.state !== "running") continue;
454
+ const held = job.claimedBy;
455
+ if (!held || job.cancelled === true) continue;
456
+ for (const call of job.toolCalls ?? []) {
457
+ if (call.leaseId !== held.leaseId) continue;
458
+ if (call.result !== void 0 || call.expiresAt <= now) continue;
459
+ out.push({
460
+ jobId: job.id,
461
+ leaseId: call.leaseId,
462
+ callId: call.callId,
463
+ envelope: call.envelope,
464
+ device: held.device,
465
+ expiresAt: call.expiresAt
466
+ });
467
+ }
468
+ }
469
+ return out;
470
+ }
471
+ /**
472
+ * {@link RoutingStore.answerToolCall} — a site's sealed answer, bound to
473
+ * its call (`TOOL_ENVELOPES_BOUND`, the relay's half).
474
+ *
475
+ * Found by **(site, job, call)**, so a result posted for job A can only
476
+ * ever land on a call of job A: another job's call id is not found here,
477
+ * and so is a call of A's that belonged to a grant that has ended. The
478
+ * daemon holds the other half — it opens the envelope and checks the job
479
+ * and the call inside the signature.
480
+ */
481
+ async answerToolCall(input) {
482
+ const now = await this.now();
483
+ const job = this.#jobs.get(keyOf(input.siteId, input.jobId));
484
+ if (job?.siteId !== input.siteId) return { refused: "not-found" };
485
+ const lease = job.claimedBy?.leaseId;
486
+ const call = (job.toolCalls ?? []).find(
487
+ (row) => row.callId === input.callId && row.leaseId === lease
488
+ );
489
+ if (!call) return { refused: "not-found" };
490
+ if (call.result !== void 0) {
491
+ return sameEnvelope(call.result, input.envelope) ? { accepted: true } : { refused: "too-late" };
492
+ }
493
+ if (call.expiresAt <= now || job.state !== "running") {
494
+ return { refused: "too-late" };
495
+ }
496
+ call.result = input.envelope;
497
+ return { accepted: true };
498
+ }
499
+ /**
500
+ * {@link RoutingStore.toolResults} — answers, to the holder that asked.
501
+ *
502
+ * Each named call is looked up through the caller's grant, exactly as
503
+ * `takePayload` looks up a job: the lease must be current and held by this
504
+ * runner, and the call must have been made under it. Anything else is
505
+ * absent rather than refused, so a poll tells a stranger nothing.
506
+ */
507
+ toolResults(input) {
508
+ const out = [];
509
+ for (const ref of input.calls) {
510
+ const job = this.#grantFor(ref.jobId, input.runnerId, ref.leaseId);
511
+ const held = job?.claimedBy;
512
+ if (!job || held?.runnerId !== input.runnerId || held.leaseId !== ref.leaseId) {
513
+ continue;
514
+ }
515
+ const call = (job.toolCalls ?? []).find(
516
+ (row) => row.callId === ref.callId && row.leaseId === ref.leaseId
517
+ );
518
+ if (call?.result === void 0) continue;
519
+ out.push({
520
+ jobId: job.id,
521
+ leaseId: call.leaseId,
522
+ callId: call.callId,
523
+ envelope: call.result
524
+ });
525
+ }
526
+ return Promise.resolve(out);
527
+ }
386
528
  async seen(presence) {
387
529
  const lastSeenAt = await this.now();
388
530
  const existing = this.#presence.get(presence.runnerId);
@@ -428,6 +570,7 @@ var RelayState = class {
428
570
  delete job.claimedBy;
429
571
  delete job.awaitingUntil;
430
572
  delete job.payload;
573
+ delete job.toolCalls;
431
574
  }
432
575
  /**
433
576
  * Fire whatever the clock says is due, and report it.
@@ -475,10 +618,11 @@ export {
475
618
  UNSEALED_PER_PAIR,
476
619
  SEAL_ATTEMPTS_BEFORE_EVICTION,
477
620
  RETRY_AFTER_MS,
621
+ subStateOf,
478
622
  routeKey,
479
623
  CHURN_EXPIRIES,
480
624
  CHURN_WINDOW_MS,
481
625
  CHURN_QUIET_MS,
482
626
  RelayState
483
627
  };
484
- //# sourceMappingURL=chunk-4ISUXCIO.js.map
628
+ //# sourceMappingURL=chunk-YRJDRZ6G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/state.ts"],"sourcesContent":["import {\n TOOL_LIMITS,\n type CapabilityMatrix,\n type ClaimedStub,\n type JobStub,\n type PublicIdentity,\n type SealedEnvelope,\n type WithheldKind,\n} from \"@byollm/protocol\";\nimport { randomUUID } from \"node:crypto\";\nimport type { Grant, RoutingStore } from \"./store.js\";\n\n/**\n * The relay's routing state — byollm_009 §7, reachable at last.\n *\n * §7 described a state machine the direct plane could not produce. There, the\n * site and the upstream are the same party: it seals when it likes, and a job\n * is never claimed-but-unsealed. Here they are different parties, and the gap\n * between them is a state:\n *\n * ```\n * queued ──claim──▶ awaiting-payload ──sealed──▶ ready ──fetch──▶ running\n * ▲ │ │\n * └────────────────────┘ ▼\n * site never seals, or seals too late ok | error | canceled\n * ```\n *\n * The relay cannot seal, so it cannot shortcut this. A payload is encrypted\n * to *the device that claimed it*, and nobody knows which device that is until\n * the claim happens — which is precisely why claim-then-fetch makes a blind\n * relay possible at all. The window is the price.\n *\n * ## What the relay holds, and what it cannot\n *\n * Stubs (metadata the site chose to publish), sealed envelopes it cannot open,\n * and public keys. There is no field on any type in this file that could hold\n * a private key or a plaintext, which is `RELAY_BLIND` expressed as a data\n * model rather than as a policy.\n */\n\n/** Where a routed job is. */\nexport type RoutedState =\n \"queued\" | \"awaiting-payload\" | \"ready\" | \"running\" | \"done\";\n\n/**\n * How long a site has to seal after one of its jobs is claimed.\n *\n * **Distinct from the lease, and distinct from the job's TTL** — byollm_009\n * §7.1. Three clocks, three different questions:\n *\n * - the **TTL** asks how long the work is worth doing at all;\n * - the **lease** asks how long this device gets to run it;\n * - this asks how long we wait for a site that has gone away.\n *\n * Collapsing any pair of them looks harmless until a site restarts during a\n * deploy: with only a lease, the device sits politely holding a job whose\n * payload will never arrive, and the lease's whole minute is spent waiting on\n * a party that is not coming back. Short, because a site that is up answers in\n * milliseconds and a site that is down will not answer sooner for waiting.\n */\nexport const AWAITING_PAYLOAD_MS = 10_000;\n\n/**\n * How many devices wait for a payload before the hub gives up on the job —\n * B042.\n *\n * Three, matching the daemon's own patience, and for the same reason: a site\n * that is slow, restarting, or briefly unreachable deserves more than one\n * chance, and a site that is gone should not cost the whole fleet a turn\n * each. At {@link AWAITING_PAYLOAD_MS} apiece this is thirty seconds of\n * waiting before a job that nobody can complete is dropped.\n *\n * Dropped rather than marked terminal, exactly as a passed deadline is: the\n * relay is a router, the site holds the authoritative record, and a stub\n * nobody may run is not routing state. A daemon mid-flight learns through\n * `renewLeases`, which reports a job the store no longer holds as `lost`.\n */\n/**\n * How many grants one (site, owner) pair may hold UNSEALED at once — B187,\n * ruled 09-16.\n *\n * A site must be told which device claimed its job, because it seals the\n * payload to that device's public key — that is what lets a blind relay\n * exist at all. **The leak is the ratio, not the key**: nothing required a\n * site to complete a single job, so one that enqueued a thousand and sealed\n * none read a thousand device identities inside one\n * {@link AWAITING_PAYLOAD_MS} window.\n *\n * Keyed on the PAIR rather than on the site, and that is load-bearing twice\n * over. A flat per-site cap would throttle a real product to two in-flight\n * jobs across all its users. And the pair is already how consent is modelled\n * here — `routeKey(siteId, owner)` — so the cap is bounded by the same unit\n * the permission is.\n *\n * **It buys time, not secrecy.** Which device claims is deliberately random\n * (B194: ties are luck), so a patient site still samples a small fleet over\n * minutes. That is the point: minutes leave a signature, and\n * {@link RelayStateOptions.onUnsealedChurn} is what reads it.\n */\nexport const UNSEALED_PER_PAIR = 2;\n\nexport const SEAL_ATTEMPTS_BEFORE_EVICTION = 3;\n\n/**\n * How long a device waits before asking about a job it could not run — the\n * rate every transient refusal needs.\n *\n * **A transient needs a rate; a retry without a not-before is a spin.** A\n * release that is not `refused` requeues immediately and stays claimable by\n * the same device, which is right for a daemon saying \"not now, I am\n * restarting\" and catastrophic for a control plane saying \"that mapping\n * resolves to another of your machines\": the device re-claims at once, is\n * declined again, and the pair loops. Measured before it could happen —\n * twelve ticks produced twelve control-plane reads, which in a deployment is\n * twelve database queries for a job that was never going to run there.\n *\n * Thirty seconds is chosen against the only thing it delays: a person who\n * fixes a mapping and has work already queued. Half a minute is a wait\n * nobody notices, and one read per device per thirty seconds per stuck job is\n * a cost nobody notices either.\n *\n * Distinct from the three durations above it, and for a fourth kind of\n * reason: the TTL asks whether the work is still worth doing, the lease how\n * long this device gets, {@link AWAITING_PAYLOAD_MS} how long we wait for the\n * site — and this asks how long before we ask *this device* again.\n */\nexport const RETRY_AFTER_MS = 30_000;\n\n/** A job the relay is routing. Metadata and ciphertext, nothing else. */\n/** Why a daemon gave a job back. Only `refused` means \"not me, ever\". */\nexport type ReleaseReason =\n \"shutdown\" | \"pause\" | \"revoked\" | \"backend-down\" | \"refused\";\n\nexport interface RoutedJob {\n readonly id: string;\n /** Which site enqueued it — the party that will be asked to seal. */\n readonly siteId: string;\n /**\n * Everything the relay knows about the work, which is everything the site\n * chose to publish and not one field more (byollm_009 §6).\n */\n readonly stub: JobStub;\n state: RoutedState;\n /** Set from the claim; the site seals to these keys. */\n claimedBy?: {\n readonly runnerId: string;\n readonly owner: string;\n readonly device: PublicIdentity;\n readonly leaseId: string;\n readonly leaseExpiresAt: number;\n };\n /** When {@link AWAITING_PAYLOAD_MS} runs out for this claim. */\n awaitingUntil?: number;\n /**\n * How many devices have waited for this payload and not received it — B042.\n *\n * A job whose site never seals is offered, waited on, requeued, and offered\n * again — to a different device each time. Every one of them does the same\n * ten seconds of nothing, and none of them can tell that the last one\n * already tried: the daemon's own patience is per-device by construction,\n * so the fleet works through itself one machine at a time until the job's\n * deadline, which can be an hour away.\n *\n * That is the poison at its source. **The daemon-side breaker (B041) stops\n * one device looping; only the hub can stop the job.** Counted here rather\n * than inferred from `awaitingUntil`, because a requeue clears that clock\n * and the count has to survive it.\n */\n sealAttempts?: number;\n /**\n * The device an ABANDONED grant goes back to — B187's sticky re-offer,\n * ruled 09-16.\n *\n * Set when an unsealed grant lapses, not at claim: a job nobody abandoned\n * is free work for whoever asks, and that is the routing this product\n * wants. Once a site has taken a grant and let it rot, the job is offered\n * only to the device that already answered for it.\n *\n * **This is what turns \"slower and visible\" into \"closed\".** The cap bounds\n * the rate; the churn report makes a walk noticeable; this removes the walk\n * itself, because abandoning the same job repeatedly now reveals ONE\n * identity instead of a fresh sample each window.\n *\n * Survives `#requeue` for the same reason `sealAttempts` does — the requeue\n * is the thing it has to outlive.\n *\n * **The accepted edge (Todd, 09-16): a device that never comes back takes\n * the job with it.** It is still evicted after\n * {@link SEAL_ATTEMPTS_BEFORE_EVICTION}, so the queue does not fill with\n * work nobody can reach; the site simply has to enqueue it again.\n */\n reofferTo?: string;\n /**\n * Runners that released this job with reason `refused` — cloud_008 §2.1.\n *\n * `REFUSAL_NOT_REOFFERED`, which the relay did not implement: it dropped\n * `ReleaseRequest.reason` on the floor. The field's own docstring says why\n * that is not cosmetic — an upstream cannot evaluate a daemon's *local*\n * `named` allowlist, so it may legitimately offer work the daemon then\n * declines, and without a record the two spin between claim and release\n * forever. The direct plane has always kept this list.\n */\n refusedBy: string[];\n /**\n * Runners that may not be offered this job again *yet*, and from when.\n *\n * The middle ground {@link RoutingStore.releaseLeases} had no way to say.\n * `refusedBy` is forever and a bare release is immediate; a control plane\n * declining a job for a reason the world can change — an unfilled mapping\n * slot, a resolution that named another machine, a store that was briefly\n * unreachable — means neither. It means \"ask again later\", and later needs\n * a number.\n *\n * Keyed by runner because it is a fact about a pairing, not about the job:\n * the same job goes to another device immediately, which is the whole\n * point of not marking it refused.\n */\n retryAfter?: Record<string, number>;\n /**\n * The site withdrew this job — cloud_008 §2.2.\n *\n * A flag rather than a state, because a cancelled job that a device is\n * *running* is not finished: the daemon has to be told, abort its backend\n * call and report `canceled`, and the ordinary `complete` path then closes\n * it. Making it a state would strand the in-flight case between two\n * machines' ideas of what happened.\n */\n cancelled?: boolean;\n /** Sealed to the claiming device by the site. Opaque here. */\n payload?: SealedEnvelope;\n /** Sealed to the site by the device. Opaque here. */\n result?: SealedEnvelope;\n /**\n * The result's clear-text discriminator — byollm_009 §6.1.\n *\n * The one outcome fact the relay is given, and the reason it is given:\n * without it the relay cannot stop dispatching a finished job. A routing\n * hint and never a fact — the *site* verifies it against the sealed\n * outcome, because only the site can open the envelope. The relay acts on\n * it and is entitled to be wrong; a lying daemon costs it a dispatch\n * decision, not a security property.\n */\n disposition?: \"ok\" | \"error\" | \"canceled\";\n /**\n * How many tool calls this job may make — byollm_012 §8, the relay's\n * counter.\n *\n * The site's number, sent beside the stub at enqueue for `llm.tools` only:\n * the lower of the payload's `maxToolCalls` and the purpose's. The relay\n * cannot read the payload, so it takes the site's word, and that is safe in\n * the one direction this counter exists for: it protects the site's tools\n * from a modified daemon, and a site that overstates its own budget spends\n * only its own. Absent, the protocol ceiling applies.\n */\n maxToolCalls?: number;\n /**\n * Tool calls this job has made, under any grant.\n *\n * Monotonic and never reset, so it is not a tally that a missed decrement\n * can corrupt. It survives `#requeue` on purpose: a budget that restarted\n * with every grant would let a modified daemon release, re-claim and spend\n * the site's tools again — the counter exists to stop exactly that. The\n * cost is that a job reclaimed after a lapse runs on what is left, and a\n * second device's own count starts at 0: its first call past what is left\n * is refused as `budget`, which an honest daemon reads as the job's tools\n * being spent — a tool error to the model and the closing turn, `ok` with\n * `stop: \"tool-budget\"` (byollm_012 §8, `TOOLS_SPENT_MESSAGE`).\n */\n toolCallsMade?: number;\n /**\n * The calls in flight under the CURRENT grant — byollm_012 §5.2.\n *\n * Short-lived: cleared when the grant ends (`#requeue`), when the job\n * finishes, and with the job. So a result can only ever be bound to a call\n * made under the lease that is running now, and a late answer for a grant\n * that ended has nothing to land on.\n */\n toolCalls?: ToolCallRow[];\n}\n\n/** One tool call the relay is carrying. Ciphertext and ids, nothing else. */\nexport interface ToolCallRow {\n readonly callId: string;\n /** The grant it was made under, which is the one it can be answered for. */\n readonly leaseId: string;\n /** Sealed to the site by the device. Opaque here. */\n readonly envelope: SealedEnvelope;\n /** When the relay stops holding it open: `TOOL_LIMITS.callTimeoutMs` on. */\n readonly expiresAt: number;\n /** Sealed to the device by the site, once answered. Opaque here. */\n result?: SealedEnvelope;\n}\n\n/**\n * The sub-state of a running job — byollm_012 §5.3.\n *\n * A job waiting on a tool result is still `running` and still holds its\n * lease. `waiting-on-site` says why nothing is moving, so that a reader\n * asking \"is anything running this?\" (`NO_RUNNER_SIGNAL`) can tell a device\n * at work from a site that has not answered. Derived rather than stored: it\n * is true exactly while a call made under the current grant is unanswered\n * and inside its timeout, and a stored flag would be a second answer to that.\n */\nexport type RunningSubState = \"waiting-on-site\";\n\nexport function subStateOf(\n job: RoutedJob,\n now: number,\n): RunningSubState | undefined {\n if (job.state !== \"running\") return undefined;\n const lease = job.claimedBy?.leaseId;\n const waiting = (job.toolCalls ?? []).some(\n (call) =>\n call.leaseId === lease &&\n call.result === undefined &&\n call.expiresAt > now,\n );\n return waiting ? \"waiting-on-site\" : undefined;\n}\n\n/** Why a tool call was refused, beyond the holder refusals. */\nexport type ToolCallRefusal =\n | HolderRefusal\n /** The job is not `llm.tools`, so it has no tools to call. */\n | \"not-tools\"\n /** The call past the job's budget — byollm_012 §8. */\n | \"budget\"\n /** A call id this grant already used, for a different envelope. */\n | \"call-conflict\";\n\n/** A call waiting on a site, with the device the answer is sealed to. */\nexport interface OutstandingToolCall {\n readonly jobId: string;\n readonly leaseId: string;\n readonly callId: string;\n readonly envelope: SealedEnvelope;\n readonly device: PublicIdentity;\n readonly expiresAt: number;\n}\n\n/** Two envelopes are one when every field is — a replay, not a new call. */\nconst sameEnvelope = (a: SealedEnvelope, b: SealedEnvelope): boolean =>\n JSON.stringify(a) === JSON.stringify(b);\n\n/** A device the relay has seen recently. */\nexport interface Presence {\n readonly runnerId: string;\n readonly owner: string;\n readonly device: PublicIdentity;\n lastSeenAt: number;\n /**\n * What this machine last said it can run — cloud_009, 2026-08-24.\n *\n * **Capabilities are presence data.** They arrive on the same heartbeat as\n * everything else here, they go stale at the same moment and for the same\n * reason, and a machine that stops heartbeating has not stopped being able\n * to run Llama — it has stopped being somewhere we can ask. Keeping them\n * anywhere else would put capability truth outside the interface that owns\n * presence, and every next consumer (a member's usable set, a dashboard's\n * pulse, a degraded-state banner) would re-derive it from a different\n * place. That is the two-owners shape this codebase keeps paying for.\n *\n * Empty is a real answer, not a missing one: it is a paired machine with no\n * healthy backend, which is a legal state the whole connect-first ruling\n * exists to make visible rather than refuse.\n */\n capabilities: CapabilityMatrix;\n /**\n * Kinds this machine is deliberately *not* advertising — byollm_016.\n *\n * Presence data for the same reason capabilities are, and stored beside\n * them rather than derived: two services answering one kind with no\n * `defaults` entry is a state only the daemon can see, and the hub cannot\n * reconstruct it from the matrix — an absent kind and a withheld kind look\n * identical there. Without this field the owner's page can say \"nothing\n * serves llm.generate\", which is true and useless, instead of \"two services\n * answer it and you have not chosen\", which is the sentence that ends with\n * the owner doing something.\n *\n * Empty is the normal answer, and means every kind resolved.\n */\n withheld: readonly WithheldKind[];\n // `revoked` is deliberately absent — cloud_008 §2.3.\n //\n // It was a boolean on the *runner*, written at heartbeat and read by\n // nothing but the debug page. Enforcement had already moved to the\n // projection, because enforcing on this flag made revocation depend on the\n // client calling an endpoint: a daemon that simply never heartbeat went on\n // claiming forever. What survived was the cache, which is a stored copy of\n // a derived fact — this project's most-repeated bug, kept alive here as a\n // display value.\n //\n // It is also a concept multi-tenancy cannot express. Revocation is a fact\n // about an (owner, site) pair; a daemon serving two sites and revoked at\n // one is not \"a revoked runner\", and a boolean on the device has nowhere to\n // put the difference. Deleting it now is what stops cloud_009 inheriting a\n // field it would have to contradict.\n}\n\n/**\n * What a routing store must do, expressed as operations — cloud_006 §3.2.\n *\n * Every method below is a **decision plus its write**, never a read the caller\n * follows with a mutation. That is the whole point, and it is the difference\n * between an interface a shared store can implement and one it cannot.\n *\n * `claim` is the specimen. It used to live in `DaemonPlane` as\n * `jobs()` → filter → mutate, which is atomic for exactly one reason: Node is\n * single-threaded and these Maps are local, so nothing runs between the read\n * and the write. Neither survives a store on a network, and\n * `packages/relay/test/two-replicas.test.ts` holds the resulting race as a\n * failing assertion.\n *\n * So the rule for anything added here: **if a caller has to read, decide, and\n * write back, the operation is in the wrong place.** Move the decision in.\n *\n * ## Why the projection does not come with it\n *\n * `claim` takes `owners: string[]` rather than a projection or a predicate.\n * A closure cannot travel to Valkey, and the projection replicates for free\n * from the control plane — so the caller collapses it with\n * `Projection.ownersRunnableBy` and hands over data the store can match on.\n * That keeps the store ignorant of consent, which is also what keeps it\n * replaceable.\n */\nexport interface ClaimInput {\n readonly runnerId: string;\n readonly owner: string;\n readonly device: PublicIdentity;\n /**\n * The (site, owner) pairs this device may run work for — cloud_009 §3.\n *\n * **One set of pairs, not a set of sites and a set of owners.** Consent\n * binds a user to a site, so the two cannot travel separately: a device\n * whose owner consented to site A, serving a roster member who consented\n * to site B, would have every element of both sets and no consented route\n * between them. Two sets multiply; consent does not.\n *\n * Built by {@link Projection.routesFor} and matched with {@link routeKey},\n * so the relay and a store in another repository agree on the encoding by\n * calling the same function rather than by both spelling it out.\n *\n * This is the collapse that lets a claim stay one operation: a predicate\n * cannot travel to a store over a network, and a set can.\n */\n readonly routes: ReadonlySet<string>;\n /**\n * Kinds this device can run — and that is now the whole of the match.\n *\n * A relay routes by kind and by consent; **which service answers is not its\n * question**. A job names a purpose, a person's mapping names a service,\n * and a control plane joins them at claim. A relay that filtered on the\n * service would need the mapping, which is the one thing it is not supposed\n * to hold.\n *\n * This carried a companion, `serves`, holding the (kind, service) pairs a\n * device advertised, so a job naming a service reached only a device with\n * it. Sites stopped naming services (Amendment L) and the field became wire\n * nothing read — so it is gone rather than left for a reader to infer\n * meaning from.\n *\n * The cost is stated plainly: a job may be offered to a device whose owner\n * admits the person but whose machine their mapping did not name. The\n * control plane declines it as not-here and it goes back with a\n * {@link RETRY_AFTER_MS} wait, which is what that mechanism is for.\n */\n readonly kinds: ReadonlySet<string>;\n readonly max: number;\n readonly leaseMs: number;\n}\n\n/**\n * How a (site, owner) route is written, so two implementations agree.\n *\n * The same `\\u0000` the job key uses, for the same reason: it cannot appear\n * in a site id or an owner id, so this is a key rather than a parser.\n */\nexport const routeKey = (siteId: string, owner: string): string =>\n `${siteId}\\u0000${owner}`;\n\n/**\n * Where the store's sense of time comes from — cloud_006 §3.4.\n *\n * **The store owns its clock; callers do not pass one.** Every deadline the\n * relay decides — a lease's expiry, the `awaiting-payload` window, what a\n * sweep considers due — is now stamped by one source, and it is the same\n * source that will later stamp them for every replica.\n *\n * It used to be a parameter. `claim` took `now`, `sweep` took `now`, and each\n * plane called its own `now()` before calling in — which is fine in one\n * process and is the recurring bug the moment there are two. A lease granted\n * by a pod whose clock runs fast is short; the same lease swept by a pod whose\n * clock runs slow outlives it. Nobody is wrong and the lease has no length.\n *\n * A Valkey-backed store returns `TIME` here, so the deadline and the sweep\n * that enforces it are read from the same server. The injected clock stays for\n * tests, which is what lets them move time instead of sleeping.\n *\n * **What deliberately does not use this**: request-signature freshness. That\n * is checked against the *local* clock on purpose — it is a question about the\n * caller's clock versus this process's, `MAX_CLOCK_SKEW_MS` already tolerates\n * two minutes of disagreement, and a network round trip to timestamp every\n * inbound request would be a cost with no property behind it.\n */\n/**\n * How often a pair may burn unsealed grants before it is worth a human's\n * attention — B187's other half, ruled 09-16.\n *\n * **The cap buys time; it does not buy secrecy.** Which device claims is\n * deliberately random (B194: ties are luck), so a patient site still samples a\n * small fleet over minutes. You cannot cap your way out of a slow walk — but\n * you can notice one, and this is the shape to notice: **an honest site never\n * gets here at all**, because it seals in about a round trip and the grant\n * never reaches {@link AWAITING_PAYLOAD_MS}.\n *\n * Six in five minutes is comfortably above the noise a flaky network makes and\n * far below what a walk produces — a pair burning its {@link\n * UNSEALED_PER_PAIR} slots every ten seconds passes this inside a minute.\n */\nexport const CHURN_EXPIRIES = 6;\nexport const CHURN_WINDOW_MS = 5 * 60_000;\n/** One report per pair per hour. An alert that repeats is an alert nobody reads. */\nexport const CHURN_QUIET_MS = 60 * 60_000;\n\n/** A pair burning grants without sealing them — B187. */\nexport interface UnsealedChurn {\n readonly siteId: string;\n readonly owner: string;\n /** How many unsealed grants expired inside the window. */\n readonly expiries: number;\n readonly windowMs: number;\n}\n\nexport interface RelayStateOptions {\n readonly now?: () => number | Promise<number>;\n /**\n * Told when a pair keeps claiming and not sealing — B187.\n *\n * A callback rather than an email, because this package is the open-source\n * relay: where a report GOES is a deployment's business, and `support@` is\n * one deployment's address. The hub wires this to mail; a self-hoster wires\n * it to whatever they read.\n *\n * Deliberately minimal — scaffolding until the signal system replaces it.\n */\n readonly onUnsealedChurn?: (churn: UnsealedChurn) => void;\n}\n\n/** Why a lease-scoped operation was refused, in the caller's vocabulary. */\nexport type HolderRefusal =\n | \"not-found\"\n | \"not-holder\"\n | \"stale-lease\"\n | \"not-ready\"\n /** The job already ended — V1-6. A replay must not reopen it. */\n | \"terminal\";\n\n/**\n * In-memory routing state.\n *\n * Deliberately not durable. The skeleton proves the protocol, and the\n * production hub replaces this with the closed multi-tenant router behind the\n * same shape (cloud_004 §9). Anything a restart loses here is a job that\n * returns to its site's queue — which is the behaviour a lapsed lease already\n * has to produce, so nothing new needs to be true for this to be safe.\n */\n/**\n * A job's key: the site that published it, and the id that site chose.\n *\n * `\\u0000` cannot appear in either half, so this is a key rather than a\n * parser — cloud_009 §3, and the reason the Valkey layout uses a distinct\n * prefix rather than a suffix on the old one.\n */\nconst keyOf = (siteId: string, jobId: string): string =>\n `${siteId}\\u0000${jobId}`;\n\nexport class RelayState implements RoutingStore {\n /**\n * Jobs by **(site, id)** — cloud_009 §3.\n *\n * A job id is a site's to choose, so two sites can choose the same one.\n * Keyed by the bare id, the second site's enqueue returned the first\n * site's job (cloud_008 finding 58), and the refusal that fixed it was a\n * cross-tenant existence oracle. Keyed by the pair, the collision does not\n * exist and there is nothing to refuse.\n *\n * `\\u0000` as the separator, because a site id is a uuid and a job id is\n * whatever a site chose — including, one day, a string with a colon in it.\n * A separator that cannot appear in either half is the difference between\n * a key and a parser.\n */\n readonly #jobs = new Map<string, RoutedJob>();\n\n /**\n * Grants by lease id, so a holder-scoped call needs no site — §3.\n *\n * `takePayload`, `complete`, `releaseLeases` and `renewLeases` carry a\n * `leaseId` the relay minted, which is unique across every site. That is\n * what lets those four signatures stay as they are: the caller names the\n * grant, and the grant names the job. A daemon never has to know a site id\n * to answer for work it holds.\n */\n readonly #byLease = new Map<string, RoutedJob>();\n\n /**\n * Jobs by bare id, across sites — the refusal path.\n *\n * The lease index alone answers the happy case and gets the refusals\n * wrong: a **stale** lease finds nothing, so `LEASE_HONORED`'s \"your grant\n * ended\" becomes \"no such job\", and a daemon that was slow is told\n * something untrue about the work it was doing. Distinguishing\n * `not-found`, `not-holder` and `stale-lease` needs the job even when the\n * lease named is over, and that is what this is for.\n *\n * A list rather than a single value: two sites may choose one id, which is\n * the whole reason `#jobs` is keyed by the pair.\n */\n readonly #byJobId = new Map<string, RoutedJob[]>();\n\n /**\n * The job a holder-scoped call is about, without a site id.\n *\n * The exact grant first, and **checked against the job the caller named**:\n * a lease id belonging to another job would otherwise hand over that job's\n * payload to somebody holding a valid-looking grant. Then the same job held\n * by this runner under an older grant, which is what `stale-lease` is.\n *\n * And then nothing — V1-8. There used to be a third step: any job with that\n * id, which produced `not-holder` where an absent job produces `not-found`.\n * Since job ids are chosen per site, a runner could name a bare id it had\n * no relationship with and learn from the status code whether some *other*\n * tenant had a job by that name. Finding 58's existence oracle, through the\n * holder door.\n *\n * The distinction it bought was never acted on: a daemon abandons the work\n * either way. So a caller now learns about jobs it holds or held, and about\n * nothing else.\n */\n #grantFor(\n jobId: string,\n runnerId: string,\n leaseId: string,\n ): RoutedJob | undefined {\n const exact = this.#byLease.get(leaseId);\n if (exact?.id === jobId) return exact;\n const candidates = this.#byJobId.get(jobId) ?? [];\n return candidates.find((job) => job.claimedBy?.runnerId === runnerId);\n }\n\n #index(job: RoutedJob): void {\n const bare = this.#byJobId.get(job.id);\n if (bare) {\n if (!bare.includes(job)) bare.push(job);\n } else {\n this.#byJobId.set(job.id, [job]);\n }\n }\n\n /**\n * Record an unsealed grant expiring, and report a pair that keeps doing it.\n *\n * Reported at the crossing rather than on every expiry after it, and then\n * quiet for {@link CHURN_QUIET_MS} — a walk produces one of these every ten\n * seconds, and an alert per expiry is an alert somebody filters.\n *\n * The callback is never awaited and its throw is swallowed: a report is\n * evidence ABOUT the sweep, not part of it, and a mail server being down\n * must not stop jobs being requeued.\n */\n #noteChurn(siteId: string, owner: string, now: number): void {\n const report = this.#churnReport;\n if (report === undefined) return;\n\n const pair = routeKey(siteId, owner);\n const seen = [...(this.#churn.get(pair) ?? []), now].filter(\n (at) => now - at <= CHURN_WINDOW_MS,\n );\n this.#churn.set(pair, seen);\n if (seen.length < CHURN_EXPIRIES) return;\n\n const told = this.#churnReported.get(pair);\n if (told !== undefined && now - told < CHURN_QUIET_MS) return;\n this.#churnReported.set(pair, now);\n\n try {\n report({\n siteId,\n owner,\n expiries: seen.length,\n windowMs: CHURN_WINDOW_MS,\n });\n } catch {\n /* A report that throws must not take the sweep with it. */\n }\n }\n\n #forget(job: RoutedJob): void {\n this.#jobs.delete(keyOf(job.siteId, job.id));\n const bare = (this.#byJobId.get(job.id) ?? []).filter((it) => it !== job);\n if (bare.length === 0) this.#byJobId.delete(job.id);\n else this.#byJobId.set(job.id, bare);\n if (job.claimedBy) this.#byLease.delete(job.claimedBy.leaseId);\n }\n /**\n * When each pair's unsealed grants expired, and when it was last reported.\n *\n * Timestamps rather than a counter, because the threshold is \"inside a\n * window\" — a counter would have to be reset by something, and whatever\n * reset it would be the thing to get wrong. Trimmed on write, so it holds\n * at most a window's worth per pair.\n */\n readonly #churn = new Map<string, number[]>();\n readonly #churnReported = new Map<string, number>();\n\n readonly #presence = new Map<string, Presence>();\n readonly #now: () => number | Promise<number>;\n /** Kept whole rather than destructured: B187's report seam lives on it. */\n readonly #churnReport: RelayStateOptions[\"onUnsealedChurn\"];\n\n constructor(options: RelayStateOptions = {}) {\n this.#now = options.now ?? Date.now;\n this.#churnReport = options.onUnsealedChurn;\n }\n\n /** The one clock every deadline in this store is stamped from. */\n async now(): Promise<number> {\n return this.#now();\n }\n\n /**\n * Take a stub for routing. The payload is not here and will not be.\n *\n * **Idempotent by job id, and that is a security property rather than a\n * convenience.** Site-plane calls are authenticated by signature, and\n * byollm_009 §4.2's argument for signing the request instead of a\n * server-issued nonce rests entirely on every write being idempotent per the\n * instance it names. This one was not: re-enqueueing a known id built a\n * fresh `queued` job over the top of the old one, discarding a live claim,\n * its lease and any payload the site had already sealed to a device. A\n * replayed enqueue inside the two-minute freshness window was therefore a\n * way to yank a job back from the machine running it — the `release` bug of\n * §4.2, rediscovered on the other plane.\n *\n * So a known id returns what is already routing, unchanged. A site that\n * restarts and republishes its queue is the normal case, and it must not\n * disturb work in flight.\n */\n enqueue(input: {\n id: string;\n siteId: string;\n stub: JobStub;\n maxToolCalls?: number;\n }): Promise<RoutedJob> {\n // Idempotent by (site, id). The refusal that used to live here went with\n // the collision it refused — cloud_009 §3.\n const existing = this.#jobs.get(keyOf(input.siteId, input.id));\n if (existing) return Promise.resolve(existing);\n const job: RoutedJob = {\n id: input.id,\n siteId: input.siteId,\n stub: input.stub,\n state: \"queued\",\n refusedBy: [],\n ...(input.maxToolCalls === undefined\n ? {}\n : { maxToolCalls: input.maxToolCalls }),\n };\n this.#jobs.set(keyOf(job.siteId, job.id), job);\n this.#index(job);\n return Promise.resolve(job);\n }\n\n job(siteId: string, jobId: string): Promise<RoutedJob | undefined> {\n return Promise.resolve(this.#jobs.get(keyOf(siteId, jobId)));\n }\n\n jobs(): Promise<RoutedJob[]> {\n return Promise.resolve([...this.#jobs.values()]);\n }\n\n /** Jobs a site must seal for, right now. */\n async awaiting(siteId: string): Promise<RoutedJob[]> {\n return (await this.jobs()).filter(\n (j) => j.siteId === siteId && j.state === \"awaiting-payload\",\n );\n }\n\n /** Sealed results waiting to go home. */\n async finished(siteId: string): Promise<RoutedJob[]> {\n return (await this.jobs()).filter(\n (j) =>\n j.siteId === siteId && j.state === \"done\" && j.result !== undefined,\n );\n }\n\n /**\n * Claim work — one operation, because it has to be.\n *\n * Moved here wholesale from `DaemonPlane`, where it was a scan followed by\n * per-job mutation. Nothing about the *decision* changed; what changed is\n * that a store can now implement it, because the filter and the write are\n * one call rather than a loop the caller drives.\n *\n * The order of the guards is worth preserving as-is when this becomes a Lua\n * script: cheapest first, and `owners` last because it is the only one that\n * needed the projection.\n */\n async claim(input: ClaimInput): Promise<ClaimedStub[]> {\n const now = await this.now();\n await this.sweep();\n\n const granted: ClaimedStub[] = [];\n\n /**\n * How many grants each pair is already sitting on, unsealed — B187.\n *\n * Counted in a pass rather than kept in a counter. The claim path is\n * already O(jobs) — the loop below visits every one — so this is the same\n * order for no new state; a maintained tally would need claim, seal,\n * requeue, forget and lease-expiry to agree for ever, and **one missed\n * decrement would throttle that pair permanently while looking exactly\n * like a quiet site.**\n */\n const unsealed = new Map<string, number>();\n for (const job of this.#jobs.values()) {\n if (job.state !== \"awaiting-payload\") continue;\n const pair = routeKey(job.siteId, job.stub.owner);\n unsealed.set(pair, (unsealed.get(pair) ?? 0) + 1);\n }\n\n for (const job of this.#jobs.values()) {\n if (granted.length >= input.max) break;\n if (job.state !== \"queued\") continue;\n // The route, as one lookup, because consent is about the pair — a\n // device whose owner consented to site A, serving a roster member who\n // consented to site B, is in both a set of sites and a set of owners\n // and has no consented route between them.\n if (!input.routes.has(routeKey(job.siteId, job.stub.owner))) continue;\n /**\n * Already holding its share unsealed — B187. Left queued rather than\n * refused: the site has consented and the work is legitimate, it is the\n * RATE of unsealed grants that is bounded. The moment it seals one, the\n * next claim takes this job.\n */\n /**\n * Abandoned once, so it goes back only to the device that answered for\n * it — B187's sticky re-offer.\n *\n * Checked before the cap, because a job this device may not have should\n * not spend that device's budget on the way to being skipped.\n */\n if (job.reofferTo !== undefined && job.reofferTo !== input.runnerId) {\n continue;\n }\n const pair = routeKey(job.siteId, job.stub.owner);\n if ((unsealed.get(pair) ?? 0) >= UNSEALED_PER_PAIR) continue;\n // By kind, and only by kind — Amendment L. Which of the owner's\n // services answers is the control plane's, resolved from this person's\n // mapping at claim; a relay that matched on it would need to hold the\n // mapping, and holding it is what a relay must not do.\n if (!input.kinds.has(job.stub.kind)) continue;\n // Already declined by this device — `REFUSAL_NOT_REOFFERED`, §2.1.\n if (job.refusedBy.includes(input.runnerId)) continue;\n // Declined for something that may have changed since, but not yet.\n if ((job.retryAfter?.[input.runnerId] ?? 0) > now) continue;\n // Withdrawn by the site — §2.2. Cheap, and before every other check.\n if (job.cancelled) continue;\n // The relay's half of AUDIENCE_BOTH_SIDES. The daemon re-checks its own\n // allowlist and may still refuse — this only ever narrows.\n\n // `self` means the owner's own machines, and the route set cannot\n // express that — cloud_008 §2.1.\n //\n // The routes are every (site, owner) this device may run for, which for\n // a Team owner's machine includes every roster member. Correct for\n // `public` and `named`, and wrong for\n // `self`: a roster member's private job was offered to the owner's\n // daemon, which refused it locally and released it, and the relay\n // offered it straight back. The ping-pong was the visible symptom; the\n // invisible one is that `self` — the audience a user picks *because*\n // they want their own machine — was the audience the relay ignored.\n if (job.stub.audience === \"private\" && job.stub.owner !== input.owner) {\n continue;\n }\n\n // A UUID, not a readable composite. The direct plane's lease ids are\n // UUIDs and the Supabase adapter's `lease_id` column is typed `uuid`, so\n // a relay minting `lease_<job>_<time>` would route perfectly against a\n // memory store and fail the moment a real site adopted the lease.\n const leaseId = randomUUID();\n job.state = \"awaiting-payload\";\n job.claimedBy = {\n runnerId: input.runnerId,\n owner: input.owner,\n device: input.device,\n leaseId,\n leaseExpiresAt: now + input.leaseMs,\n };\n // Not the lease: this bounds how long we wait for a *site*, not how long\n // the device may work. byollm_009 §7.1's third clock.\n job.awaitingUntil = now + AWAITING_PAYLOAD_MS;\n /* This pair now holds one more unsealed grant, so a later job in the\n same batch sees the cap — B187. Without it `max: 10` would hand a\n non-sealing site ten devices in one call. */\n unsealed.set(pair, (unsealed.get(pair) ?? 0) + 1);\n // The grant is findable by its own id, which is how a holder-scoped\n // call needs no site — cloud_009 §3.\n this.#byLease.set(leaseId, job);\n\n granted.push({\n ...job.stub,\n lease: {\n id: leaseId,\n runnerId: input.runnerId,\n expiresAt: job.claimedBy.leaseExpiresAt,\n },\n });\n }\n return granted;\n }\n\n /**\n * Hand over the sealed payload to the device that holds the lease.\n *\n * The read and the state transition are one operation for the same reason\n * `claim` is: `running` must be set by whoever was told the envelope, or two\n * replicas can both hand out the same work and both believe they were first.\n */\n takePayload(input: {\n jobId: string;\n runnerId: string;\n leaseId: string;\n }): Promise<{ envelope: SealedEnvelope } | { refused: HolderRefusal }> {\n const job = this.#grantFor(input.jobId, input.runnerId, input.leaseId);\n if (!job) return Promise.resolve({ refused: \"not-found\" });\n if (job.claimedBy?.runnerId !== input.runnerId) {\n return Promise.resolve({ refused: \"not-holder\" });\n }\n // LEASE_HONORED per *instance*: a stale lease id names a grant that is\n // over, and answering it would hand work to a previous holder.\n if (job.claimedBy.leaseId !== input.leaseId) {\n return Promise.resolve({ refused: \"stale-lease\" });\n }\n if (!job.payload) return Promise.resolve({ refused: \"not-ready\" });\n // Only a job that is still running gets handed its payload — V1-6.\n //\n // The holder and lease checks pass for a job this runner finished\n // moments ago, because completing does not end the grant. A replayed\n // fetch then set `state = 'running'` on a **done** job: `finished()`\n // stopped returning its result to the site, and the sweep requeued\n // completed work as though the device had died holding it. A duplicate\n // request undoing a finished job is the shape `RESULT_IDEMPOTENT` exists\n // to forbid, arriving through the other door.\n if (job.state !== \"ready\" && job.state !== \"running\") {\n return Promise.resolve({ refused: \"terminal\" });\n }\n job.state = \"running\";\n return Promise.resolve({ envelope: job.payload });\n }\n\n /**\n * Record a finished job.\n *\n * `RESULT_IDEMPOTENT` lives here rather than in the caller: a replayed\n * result must be a no-op decided by the same operation that would have\n * written it, or two replicas can both decide they were the first.\n */\n complete(input: {\n jobId: string;\n runnerId: string;\n leaseId: string;\n envelope: SealedEnvelope;\n disposition: \"ok\" | \"error\" | \"canceled\";\n }): Promise<\n | { accepted: boolean; duplicate?: boolean; state: RoutedState }\n | { refused: HolderRefusal }\n > {\n const job = this.#grantFor(input.jobId, input.runnerId, input.leaseId);\n if (!job) return Promise.resolve({ refused: \"not-found\" });\n if (job.claimedBy?.runnerId !== input.runnerId) {\n return Promise.resolve({ refused: \"not-holder\" });\n }\n // Terminal before holder — cloud_008 §3.6, and the same order in all four\n // stores.\n //\n // This file argued the opposite two days ago: that a result under a grant\n // that ended is a different device's work arriving late rather than a\n // replay, so the lease check should win. That is right for a job which is\n // **not** terminal, and the two orders only ever disagree about a *done*\n // job asked about under a stale grant — where \"already recorded\" is the\n // more useful of two true statements, and \"your lease is stale\" invents a\n // worry about an answer that is safely stored.\n //\n // The deciding argument is not comfort. byollm_009 §4's case for signing\n // requests rather than issuing nonces rests on every write being\n // idempotent per the instance it names, and on the direct plane\n // `RESULT_IDEMPOTENT` was holding only because `complete` nulls the lease\n // and the holder check tripped first. A MUST another MUST's security\n // argument leans on cannot hold by coincidence.\n //\n // Scoped to the device that finished it: anyone else falls through to the\n // holder check and gets the refusal they would get for a job that is not\n // terminal, so a job id is not a terminality probe.\n if (job.state === \"done\") {\n const sameGrant = job.claimedBy.leaseId === input.leaseId;\n return Promise.resolve(\n sameGrant\n ? { accepted: false, duplicate: true, state: job.state }\n : { refused: \"stale-lease\" },\n );\n }\n // LEASE_HONORED per instance — cloud_008 §1.4a.\n if (job.claimedBy.leaseId !== input.leaseId) {\n return Promise.resolve({ refused: \"stale-lease\" });\n }\n job.result = input.envelope;\n job.disposition = input.disposition;\n job.state = \"done\";\n // The job ended, so every call made under it did too — byollm_012 §5.2.\n // A site answering one now has nothing to land on.\n delete job.toolCalls;\n return Promise.resolve({ accepted: true, state: job.state });\n }\n\n /** Give back leases this runner holds, naming each grant it means. */\n releaseLeases(input: {\n runnerId: string;\n leases: readonly { jobId: string; leaseId: string }[];\n reason?: ReleaseReason;\n retryAfter?: number;\n }): Promise<string[]> {\n const released: string[] = [];\n for (const { jobId, leaseId } of input.leases) {\n // Through the grant, like every other holder-scoped operation — the\n // caller names a lease and this store no longer keys jobs by a bare id.\n const job = this.#grantFor(jobId, input.runnerId, leaseId);\n if (!job || job.claimedBy?.runnerId !== input.runnerId) continue;\n if (job.claimedBy.leaseId !== leaseId) continue;\n /**\n * A finished job is finished — byollm-review 2026-08-27.\n *\n * Terminal **before** holder, the ordering `complete` already uses: a\n * release naming a valid lease on a done job was flipping it back to\n * `queued`. The recorded result survives on the row and becomes\n * unreachable, because `finished()` filters on the state — so the site\n * never collects it, the job is offered again, and somebody's hardware\n * runs it a second time and overwrites the first answer.\n *\n * The daemon's own shutdown races exactly this. `shutdown()` snapshots\n * the active leases while a job is finishing, the abort lands, and a\n * release and a result for the same lease are in flight together. If\n * the result wins, this used to undo it.\n *\n * `takePayload` got this guard at V1-6 and `complete` at cloud_008\n * §3.6. This is the third holder-scoped door and it was the one left\n * open — which is the argument for the contract case beside it: three\n * doors, one rule, and the two that were shut were shut one at a time.\n */\n if (job.state === \"done\") continue;\n // Recorded before the requeue, so the job goes back to the queue\n // already knowing not to come back here. A daemon releasing for\n // `shutdown` or `backend-down` is saying \"not now\"; `refused` is the\n // only one that means \"not me, ever\" — the others must stay claimable\n // by the same device or a restart would strand its own work.\n if (\n input.reason === \"refused\" &&\n !job.refusedBy.includes(input.runnerId)\n ) {\n job.refusedBy.push(input.runnerId);\n }\n // Recorded before the requeue for the same reason the refusal is: the\n // job goes back to the queue already knowing when it may come back\n // here, rather than being claimable for the instant in between.\n if (input.retryAfter !== undefined) {\n job.retryAfter = {\n ...job.retryAfter,\n [input.runnerId]: input.retryAfter,\n };\n }\n this.#requeue(job);\n released.push(jobId);\n }\n return Promise.resolve(released);\n }\n\n /**\n * Take a site's sealed payload for a claimed job.\n *\n * Refuses anything not `awaiting-payload`, which is what makes the timeout\n * mean something: a late seal must not land on a claim that has moved.\n */\n seal(input: {\n jobId: string;\n siteId: string;\n envelope: SealedEnvelope;\n }): Promise<\n | { state: RoutedState }\n | { refused: \"not-found\" | \"too-late\"; was?: RoutedState }\n > {\n const job = this.#jobs.get(keyOf(input.siteId, input.jobId));\n if (job?.siteId !== input.siteId) {\n return Promise.resolve({ refused: \"not-found\" });\n }\n if (job.state !== \"awaiting-payload\") {\n return Promise.resolve({ refused: \"too-late\", was: job.state });\n }\n job.payload = input.envelope;\n job.state = \"ready\";\n delete job.awaitingUntil;\n /* The site sealed, so the count of devices that waited in vain resets —\n B042. It measures CONSECUTIVE failures to seal; without this it would\n become a lifetime quota, and a job requeued twice for ordinary lease\n lapses would be evicted for a payload problem it does not have. */\n delete job.sealAttempts;\n return Promise.resolve({ state: job.state });\n }\n\n /** {@link RoutingStore.cancel} — the site withdraws a job. */\n cancel(input: { jobId: string; siteId: string }): Promise<boolean> {\n const job = this.#jobs.get(keyOf(input.siteId, input.jobId));\n // Scoped to the caller's site for the same reason every other site-plane\n // operation is: a site must not be able to cancel somebody else's work by\n // guessing an id.\n if (job?.siteId !== input.siteId) return Promise.resolve(false);\n job.cancelled = true;\n // Not deleted, and not requeued. If a device holds it, that device has to\n // hear about it — which is what `cancelRequests` below is for.\n return Promise.resolve(true);\n }\n\n /** {@link RoutingStore.cancelRequests} — cancelled jobs this runner holds. */\n cancelRequests(runnerId: string): Promise<Grant[]> {\n return Promise.resolve(\n [...this.#jobs.values()]\n .filter(\n (job) =>\n job.cancelled === true && job.claimedBy?.runnerId === runnerId,\n )\n // The grant, not the id — V1-3. Two sites may have chosen the same\n // job id, and a daemon holding both cannot tell which of them a bare\n // id means.\n .map((job) => ({\n jobId: job.id,\n leaseId: job.claimedBy?.leaseId ?? \"\",\n }))\n .filter((grant) => grant.leaseId !== \"\"),\n );\n }\n\n /** {@link RoutingStore.renewLeases} — extend what is still held, name what is not. */\n async renewLeases(input: {\n runnerId: string;\n leases: readonly { jobId: string; leaseId: string }[];\n leaseMs: number;\n }): Promise<{\n renewed: { jobId: string; expiresAt: number }[];\n lost: Grant[];\n }> {\n // The store's clock, not the caller's — cloud_006 §3.4. A lease extended\n // against one replica's `Date.now()` and swept against another's is a\n // lease with no length.\n const now = await this.now();\n const renewed: { jobId: string; expiresAt: number }[] = [];\n const lost: Grant[] = [];\n\n for (const { jobId, leaseId } of input.leases) {\n const job = this.#grantFor(jobId, input.runnerId, leaseId);\n const held = job?.claimedBy;\n // The lease id *and* the runner. A lease id is a UUID so the runner\n // check is belt and braces, but \"this grant, held by you\" is the\n // sentence every other operation in this file checks, and a renewal is\n // the one that extends a hold rather than ending it.\n if (\n !job ||\n held?.leaseId !== leaseId ||\n held.runnerId !== input.runnerId\n ) {\n lost.push({ jobId, leaseId });\n continue;\n }\n // Replaced rather than mutated: the grant is a readonly record, which\n // is what stops any other operation here from quietly extending it.\n const expiresAt = now + input.leaseMs;\n job.claimedBy = { ...held, leaseExpiresAt: expiresAt };\n renewed.push({ jobId, expiresAt });\n }\n\n // `awaitingUntil` is deliberately untouched. That clock bounds how long we\n // wait for a *site* to seal, and a busy device has no bearing on it —\n // byollm_009 §7.1's third clock stays third.\n return { renewed, lost };\n }\n\n /**\n * {@link RoutingStore.recordToolCall} — one sealed call, counted and kept.\n *\n * The holder checks are `takePayload`'s, in the same order, because a\n * tool call is the same claim (\"this grant, held by me\") made mid-job.\n * Then the two only this endpoint has: the job must be `llm.tools`, and\n * the call must fit the budget. Counted **before** it is written, so the\n * call that would exceed the budget is the one refused (`TOOLS_BUDGETED`).\n */\n async recordToolCall(input: {\n jobId: string;\n runnerId: string;\n leaseId: string;\n callId: string;\n envelope: SealedEnvelope;\n }): Promise<\n | { callId: string; expiresAt: number; duplicate?: true }\n | { refused: ToolCallRefusal }\n > {\n const now = await this.now();\n const job = this.#grantFor(input.jobId, input.runnerId, input.leaseId);\n if (!job) return { refused: \"not-found\" };\n if (job.claimedBy?.runnerId !== input.runnerId) {\n return { refused: \"not-holder\" };\n }\n // Terminal before holder, as `complete` orders it: a finished or\n // withdrawn job makes no more calls, whoever is asking.\n if (job.state === \"done\" || job.cancelled === true) {\n return { refused: \"terminal\" };\n }\n if (job.claimedBy.leaseId !== input.leaseId) {\n return { refused: \"stale-lease\" };\n }\n // A call is made by a device that has its payload. Before that it is a\n // daemon calling tools for a prompt it has not read.\n if (job.state !== \"running\") return { refused: \"not-ready\" };\n if (job.stub.kind !== \"llm.tools\") return { refused: \"not-tools\" };\n\n const calls = job.toolCalls ?? [];\n const known = calls.find((call) => call.callId === input.callId);\n if (known) {\n // A replayed request is the call it replays — byollm_009 §4.2's\n // argument for signed requests needs every write idempotent per the\n // instance it names, and this one must not be counted twice.\n return sameEnvelope(known.envelope, input.envelope)\n ? { callId: known.callId, expiresAt: known.expiresAt, duplicate: true }\n : { refused: \"call-conflict\" };\n }\n const limit = job.maxToolCalls ?? TOOL_LIMITS.maxToolCalls;\n if ((job.toolCallsMade ?? 0) >= limit) return { refused: \"budget\" };\n\n const row: ToolCallRow = {\n callId: input.callId,\n leaseId: input.leaseId,\n envelope: input.envelope,\n expiresAt: now + TOOL_LIMITS.callTimeoutMs,\n };\n job.toolCalls = [...calls, row];\n job.toolCallsMade = (job.toolCallsMade ?? 0) + 1;\n return { callId: row.callId, expiresAt: row.expiresAt };\n }\n\n /**\n * {@link RoutingStore.toolCalls} — what is waiting on this site.\n *\n * Outstanding only: the current grant's, unanswered, inside the timeout.\n * A call that timed out is gone from here because the daemon has already\n * told the model the site did not answer, and running the tool now would\n * spend the site's tools on an answer nobody will read.\n */\n async toolCalls(siteId: string): Promise<OutstandingToolCall[]> {\n const now = await this.now();\n const out: OutstandingToolCall[] = [];\n for (const job of this.#jobs.values()) {\n if (job.siteId !== siteId || job.state !== \"running\") continue;\n const held = job.claimedBy;\n if (!held || job.cancelled === true) continue;\n for (const call of job.toolCalls ?? []) {\n if (call.leaseId !== held.leaseId) continue;\n if (call.result !== undefined || call.expiresAt <= now) continue;\n out.push({\n jobId: job.id,\n leaseId: call.leaseId,\n callId: call.callId,\n envelope: call.envelope,\n device: held.device,\n expiresAt: call.expiresAt,\n });\n }\n }\n return out;\n }\n\n /**\n * {@link RoutingStore.answerToolCall} — a site's sealed answer, bound to\n * its call (`TOOL_ENVELOPES_BOUND`, the relay's half).\n *\n * Found by **(site, job, call)**, so a result posted for job A can only\n * ever land on a call of job A: another job's call id is not found here,\n * and so is a call of A's that belonged to a grant that has ended. The\n * daemon holds the other half — it opens the envelope and checks the job\n * and the call inside the signature.\n */\n async answerToolCall(input: {\n siteId: string;\n jobId: string;\n callId: string;\n envelope: SealedEnvelope;\n }): Promise<{ accepted: true } | { refused: \"not-found\" | \"too-late\" }> {\n const now = await this.now();\n const job = this.#jobs.get(keyOf(input.siteId, input.jobId));\n if (job?.siteId !== input.siteId) return { refused: \"not-found\" };\n const lease = job.claimedBy?.leaseId;\n const call = (job.toolCalls ?? []).find(\n (row) => row.callId === input.callId && row.leaseId === lease,\n );\n if (!call) return { refused: \"not-found\" };\n if (call.result !== undefined) {\n // The same answer again is the replay of a signed write; a different\n // one is a second answer to a call that already has one.\n return sameEnvelope(call.result, input.envelope)\n ? { accepted: true }\n : { refused: \"too-late\" };\n }\n if (call.expiresAt <= now || job.state !== \"running\") {\n return { refused: \"too-late\" };\n }\n call.result = input.envelope;\n return { accepted: true };\n }\n\n /**\n * {@link RoutingStore.toolResults} — answers, to the holder that asked.\n *\n * Each named call is looked up through the caller's grant, exactly as\n * `takePayload` looks up a job: the lease must be current and held by this\n * runner, and the call must have been made under it. Anything else is\n * absent rather than refused, so a poll tells a stranger nothing.\n */\n toolResults(input: {\n runnerId: string;\n calls: readonly { jobId: string; leaseId: string; callId: string }[];\n }): Promise<\n {\n jobId: string;\n leaseId: string;\n callId: string;\n envelope: SealedEnvelope;\n }[]\n > {\n const out: {\n jobId: string;\n leaseId: string;\n callId: string;\n envelope: SealedEnvelope;\n }[] = [];\n for (const ref of input.calls) {\n const job = this.#grantFor(ref.jobId, input.runnerId, ref.leaseId);\n const held = job?.claimedBy;\n if (\n !job ||\n held?.runnerId !== input.runnerId ||\n held.leaseId !== ref.leaseId\n ) {\n continue;\n }\n const call = (job.toolCalls ?? []).find(\n (row) => row.callId === ref.callId && row.leaseId === ref.leaseId,\n );\n if (call?.result === undefined) continue;\n out.push({\n jobId: job.id,\n leaseId: call.leaseId,\n callId: call.callId,\n envelope: call.result,\n });\n }\n return Promise.resolve(out);\n }\n\n async seen(presence: Omit<Presence, \"lastSeenAt\">): Promise<Presence> {\n const lastSeenAt = await this.now();\n const existing = this.#presence.get(presence.runnerId);\n if (existing) {\n existing.lastSeenAt = lastSeenAt;\n // Refreshed, not merged. The heartbeat re-sends the whole matrix every\n // time precisely so a server never matches against a stale one, and a\n // record that kept the union would keep advertising a backend the\n // machine has since lost — which is worse than forgetting one it still\n // has, because work would route to it.\n existing.capabilities = presence.capabilities;\n // Refreshed for the same reason and in the same breath: a kind that\n // stopped being contended — because the owner chose a default, or one\n // service went away — must stop being reported as withheld, or the page\n // keeps asking for a decision that has already been made.\n existing.withheld = presence.withheld;\n return existing;\n }\n const fresh: Presence = { ...presence, lastSeenAt };\n this.#presence.set(presence.runnerId, fresh);\n return fresh;\n }\n\n presence(runnerId: string): Promise<Presence | undefined> {\n return Promise.resolve(this.#presence.get(runnerId));\n }\n\n /**\n * Lose a record, the way a real store does.\n *\n * A shared store drops presence for reasons this one never will — a TTL, a\n * reschedule, a restart — and the interesting behaviour is what the relay\n * does next. `ValkeyRoutingStore` has carried the same helper since\n * finding 52; this is its memory twin, so the case can be written once\n * against the implementation that is easy to reason about.\n */\n dropPresenceForTests(runnerId: string): Promise<void> {\n this.#presence.delete(runnerId);\n return Promise.resolve();\n }\n\n everyone(): Promise<Presence[]> {\n return Promise.resolve([...this.#presence.values()]);\n }\n\n /**\n * Return a job to the queue, forgetting the claim.\n *\n * The stub survives; nothing is lost. That is `LEASE_RECLAIMABLE` and it is\n * why the awaiting-payload timeout is cheap to fire: the worst case is that\n * a device did nothing for ten seconds and another one gets a turn.\n */\n #requeue(job: RoutedJob): void {\n job.state = \"queued\";\n // The grant ended; the index that names it must end with it, or a stale\n // lease id resolves to a job it no longer holds.\n if (job.claimedBy) this.#byLease.delete(job.claimedBy.leaseId);\n delete job.claimedBy;\n delete job.awaitingUntil;\n delete job.payload;\n /* The grant's calls end with the grant. `toolCallsMade` deliberately\n stays: it is the job's budget, not the grant's (see its docstring). */\n delete job.toolCalls;\n /* `sealAttempts` is deliberately NOT cleared. It counts how many devices\n have waited on this job, and a requeue is exactly the event it counts —\n clearing it here would reset the counter on every tick and the job\n would be handed round forever, which is the bug B042 is about. */\n }\n\n /**\n * Fire whatever the clock says is due, and report it.\n *\n * Returns the jobs it requeued so a caller can log or surface them — a\n * timeout that fires invisibly is indistinguishable from a job that was\n * never claimed, and those want very different debugging.\n */\n async sweep(): Promise<RoutedJob[]> {\n const now = await this.now();\n const requeued: RoutedJob[] = [];\n const expired: RoutedJob[] = [];\n for (const job of this.#jobs.values()) {\n // Past its deadline — cloud_008 §2.2, and `TTL_EXPIRY` on this plane.\n //\n // The relay never read `stub.deadlineAt`. Not \"read it and got the\n // arithmetic wrong\": the field travelled on every stub, byollm_009 §6\n // describes it as the bound on how long a ciphertext is worth carrying,\n // and nothing here ever looked at it. A job whose deadline passed went\n // on being offered to devices forever, and its sealed payload sat in\n // the relay for as long as the process lived.\n //\n // Dropped rather than marked terminal. The relay is a router and the\n // site holds the authoritative record; a stub nobody may run is not\n // routing state, and keeping a tombstone would be keeping the ciphertext\n // with it. A daemon mid-flight learns through `renewLeases`, which\n // reports a job the store no longer holds as `lost` — the path that\n // already exists for a lease that ended.\n if (job.stub.deadlineAt <= now) {\n this.#forget(job);\n expired.push(job);\n continue;\n }\n if (job.state === \"awaiting-payload\" && (job.awaitingUntil ?? 0) <= now) {\n /**\n * Counted before it is requeued, and evicted once the count is spent\n * — B042.\n *\n * The requeue is what makes this a fleet-wide problem rather than\n * one device's: it puts the job back for somebody else to wait on.\n * After three that is no longer patience, it is a queue handing the\n * same dead job around.\n */\n /* A grant this pair took and did not seal — B187's signature. */\n this.#noteChurn(job.siteId, job.stub.owner, now);\n /* And from here it is that device's job or nobody's — the sticky\n re-offer. Set before the requeue, which clears `claimedBy`. */\n const abandonedBy = job.claimedBy?.runnerId;\n if (abandonedBy !== undefined) job.reofferTo ??= abandonedBy;\n const attempts = (job.sealAttempts ?? 0) + 1;\n if (attempts >= SEAL_ATTEMPTS_BEFORE_EVICTION) {\n this.#forget(job);\n expired.push(job);\n continue;\n }\n job.sealAttempts = attempts;\n this.#requeue(job);\n requeued.push(job);\n }\n const lease = job.claimedBy;\n if (\n lease &&\n (job.state === \"ready\" || job.state === \"running\") &&\n lease.leaseExpiresAt <= now\n ) {\n this.#requeue(job);\n requeued.push(job);\n }\n }\n // Both, because a caller that logs \"requeued\" and never mentions expiry\n // would report a shrinking queue with no reason for it.\n return [...requeued, ...expired];\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,OAOK;AACP,SAAS,kBAAkB;AAmDpB,IAAM,sBAAsB;AAuC5B,IAAM,oBAAoB;AAE1B,IAAM,gCAAgC;AAyBtC,IAAM,iBAAiB;AAmLvB,SAAS,WACd,KACA,KAC6B;AAC7B,MAAI,IAAI,UAAU,UAAW,QAAO;AACpC,QAAM,QAAQ,IAAI,WAAW;AAC7B,QAAM,WAAW,IAAI,aAAa,CAAC,GAAG;AAAA,IACpC,CAAC,SACC,KAAK,YAAY,SACjB,KAAK,WAAW,UAChB,KAAK,YAAY;AAAA,EACrB;AACA,SAAO,UAAU,oBAAoB;AACvC;AAuBA,IAAM,eAAe,CAAC,GAAmB,MACvC,KAAK,UAAU,CAAC,MAAM,KAAK,UAAU,CAAC;AAuIjC,IAAM,WAAW,CAAC,QAAgB,UACvC,GAAG,MAAM,KAAS,KAAK;AAyClB,IAAM,iBAAiB;AACvB,IAAM,k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