@byollm/relay 0.1.0-alpha.9 → 0.1.0-alpha.90

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.
@@ -0,0 +1,687 @@
1
+ import { PublicIdentity, CapabilityMatrix, WithheldKind, JobStub, SealedEnvelope, ClaimedStub } from '@byollm/protocol';
2
+
3
+ /**
4
+ * The relay's routing state — byollm_009 §7, reachable at last.
5
+ *
6
+ * §7 described a state machine the direct plane could not produce. There, the
7
+ * site and the upstream are the same party: it seals when it likes, and a job
8
+ * is never claimed-but-unsealed. Here they are different parties, and the gap
9
+ * between them is a state:
10
+ *
11
+ * ```
12
+ * queued ──claim──▶ awaiting-payload ──sealed──▶ ready ──fetch──▶ running
13
+ * ▲ │ │
14
+ * └────────────────────┘ ▼
15
+ * site never seals, or seals too late ok | error | canceled
16
+ * ```
17
+ *
18
+ * The relay cannot seal, so it cannot shortcut this. A payload is encrypted
19
+ * to *the device that claimed it*, and nobody knows which device that is until
20
+ * the claim happens — which is precisely why claim-then-fetch makes a blind
21
+ * relay possible at all. The window is the price.
22
+ *
23
+ * ## What the relay holds, and what it cannot
24
+ *
25
+ * Stubs (metadata the site chose to publish), sealed envelopes it cannot open,
26
+ * and public keys. There is no field on any type in this file that could hold
27
+ * a private key or a plaintext, which is `RELAY_BLIND` expressed as a data
28
+ * model rather than as a policy.
29
+ */
30
+ /** Where a routed job is. */
31
+ type RoutedState = "queued" | "awaiting-payload" | "ready" | "running" | "done";
32
+ /**
33
+ * How long a site has to seal after one of its jobs is claimed.
34
+ *
35
+ * **Distinct from the lease, and distinct from the job's TTL** — byollm_009
36
+ * §7.1. Three clocks, three different questions:
37
+ *
38
+ * - the **TTL** asks how long the work is worth doing at all;
39
+ * - the **lease** asks how long this device gets to run it;
40
+ * - this asks how long we wait for a site that has gone away.
41
+ *
42
+ * Collapsing any pair of them looks harmless until a site restarts during a
43
+ * deploy: with only a lease, the device sits politely holding a job whose
44
+ * payload will never arrive, and the lease's whole minute is spent waiting on
45
+ * a party that is not coming back. Short, because a site that is up answers in
46
+ * milliseconds and a site that is down will not answer sooner for waiting.
47
+ */
48
+ declare const AWAITING_PAYLOAD_MS = 10000;
49
+ /**
50
+ * How many devices wait for a payload before the hub gives up on the job —
51
+ * B042.
52
+ *
53
+ * Three, matching the daemon's own patience, and for the same reason: a site
54
+ * that is slow, restarting, or briefly unreachable deserves more than one
55
+ * chance, and a site that is gone should not cost the whole fleet a turn
56
+ * each. At {@link AWAITING_PAYLOAD_MS} apiece this is thirty seconds of
57
+ * waiting before a job that nobody can complete is dropped.
58
+ *
59
+ * Dropped rather than marked terminal, exactly as a passed deadline is: the
60
+ * relay is a router, the site holds the authoritative record, and a stub
61
+ * nobody may run is not routing state. A daemon mid-flight learns through
62
+ * `renewLeases`, which reports a job the store no longer holds as `lost`.
63
+ */
64
+ declare const SEAL_ATTEMPTS_BEFORE_EVICTION = 3;
65
+ /** A job the relay is routing. Metadata and ciphertext, nothing else. */
66
+ /** Why a daemon gave a job back. Only `refused` means "not me, ever". */
67
+ type ReleaseReason = "shutdown" | "pause" | "revoked" | "backend-down" | "refused";
68
+ interface RoutedJob {
69
+ readonly id: string;
70
+ /** Which site enqueued it — the party that will be asked to seal. */
71
+ readonly siteId: string;
72
+ /**
73
+ * Everything the relay knows about the work, which is everything the site
74
+ * chose to publish and not one field more (byollm_009 §6).
75
+ */
76
+ readonly stub: JobStub;
77
+ state: RoutedState;
78
+ /** Set from the claim; the site seals to these keys. */
79
+ claimedBy?: {
80
+ readonly runnerId: string;
81
+ readonly owner: string;
82
+ readonly device: PublicIdentity;
83
+ readonly leaseId: string;
84
+ readonly leaseExpiresAt: number;
85
+ };
86
+ /** When {@link AWAITING_PAYLOAD_MS} runs out for this claim. */
87
+ awaitingUntil?: number;
88
+ /**
89
+ * How many devices have waited for this payload and not received it — B042.
90
+ *
91
+ * A job whose site never seals is offered, waited on, requeued, and offered
92
+ * again — to a different device each time. Every one of them does the same
93
+ * ten seconds of nothing, and none of them can tell that the last one
94
+ * already tried: the daemon's own patience is per-device by construction,
95
+ * so the fleet works through itself one machine at a time until the job's
96
+ * deadline, which can be an hour away.
97
+ *
98
+ * That is the poison at its source. **The daemon-side breaker (B041) stops
99
+ * one device looping; only the hub can stop the job.** Counted here rather
100
+ * than inferred from `awaitingUntil`, because a requeue clears that clock
101
+ * and the count has to survive it.
102
+ */
103
+ sealAttempts?: number;
104
+ /**
105
+ * Runners that released this job with reason `refused` — cloud_008 §2.1.
106
+ *
107
+ * `REFUSAL_NOT_REOFFERED`, which the relay did not implement: it dropped
108
+ * `ReleaseRequest.reason` on the floor. The field's own docstring says why
109
+ * that is not cosmetic — an upstream cannot evaluate a daemon's *local*
110
+ * `named` allowlist, so it may legitimately offer work the daemon then
111
+ * declines, and without a record the two spin between claim and release
112
+ * forever. The direct plane has always kept this list.
113
+ */
114
+ refusedBy: string[];
115
+ /**
116
+ * Runners that may not be offered this job again *yet*, and from when.
117
+ *
118
+ * The middle ground {@link RoutingStore.releaseLeases} had no way to say.
119
+ * `refusedBy` is forever and a bare release is immediate; a control plane
120
+ * declining a job for a reason the world can change — an unfilled mapping
121
+ * slot, a resolution that named another machine, a store that was briefly
122
+ * unreachable — means neither. It means "ask again later", and later needs
123
+ * a number.
124
+ *
125
+ * Keyed by runner because it is a fact about a pairing, not about the job:
126
+ * the same job goes to another device immediately, which is the whole
127
+ * point of not marking it refused.
128
+ */
129
+ retryAfter?: Record<string, number>;
130
+ /**
131
+ * The site withdrew this job — cloud_008 §2.2.
132
+ *
133
+ * A flag rather than a state, because a cancelled job that a device is
134
+ * *running* is not finished: the daemon has to be told, abort its backend
135
+ * call and report `canceled`, and the ordinary `complete` path then closes
136
+ * it. Making it a state would strand the in-flight case between two
137
+ * machines' ideas of what happened.
138
+ */
139
+ cancelled?: boolean;
140
+ /** Sealed to the claiming device by the site. Opaque here. */
141
+ payload?: SealedEnvelope;
142
+ /** Sealed to the site by the device. Opaque here. */
143
+ result?: SealedEnvelope;
144
+ /**
145
+ * The result's clear-text discriminator — byollm_009 §6.1.
146
+ *
147
+ * The one outcome fact the relay is given, and the reason it is given:
148
+ * without it the relay cannot stop dispatching a finished job. A routing
149
+ * hint and never a fact — the *site* verifies it against the sealed
150
+ * outcome, because only the site can open the envelope. The relay acts on
151
+ * it and is entitled to be wrong; a lying daemon costs it a dispatch
152
+ * decision, not a security property.
153
+ */
154
+ disposition?: "ok" | "error" | "canceled";
155
+ }
156
+ /** A device the relay has seen recently. */
157
+ interface Presence {
158
+ readonly runnerId: string;
159
+ readonly owner: string;
160
+ readonly device: PublicIdentity;
161
+ lastSeenAt: number;
162
+ /**
163
+ * What this machine last said it can run — cloud_009, 2026-08-24.
164
+ *
165
+ * **Capabilities are presence data.** They arrive on the same heartbeat as
166
+ * everything else here, they go stale at the same moment and for the same
167
+ * reason, and a machine that stops heartbeating has not stopped being able
168
+ * to run Llama — it has stopped being somewhere we can ask. Keeping them
169
+ * anywhere else would put capability truth outside the interface that owns
170
+ * presence, and every next consumer (a member's usable set, a dashboard's
171
+ * pulse, a degraded-state banner) would re-derive it from a different
172
+ * place. That is the two-owners shape this codebase keeps paying for.
173
+ *
174
+ * Empty is a real answer, not a missing one: it is a paired machine with no
175
+ * healthy backend, which is a legal state the whole connect-first ruling
176
+ * exists to make visible rather than refuse.
177
+ */
178
+ capabilities: CapabilityMatrix;
179
+ /**
180
+ * Kinds this machine is deliberately *not* advertising — byollm_016.
181
+ *
182
+ * Presence data for the same reason capabilities are, and stored beside
183
+ * them rather than derived: two services answering one kind with no
184
+ * `defaults` entry is a state only the daemon can see, and the hub cannot
185
+ * reconstruct it from the matrix — an absent kind and a withheld kind look
186
+ * identical there. Without this field the owner's page can say "nothing
187
+ * serves llm.generate", which is true and useless, instead of "two services
188
+ * answer it and you have not chosen", which is the sentence that ends with
189
+ * the owner doing something.
190
+ *
191
+ * Empty is the normal answer, and means every kind resolved.
192
+ */
193
+ withheld: readonly WithheldKind[];
194
+ }
195
+ /**
196
+ * What a routing store must do, expressed as operations — cloud_006 §3.2.
197
+ *
198
+ * Every method below is a **decision plus its write**, never a read the caller
199
+ * follows with a mutation. That is the whole point, and it is the difference
200
+ * between an interface a shared store can implement and one it cannot.
201
+ *
202
+ * `claim` is the specimen. It used to live in `DaemonPlane` as
203
+ * `jobs()` → filter → mutate, which is atomic for exactly one reason: Node is
204
+ * single-threaded and these Maps are local, so nothing runs between the read
205
+ * and the write. Neither survives a store on a network, and
206
+ * `packages/relay/test/two-replicas.test.ts` holds the resulting race as a
207
+ * failing assertion.
208
+ *
209
+ * So the rule for anything added here: **if a caller has to read, decide, and
210
+ * write back, the operation is in the wrong place.** Move the decision in.
211
+ *
212
+ * ## Why the projection does not come with it
213
+ *
214
+ * `claim` takes `owners: string[]` rather than a projection or a predicate.
215
+ * A closure cannot travel to Valkey, and the projection replicates for free
216
+ * from the control plane — so the caller collapses it with
217
+ * `Projection.ownersRunnableBy` and hands over data the store can match on.
218
+ * That keeps the store ignorant of consent, which is also what keeps it
219
+ * replaceable.
220
+ */
221
+ interface ClaimInput {
222
+ readonly runnerId: string;
223
+ readonly owner: string;
224
+ readonly device: PublicIdentity;
225
+ /**
226
+ * The (site, owner) pairs this device may run work for — cloud_009 §3.
227
+ *
228
+ * **One set of pairs, not a set of sites and a set of owners.** Consent
229
+ * binds a user to a site, so the two cannot travel separately: a device
230
+ * whose owner consented to site A, serving a roster member who consented
231
+ * to site B, would have every element of both sets and no consented route
232
+ * between them. Two sets multiply; consent does not.
233
+ *
234
+ * Built by {@link Projection.routesFor} and matched with {@link routeKey},
235
+ * so the relay and a store in another repository agree on the encoding by
236
+ * calling the same function rather than by both spelling it out.
237
+ *
238
+ * This is the collapse that lets a claim stay one operation: a predicate
239
+ * cannot travel to a store over a network, and a set can.
240
+ */
241
+ readonly routes: ReadonlySet<string>;
242
+ /**
243
+ * Kinds this device can run — and that is now the whole of the match.
244
+ *
245
+ * A relay routes by kind and by consent; **which service answers is not its
246
+ * question**. A job names a purpose, a person's mapping names a service,
247
+ * and a control plane joins them at claim. A relay that filtered on the
248
+ * service would need the mapping, which is the one thing it is not supposed
249
+ * to hold.
250
+ *
251
+ * This carried a companion, `serves`, holding the (kind, service) pairs a
252
+ * device advertised, so a job naming a service reached only a device with
253
+ * it. Sites stopped naming services (Amendment L) and the field became wire
254
+ * nothing read — so it is gone rather than left for a reader to infer
255
+ * meaning from.
256
+ *
257
+ * The cost is stated plainly: a job may be offered to a device whose owner
258
+ * admits the person but whose machine their mapping did not name. The
259
+ * control plane declines it as not-here and it goes back with a
260
+ * {@link RETRY_AFTER_MS} wait, which is what that mechanism is for.
261
+ */
262
+ readonly kinds: ReadonlySet<string>;
263
+ readonly max: number;
264
+ readonly leaseMs: number;
265
+ }
266
+ /**
267
+ * How a (site, owner) route is written, so two implementations agree.
268
+ *
269
+ * The same `\u0000` the job key uses, for the same reason: it cannot appear
270
+ * in a site id or an owner id, so this is a key rather than a parser.
271
+ */
272
+ declare const routeKey: (siteId: string, owner: string) => string;
273
+ /**
274
+ * Where the store's sense of time comes from — cloud_006 §3.4.
275
+ *
276
+ * **The store owns its clock; callers do not pass one.** Every deadline the
277
+ * relay decides — a lease's expiry, the `awaiting-payload` window, what a
278
+ * sweep considers due — is now stamped by one source, and it is the same
279
+ * source that will later stamp them for every replica.
280
+ *
281
+ * It used to be a parameter. `claim` took `now`, `sweep` took `now`, and each
282
+ * plane called its own `now()` before calling in — which is fine in one
283
+ * process and is the recurring bug the moment there are two. A lease granted
284
+ * by a pod whose clock runs fast is short; the same lease swept by a pod whose
285
+ * clock runs slow outlives it. Nobody is wrong and the lease has no length.
286
+ *
287
+ * A Valkey-backed store returns `TIME` here, so the deadline and the sweep
288
+ * that enforces it are read from the same server. The injected clock stays for
289
+ * tests, which is what lets them move time instead of sleeping.
290
+ *
291
+ * **What deliberately does not use this**: request-signature freshness. That
292
+ * is checked against the *local* clock on purpose — it is a question about the
293
+ * caller's clock versus this process's, `MAX_CLOCK_SKEW_MS` already tolerates
294
+ * two minutes of disagreement, and a network round trip to timestamp every
295
+ * inbound request would be a cost with no property behind it.
296
+ */
297
+ interface RelayStateOptions {
298
+ readonly now?: () => number | Promise<number>;
299
+ }
300
+ /** Why a lease-scoped operation was refused, in the caller's vocabulary. */
301
+ type HolderRefusal = "not-found" | "not-holder" | "stale-lease" | "not-ready"
302
+ /** The job already ended — V1-6. A replay must not reopen it. */
303
+ | "terminal";
304
+ declare class RelayState implements RoutingStore {
305
+ #private;
306
+ constructor(options?: RelayStateOptions);
307
+ /** The one clock every deadline in this store is stamped from. */
308
+ now(): Promise<number>;
309
+ /**
310
+ * Take a stub for routing. The payload is not here and will not be.
311
+ *
312
+ * **Idempotent by job id, and that is a security property rather than a
313
+ * convenience.** Site-plane calls are authenticated by signature, and
314
+ * byollm_009 §4.2's argument for signing the request instead of a
315
+ * server-issued nonce rests entirely on every write being idempotent per the
316
+ * instance it names. This one was not: re-enqueueing a known id built a
317
+ * fresh `queued` job over the top of the old one, discarding a live claim,
318
+ * its lease and any payload the site had already sealed to a device. A
319
+ * replayed enqueue inside the two-minute freshness window was therefore a
320
+ * way to yank a job back from the machine running it — the `release` bug of
321
+ * §4.2, rediscovered on the other plane.
322
+ *
323
+ * So a known id returns what is already routing, unchanged. A site that
324
+ * restarts and republishes its queue is the normal case, and it must not
325
+ * disturb work in flight.
326
+ */
327
+ enqueue(input: {
328
+ id: string;
329
+ siteId: string;
330
+ stub: JobStub;
331
+ }): Promise<RoutedJob>;
332
+ job(siteId: string, jobId: string): Promise<RoutedJob | undefined>;
333
+ jobs(): Promise<RoutedJob[]>;
334
+ /** Jobs a site must seal for, right now. */
335
+ awaiting(siteId: string): Promise<RoutedJob[]>;
336
+ /** Sealed results waiting to go home. */
337
+ finished(siteId: string): Promise<RoutedJob[]>;
338
+ /**
339
+ * Claim work — one operation, because it has to be.
340
+ *
341
+ * Moved here wholesale from `DaemonPlane`, where it was a scan followed by
342
+ * per-job mutation. Nothing about the *decision* changed; what changed is
343
+ * that a store can now implement it, because the filter and the write are
344
+ * one call rather than a loop the caller drives.
345
+ *
346
+ * The order of the guards is worth preserving as-is when this becomes a Lua
347
+ * script: cheapest first, and `owners` last because it is the only one that
348
+ * needed the projection.
349
+ */
350
+ claim(input: ClaimInput): Promise<ClaimedStub[]>;
351
+ /**
352
+ * Hand over the sealed payload to the device that holds the lease.
353
+ *
354
+ * The read and the state transition are one operation for the same reason
355
+ * `claim` is: `running` must be set by whoever was told the envelope, or two
356
+ * replicas can both hand out the same work and both believe they were first.
357
+ */
358
+ takePayload(input: {
359
+ jobId: string;
360
+ runnerId: string;
361
+ leaseId: string;
362
+ }): Promise<{
363
+ envelope: SealedEnvelope;
364
+ } | {
365
+ refused: HolderRefusal;
366
+ }>;
367
+ /**
368
+ * Record a finished job.
369
+ *
370
+ * `RESULT_IDEMPOTENT` lives here rather than in the caller: a replayed
371
+ * result must be a no-op decided by the same operation that would have
372
+ * written it, or two replicas can both decide they were the first.
373
+ */
374
+ complete(input: {
375
+ jobId: string;
376
+ runnerId: string;
377
+ leaseId: string;
378
+ envelope: SealedEnvelope;
379
+ disposition: "ok" | "error" | "canceled";
380
+ }): Promise<{
381
+ accepted: boolean;
382
+ duplicate?: boolean;
383
+ state: RoutedState;
384
+ } | {
385
+ refused: HolderRefusal;
386
+ }>;
387
+ /** Give back leases this runner holds, naming each grant it means. */
388
+ releaseLeases(input: {
389
+ runnerId: string;
390
+ leases: readonly {
391
+ jobId: string;
392
+ leaseId: string;
393
+ }[];
394
+ reason?: ReleaseReason;
395
+ retryAfter?: number;
396
+ }): Promise<string[]>;
397
+ /**
398
+ * Take a site's sealed payload for a claimed job.
399
+ *
400
+ * Refuses anything not `awaiting-payload`, which is what makes the timeout
401
+ * mean something: a late seal must not land on a claim that has moved.
402
+ */
403
+ seal(input: {
404
+ jobId: string;
405
+ siteId: string;
406
+ envelope: SealedEnvelope;
407
+ }): Promise<{
408
+ state: RoutedState;
409
+ } | {
410
+ refused: "not-found" | "too-late";
411
+ was?: RoutedState;
412
+ }>;
413
+ /** {@link RoutingStore.cancel} — the site withdraws a job. */
414
+ cancel(input: {
415
+ jobId: string;
416
+ siteId: string;
417
+ }): Promise<boolean>;
418
+ /** {@link RoutingStore.cancelRequests} — cancelled jobs this runner holds. */
419
+ cancelRequests(runnerId: string): Promise<Grant[]>;
420
+ /** {@link RoutingStore.renewLeases} — extend what is still held, name what is not. */
421
+ renewLeases(input: {
422
+ runnerId: string;
423
+ leases: readonly {
424
+ jobId: string;
425
+ leaseId: string;
426
+ }[];
427
+ leaseMs: number;
428
+ }): Promise<{
429
+ renewed: {
430
+ jobId: string;
431
+ expiresAt: number;
432
+ }[];
433
+ lost: Grant[];
434
+ }>;
435
+ seen(presence: Omit<Presence, "lastSeenAt">): Promise<Presence>;
436
+ presence(runnerId: string): Promise<Presence | undefined>;
437
+ /**
438
+ * Lose a record, the way a real store does.
439
+ *
440
+ * A shared store drops presence for reasons this one never will — a TTL, a
441
+ * reschedule, a restart — and the interesting behaviour is what the relay
442
+ * does next. `ValkeyRoutingStore` has carried the same helper since
443
+ * finding 52; this is its memory twin, so the case can be written once
444
+ * against the implementation that is easy to reason about.
445
+ */
446
+ dropPresenceForTests(runnerId: string): Promise<void>;
447
+ everyone(): Promise<Presence[]>;
448
+ /**
449
+ * Fire whatever the clock says is due, and report it.
450
+ *
451
+ * Returns the jobs it requeued so a caller can log or surface them — a
452
+ * timeout that fires invisibly is indistinguishable from a job that was
453
+ * never claimed, and those want very different debugging.
454
+ */
455
+ sweep(): Promise<RoutedJob[]>;
456
+ }
457
+
458
+ /**
459
+ * What the relay needs from a place to keep routing state — cloud_006 §3.2.
460
+ *
461
+ * `RelayState` implements this in memory and is the reference; a Valkey-backed
462
+ * store implements the same thing across replicas. The interface exists so the
463
+ * relay depends on the *contract* rather than on either, and so the properties
464
+ * below are stated once rather than rediscovered per implementation.
465
+ *
466
+ * ## Every method is a decision plus its write
467
+ *
468
+ * Not one is a read the caller follows with a mutation. That is the whole
469
+ * design, and it is not a style preference: `claim` used to be
470
+ * `jobs()` → filter → mutate in the plane, which is atomic for exactly one
471
+ * reason — Node is single-threaded and the Maps are local. Neither survives a
472
+ * store on a network, and `packages/relay/test/two-replicas.test.ts` holds the
473
+ * resulting race as a failing assertion.
474
+ *
475
+ * **The rule for anything added here:** if a caller has to read, decide, and
476
+ * write back, the operation is in the wrong place. Move the decision in.
477
+ *
478
+ * ## What an implementation must guarantee
479
+ *
480
+ * 1. **`claim` is atomic.** Two callers claiming concurrently must not both
481
+ * receive the same job. `CLAIM_ATOMIC` is a protocol MUST.
482
+ * 2. **`enqueue` is idempotent by job id.** A known id returns what is already
483
+ * routing rather than rebuilding it — byollm_009 §4.2's replay argument
484
+ * rests on every write being idempotent per the instance it names.
485
+ * 3. **`complete` is idempotent.** A replayed result changes nothing, and the
486
+ * decision is made by the same operation that would have written it.
487
+ * 4. **Lease-scoped operations name the grant.** `takePayload`, `complete` and
488
+ * `releaseLeases` check the lease *id*, not just the runner — a runner
489
+ * survives a claim-release-reclaim cycle and a grant does not.
490
+ * 5. **`now()` is the only clock.** Every deadline the store stamps and every
491
+ * deadline it enforces come from here (§3.4). An implementation backed by a
492
+ * server returns that server's time, so two replicas cannot disagree about
493
+ * how long a lease is.
494
+ *
495
+ * ## What it must not do
496
+ *
497
+ * Hold a key, or learn about consent. `claim` takes `owners` as data because a
498
+ * predicate cannot travel to Valkey — and the effect is that the store cannot
499
+ * express an opinion about who may route, only about what it was told. That is
500
+ * what keeps `RELAY_BLIND` a property of the shape rather than of the code.
501
+ */
502
+ /**
503
+ * One grant, named by both halves — V1-3.
504
+ *
505
+ * A job id is chosen per site, so two sites can pick the same one; the lease
506
+ * id is the unique thing an upstream and a daemon can both point at. Anywhere
507
+ * this store says "this piece of work, held by you", it says it with both.
508
+ */
509
+ interface Grant {
510
+ readonly jobId: string;
511
+ readonly leaseId: string;
512
+ }
513
+ interface RoutingStore {
514
+ /** The one clock every deadline in this store is stamped from. */
515
+ now(): Promise<number>;
516
+ /**
517
+ * Take a stub for routing. Idempotent by id, **within a site**.
518
+ *
519
+ * A republished id belonging to the same site returns what is already
520
+ * routing, unchanged: a site that restarts and republishes its queue must
521
+ * not disturb work in flight (byollm_009 §4.2's replay argument rests on
522
+ * it).
523
+ *
524
+ * A republished id belonging to a **different** site is a different job —
525
+ * cloud_009 §3. Keys are `(site, id)`, so two sites choosing one id collide
526
+ * nowhere and there is nothing to refuse.
527
+ *
528
+ * cloud_008 finding 58 closed this by refusing the collision, which was as
529
+ * far as a single-site relay could go and left a cross-tenant existence
530
+ * oracle: a site knows its own stub is well-formed, so any answer it can
531
+ * tell apart from success confirms that somebody else holds that id. The
532
+ * refusal is gone with the collision.
533
+ */
534
+ enqueue(input: {
535
+ id: string;
536
+ siteId: string;
537
+ stub: JobStub;
538
+ }): Promise<RoutedJob>;
539
+ /**
540
+ * One job, named by the site that published it — cloud_009 §3.
541
+ *
542
+ * The site id is a parameter rather than a scan, and the difference is
543
+ * finding eleven wearing a different hat: a reader that finds a job by id
544
+ * alone is a reader that can see every tenant's state through one door,
545
+ * which is exactly the anonymous read the debug page had and lost. The
546
+ * debug page is per-site or it is nothing.
547
+ */
548
+ job(siteId: string, jobId: string): Promise<RoutedJob | undefined>;
549
+ jobs(): Promise<RoutedJob[]>;
550
+ /** Jobs a site must seal for, right now. */
551
+ awaiting(siteId: string): Promise<RoutedJob[]>;
552
+ /** Sealed results waiting to go home. */
553
+ finished(siteId: string): Promise<RoutedJob[]>;
554
+ /** Grant work to a device — one operation, because it has to be. */
555
+ claim(input: ClaimInput): Promise<ClaimedStub[]>;
556
+ /** Hand the sealed payload to the device that holds the lease. */
557
+ takePayload(input: {
558
+ jobId: string;
559
+ runnerId: string;
560
+ leaseId: string;
561
+ }): Promise<{
562
+ envelope: SealedEnvelope;
563
+ } | {
564
+ refused: HolderRefusal;
565
+ }>;
566
+ /** Record a finished job. Idempotent. */
567
+ complete(input: {
568
+ jobId: string;
569
+ runnerId: string;
570
+ /**
571
+ * The grant the result was produced under — cloud_008 §1.4a.
572
+ *
573
+ * `takePayload` and `releaseLeases` have always checked this and said why;
574
+ * the operation that *writes* checked only the runner, which survives a
575
+ * claim-release-reclaim cycle.
576
+ */
577
+ leaseId: string;
578
+ envelope: SealedEnvelope;
579
+ disposition: "ok" | "error" | "canceled";
580
+ }): Promise<{
581
+ accepted: boolean;
582
+ duplicate?: boolean;
583
+ state: RoutedState;
584
+ } | {
585
+ refused: HolderRefusal;
586
+ }>;
587
+ /** Give back the grants this runner names. */
588
+ releaseLeases(input: {
589
+ runnerId: string;
590
+ leases: readonly {
591
+ jobId: string;
592
+ leaseId: string;
593
+ }[];
594
+ /**
595
+ * Why — cloud_008 §2.1. `refused` MUST be remembered and that job MUST
596
+ * NOT be offered to that runner again (`REFUSAL_NOT_REOFFERED`); every
597
+ * other reason means "not now" and must leave the job claimable by the
598
+ * same device, or a restart would strand its own work.
599
+ */
600
+ reason?: ReleaseReason;
601
+ /**
602
+ * Epoch ms before which this job MUST NOT be offered to this runner
603
+ * again — the rate a transient refusal needs.
604
+ *
605
+ * "Not now" and "not ever" were the only two things a release could say,
606
+ * and a control plane declining a job for something the world can change
607
+ * means neither. Left immediate, the device re-claims at once and is
608
+ * declined again: a spin, and in a deployment one database read per turn
609
+ * of it.
610
+ *
611
+ * A store MUST NOT offer the job to that runner before this moment, and
612
+ * MUST go on offering it to every other device immediately — the whole
613
+ * reason it is not a refusal is that another machine may be the right
614
+ * one.
615
+ */
616
+ retryAfter?: number;
617
+ }): Promise<string[]>;
618
+ /** Take a site's sealed payload for a claimed job. */
619
+ seal(input: {
620
+ jobId: string;
621
+ siteId: string;
622
+ envelope: SealedEnvelope;
623
+ }): Promise<{
624
+ state: RoutedState;
625
+ } | {
626
+ refused: "not-found" | "too-late";
627
+ was?: RoutedState;
628
+ }>;
629
+ /**
630
+ * Extend the leases this runner still holds, and name the ones it does not.
631
+ *
632
+ * One call because it is one question — cloud_008 §0.6. This was
633
+ * `lostLeases`, which answered only the second half, and the relay's
634
+ * heartbeat answered the first half with the literal `leases: []`. A daemon
635
+ * was therefore told, every few seconds, that none of its work had been
636
+ * renewed; the sweep requeued at `leaseMs` regardless of how alive the
637
+ * device was, and any job that took longer than a lease was handed to
638
+ * somebody else while the first device was still running it. The direct
639
+ * plane has always renewed here (`handlers.ts` §3), so this was also the two
640
+ * upstreams disagreeing about a rule the daemon cannot see.
641
+ *
642
+ * Renewal and loss come from one read of one state: asked separately they
643
+ * are two answers to "who holds this now", and under two replicas they can
644
+ * differ.
645
+ */
646
+ renewLeases(input: {
647
+ runnerId: string;
648
+ leases: readonly {
649
+ jobId: string;
650
+ leaseId: string;
651
+ }[];
652
+ leaseMs: number;
653
+ }): Promise<{
654
+ renewed: readonly {
655
+ jobId: string;
656
+ expiresAt: number;
657
+ }[];
658
+ lost: readonly Grant[];
659
+ }>;
660
+ /**
661
+ * The site withdraws a job — cloud_008 §2.2.
662
+ *
663
+ * Returns false when the job is not this site's, which is the same scoping
664
+ * every other site-plane operation carries: a site must not cancel
665
+ * somebody else's work by guessing an id.
666
+ */
667
+ cancel(input: {
668
+ jobId: string;
669
+ siteId: string;
670
+ }): Promise<boolean>;
671
+ /**
672
+ * Cancelled jobs this runner is holding, for the heartbeat to report.
673
+ *
674
+ * The relay answered `cancel: []` unconditionally, so a site could not stop
675
+ * a job it had already withdrawn — a device went on running work whose
676
+ * result nobody would accept, on somebody's own machine, at their expense.
677
+ */
678
+ cancelRequests(runnerId: string): Promise<Grant[]>;
679
+ /** Record a device as present. The store stamps when. */
680
+ seen(presence: Omit<Presence, "lastSeenAt">): Promise<Presence>;
681
+ presence(runnerId: string): Promise<Presence | undefined>;
682
+ everyone(): Promise<Presence[]>;
683
+ /** Fire whatever the clock says is due, and report it. */
684
+ sweep(): Promise<RoutedJob[]>;
685
+ }
686
+
687
+ export { AWAITING_PAYLOAD_MS as A, type ClaimInput as C, type Grant as G, type HolderRefusal as H, type Presence as P, type RoutingStore as R, SEAL_ATTEMPTS_BEFORE_EVICTION as S, RelayState as a, type ReleaseReason as b, type RoutedJob as c, type RoutedState as d, routeKey as r };