@byollm/relay 0.1.5-beta.1 → 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/dist/index.js CHANGED
@@ -19,6 +19,10 @@ import {
19
19
 
20
20
  // src/daemon-plane.ts
21
21
  import {
22
+ BlobSlotRequest,
23
+ BlobSlotResponse,
24
+ BlobUrlRequest,
25
+ BlobUrlResponse,
22
26
  PairPollRequest,
23
27
  PairStartRequest,
24
28
  ClaimRequest,
@@ -42,7 +46,8 @@ import {
42
46
  checkDaemonFloor,
43
47
  UPGRADE_COMMAND,
44
48
  PublicIdentity,
45
- ERROR_STATUS as ERROR_STATUS2
49
+ ERROR_STATUS as ERROR_STATUS2,
50
+ isBlobObjectSize
46
51
  } from "@byollm/protocol";
47
52
  import { z } from "zod";
48
53
 
@@ -177,6 +182,7 @@ var fail = (status, error, message) => ({
177
182
  status,
178
183
  body: { error, message }
179
184
  });
185
+ var SLOT_SIZE_MESSAGE = "a slot is whole 256 KiB buckets plus 40 bytes, up to one image at the cap";
180
186
  var TOOL_CALL_REFUSALS = {
181
187
  ...REFUSALS,
182
188
  "not-tools": fail(400, "bad-request", "this job does not carry tools"),
@@ -551,6 +557,16 @@ var DaemonPlane = class {
551
557
  return this.#authed(auth, body, ResultRequest, async (request, device) => {
552
558
  const bytes = envelopeBytes(request.envelope);
553
559
  if (bytes > MAX_ENVELOPE_BYTES2) return tooLargeRefusal(bytes);
560
+ const blobs = this.#deps.blobs;
561
+ const job = blobs === void 0 ? void 0 : await this.#jobUnder(request.jobId, request.leaseId, device);
562
+ if (blobs !== void 0 && job !== void 0 && job.state !== "done" && job.stub.kind === "llm.image" && request.disposition === "ok") {
563
+ const fault = await blobs.outputFault({
564
+ siteId: job.siteId,
565
+ jobId: job.id,
566
+ leaseId: request.leaseId
567
+ });
568
+ if (fault !== null) return fail(400, "bad-request", fault);
569
+ }
554
570
  const recorded = await this.#deps.state.complete({
555
571
  jobId: request.jobId,
556
572
  runnerId: device.runnerId,
@@ -559,9 +575,130 @@ var DaemonPlane = class {
559
575
  disposition: request.disposition
560
576
  });
561
577
  if ("refused" in recorded) return REFUSALS[recorded.refused];
578
+ if (blobs !== void 0 && job !== void 0 && recorded.accepted) {
579
+ await blobs.resultAccepted(
580
+ { siteId: job.siteId, jobId: job.id },
581
+ request.disposition
582
+ ).catch(() => void 0);
583
+ }
562
584
  return ok(recorded);
563
585
  });
564
586
  }
587
+ // -- blobs — byollm_021 §2 ------------------------------------------------
588
+ /**
589
+ * The job this device is the claimant of under `leaseId`, in any state,
590
+ * or `undefined`.
591
+ *
592
+ * A blob request names a job and a lease and no site, and a job id is a
593
+ * site's to choose, so the job is looked for under each site this
594
+ * device's owner has consented to — the only sites whose work can be on
595
+ * this machine at all. Matched on the lease id, which this relay minted
596
+ * and which is unique across sites, and on the runner the signature
597
+ * proved. Read through `RoutingStore.job`, so a store needs nothing new.
598
+ */
599
+ async #jobUnder(jobId, leaseId, device) {
600
+ for (const site of this.#deps.projection.sitesFor(device.owner)) {
601
+ const job = await this.#deps.state.job(site.siteId, jobId);
602
+ if (job?.claimedBy?.runnerId === device.runnerId && job.claimedBy.leaseId === leaseId) {
603
+ return job;
604
+ }
605
+ }
606
+ return void 0;
607
+ }
608
+ /**
609
+ * The job this device holds *right now* under `leaseId`, or `undefined` —
610
+ * the lease scope both blob endpoints share
611
+ * ({@link MUSTS.LEASE_SCOPED_BY_GRANT}, C053).
612
+ *
613
+ * Held means: claimed by this runner under exactly this grant, the grant
614
+ * not yet expired on the store's clock, the payload collected (`running`),
615
+ * and the job neither finished nor withdrawn. A device that has not
616
+ * fetched its payload has no reference to ask about, and one whose grant
617
+ * ended has no business with the job's blobs.
618
+ */
619
+ async #held(jobId, leaseId, device) {
620
+ const job = await this.#jobUnder(jobId, leaseId, device);
621
+ if (job?.claimedBy === void 0 || job.state !== "running" || job.cancelled === true || job.claimedBy.leaseExpiresAt <= await this.#deps.state.now()) {
622
+ return void 0;
623
+ }
624
+ return job;
625
+ }
626
+ /**
627
+ * A download URL for one input blob of a job this device holds.
628
+ *
629
+ * **No lease, no URL.** One `not-found` for a lease that is not held, a
630
+ * blob that is not one of this job's stored inputs, and one that is not
631
+ * the size its slot was issued for — a caller without the lease learns
632
+ * nothing about which. The object is addressed by the site and the job
633
+ * the lease names, never by anything in the request but the blob id, so
634
+ * a lease on one job reaches no other job's blobs.
635
+ */
636
+ blobUrl(blobs, auth, body) {
637
+ return this.#authed(auth, body, BlobUrlRequest, async (request, device) => {
638
+ if (request.runnerId !== device.runnerId) {
639
+ return fail(403, "forbidden", "runner id does not match the key");
640
+ }
641
+ const job = await this.#held(request.jobId, request.leaseId, device);
642
+ const signed = job === void 0 ? null : await blobs.downloadUrl({
643
+ siteId: job.siteId,
644
+ jobId: job.id,
645
+ direction: "in",
646
+ blob: request.blob
647
+ });
648
+ if (signed === null) {
649
+ return fail(404, "not-found", "no such blob under a lease you hold");
650
+ }
651
+ return ok(BlobUrlResponse.parse(signed));
652
+ });
653
+ }
654
+ /**
655
+ * An upload slot for one output image of an `llm.image` job this device
656
+ * holds. Lease-scoped as {@link DaemonPlane.blobUrl} is, and at most
657
+ * `MAX_IMAGES_OUT` under one lease.
658
+ */
659
+ blobSlot(blobs, auth, body) {
660
+ return this.#authed(
661
+ auth,
662
+ body,
663
+ BlobSlotRequest,
664
+ async (request, device) => {
665
+ if (request.runnerId !== device.runnerId) {
666
+ return fail(403, "forbidden", "runner id does not match the key");
667
+ }
668
+ const job = await this.#held(request.jobId, request.leaseId, device);
669
+ if (job === void 0) {
670
+ return fail(404, "not-found", "no such lease on this job");
671
+ }
672
+ if (job.stub.kind !== "llm.image") {
673
+ return fail(
674
+ 400,
675
+ "bad-request",
676
+ "only an llm.image job uploads images"
677
+ );
678
+ }
679
+ if (!isBlobObjectSize(request.bytes)) {
680
+ return fail(400, "bad-request", SLOT_SIZE_MESSAGE);
681
+ }
682
+ const slot = await blobs.outputSlot(
683
+ {
684
+ siteId: job.siteId,
685
+ jobId: job.id,
686
+ leaseId: request.leaseId,
687
+ deadlineAt: job.stub.deadlineAt
688
+ },
689
+ request.bytes
690
+ );
691
+ if (slot === "full") {
692
+ return fail(
693
+ 400,
694
+ "bad-request",
695
+ "this lease has been issued every output slot an llm.image job may use"
696
+ );
697
+ }
698
+ return ok(BlobSlotResponse.parse(slot));
699
+ }
700
+ );
701
+ }
565
702
  /**
566
703
  * One sealed tool call, from the device holding the job — byollm_012 §5.2.
567
704
  *
@@ -735,6 +872,489 @@ var PairFixtureRequest = z.object({
735
872
  }).strict();
736
873
  var fingerprintOf = (identity) => keyId(identity.identity);
737
874
 
875
+ // src/blobs.ts
876
+ import { randomBytes as randomBytes2 } from "crypto";
877
+ import {
878
+ BLOB_NONCE_BYTES,
879
+ BLOB_PADDING_BYTES,
880
+ BLOB_TAG_BYTES,
881
+ BLOBS_KEPT_AFTER_DEADLINE_MS,
882
+ ENVELOPE_MAX_AGE_MS,
883
+ MAX_BLOB_OBJECT_BYTES,
884
+ MAX_IMAGES_IN,
885
+ MAX_IMAGES_OUT,
886
+ OUTPUT_KEPT_AFTER_COLLECTION_MS,
887
+ isBlobObjectSize as isBlobObjectSize2
888
+ } from "@byollm/protocol";
889
+ var BLOB_OBJECT_PREFIX = "blobs";
890
+ function segment(id) {
891
+ return /^[A-Za-z0-9_-]{1,200}$/.test(id) ? id : `~${Buffer.from(id, "utf8").toString("base64url")}`;
892
+ }
893
+ function unsegment(part) {
894
+ const id = part.startsWith("~") ? Buffer.from(part.slice(1), "base64url").toString("utf8") : part;
895
+ return id !== "" && segment(id) === part ? id : null;
896
+ }
897
+ function blobJobPrefix(job) {
898
+ return `${BLOB_OBJECT_PREFIX}/${segment(job.siteId)}/${segment(job.jobId)}/`;
899
+ }
900
+ function blobObjectName(address) {
901
+ if (slotBytesOf(address.blob) === null) {
902
+ throw new Error(
903
+ "a blob object is named only for a blob id this relay minted"
904
+ );
905
+ }
906
+ return `${blobJobPrefix(address)}${address.direction}/${address.blob}`;
907
+ }
908
+ function blobAddressOf(name) {
909
+ const [prefix, site, job, direction, blob, extra] = name.split("/");
910
+ if (prefix !== BLOB_OBJECT_PREFIX || site === void 0 || job === void 0 || direction !== "in" && direction !== "out" || blob === void 0 || extra !== void 0 || slotBytesOf(blob) === null) {
911
+ return null;
912
+ }
913
+ const siteId = unsegment(site);
914
+ const jobId = unsegment(job);
915
+ return siteId === null || jobId === null ? null : { siteId, jobId, direction, blob };
916
+ }
917
+ var ORPHAN_BLOB_AGE_MS = ENVELOPE_MAX_AGE_MS + BLOBS_KEPT_AFTER_DEADLINE_MS;
918
+ var BLOB_ID = /^[A-Za-z0-9_-]{22}([1-9][0-9]?)$/;
919
+ var BLOB_OVERHEAD_BYTES = BLOB_NONCE_BYTES + BLOB_TAG_BYTES;
920
+ function mintBlobId(bytes) {
921
+ if (!isBlobObjectSize2(bytes)) {
922
+ throw new Error("a slot is whole 256 KiB buckets plus 40 bytes");
923
+ }
924
+ const buckets = (bytes - BLOB_OVERHEAD_BYTES) / BLOB_PADDING_BYTES;
925
+ return `${randomBytes2(16).toString("base64url")}${String(buckets)}`;
926
+ }
927
+ function slotBytesOf(blob) {
928
+ const buckets = BLOB_ID.exec(blob)?.[1];
929
+ if (buckets === void 0) return null;
930
+ const bytes = Number(buckets) * BLOB_PADDING_BYTES + BLOB_OVERHEAD_BYTES;
931
+ return isBlobObjectSize2(bytes) ? bytes : null;
932
+ }
933
+ var ledgerKey = (siteId, jobId) => `${siteId}\0${jobId}`;
934
+ var MemoryBlobLedger = class {
935
+ #records = /* @__PURE__ */ new Map();
936
+ issue(input) {
937
+ const key = ledgerKey(input.siteId, input.jobId);
938
+ const record = this.#records.get(key);
939
+ const { slot } = input;
940
+ const displaced = (record?.slots ?? []).filter(
941
+ (other) => other.direction === slot.direction && other.leaseId !== slot.leaseId
942
+ );
943
+ const kept = (record?.slots ?? []).filter(
944
+ (other) => !displaced.includes(other)
945
+ );
946
+ const issued = kept.filter((other) => other.direction === slot.direction).length < input.max;
947
+ const slots = issued ? [...kept, slot] : kept;
948
+ if (slots.length === 0) {
949
+ this.#records.delete(key);
950
+ } else {
951
+ this.#records.set(key, {
952
+ siteId: input.siteId,
953
+ jobId: input.jobId,
954
+ deleteAt: input.deleteAt,
955
+ ...record,
956
+ slots
957
+ });
958
+ }
959
+ return Promise.resolve({ issued, displaced });
960
+ }
961
+ record(siteId, jobId) {
962
+ return Promise.resolve(this.#records.get(ledgerKey(siteId, jobId)));
963
+ }
964
+ bringForward(input) {
965
+ const key = ledgerKey(input.siteId, input.jobId);
966
+ const record = this.#records.get(key);
967
+ if (record === void 0) return Promise.resolve();
968
+ const outputDeleteAt = Math.min(
969
+ record.outputDeleteAt ?? Infinity,
970
+ input.outputDeleteAt ?? Infinity
971
+ );
972
+ this.#records.set(key, {
973
+ ...record,
974
+ deleteAt: Math.min(record.deleteAt, input.deleteAt ?? Infinity),
975
+ ...Number.isFinite(outputDeleteAt) ? { outputDeleteAt } : {}
976
+ });
977
+ return Promise.resolve();
978
+ }
979
+ drop(input) {
980
+ const key = ledgerKey(input.siteId, input.jobId);
981
+ const record = this.#records.get(key);
982
+ if (record === void 0) return Promise.resolve();
983
+ const slots = record.slots.filter(
984
+ (slot) => input.direction !== void 0 && slot.direction !== input.direction || input.blobs !== void 0 && !input.blobs.includes(slot.blob)
985
+ );
986
+ if (slots.length === 0) this.#records.delete(key);
987
+ else this.#records.set(key, { ...record, slots });
988
+ return Promise.resolve();
989
+ }
990
+ due(now) {
991
+ return Promise.resolve(
992
+ [...this.#records.values()].filter(
993
+ (record) => record.deleteAt <= now || (record.outputDeleteAt ?? Infinity) <= now
994
+ )
995
+ );
996
+ }
997
+ };
998
+ var MEMORY_BLOB_URL_TTL_MS = 15 * 6e4;
999
+ var MEMORY_BLOB_PATH = "/relay/blob-store/";
1000
+ var MemoryBlobStore = class {
1001
+ #objects = /* @__PURE__ */ new Map();
1002
+ #storedAt = /* @__PURE__ */ new Map();
1003
+ #urls = /* @__PURE__ */ new Map();
1004
+ #origin;
1005
+ #now;
1006
+ constructor(options) {
1007
+ this.#origin = options.origin.replace(/\/+$/, "");
1008
+ this.#now = options.now ?? Date.now;
1009
+ }
1010
+ #sign(name, method) {
1011
+ const now = this.#now();
1012
+ for (const [token2, grant] of this.#urls) {
1013
+ if (grant.expiresAt <= now) this.#urls.delete(token2);
1014
+ }
1015
+ const token = randomBytes2(24).toString("base64url");
1016
+ const expiresAt = now + MEMORY_BLOB_URL_TTL_MS;
1017
+ this.#urls.set(token, { name, method, expiresAt });
1018
+ return { url: `${this.#origin}${MEMORY_BLOB_PATH}${token}`, expiresAt };
1019
+ }
1020
+ slot(address, _bytes) {
1021
+ return Promise.resolve(this.#sign(blobObjectName(address), "PUT"));
1022
+ }
1023
+ url(address) {
1024
+ return Promise.resolve(this.#sign(blobObjectName(address), "GET"));
1025
+ }
1026
+ head(address) {
1027
+ return Promise.resolve(
1028
+ this.#objects.get(blobObjectName(address))?.length ?? null
1029
+ );
1030
+ }
1031
+ list(job) {
1032
+ const prefix = blobJobPrefix(job);
1033
+ const found = [];
1034
+ for (const name of this.#objects.keys()) {
1035
+ if (!name.startsWith(prefix)) continue;
1036
+ const [direction, blob, extra] = name.slice(prefix.length).split("/");
1037
+ if ((direction === "in" || direction === "out") && blob !== void 0 && extra === void 0) {
1038
+ found.push({ direction, blob });
1039
+ }
1040
+ }
1041
+ return Promise.resolve(found);
1042
+ }
1043
+ storedBefore(time) {
1044
+ const found = [];
1045
+ for (const [name, storedAt] of this.#storedAt) {
1046
+ const address = storedAt <= time ? blobAddressOf(name) : null;
1047
+ if (address !== null) found.push({ address, storedAt });
1048
+ }
1049
+ return Promise.resolve(found);
1050
+ }
1051
+ delete(address) {
1052
+ const name = blobObjectName(address);
1053
+ this.#objects.delete(name);
1054
+ this.#storedAt.delete(name);
1055
+ return Promise.resolve();
1056
+ }
1057
+ async serve(request) {
1058
+ const { pathname } = new URL(request.url);
1059
+ if (!pathname.startsWith(MEMORY_BLOB_PATH)) return void 0;
1060
+ const grant = this.#urls.get(pathname.slice(MEMORY_BLOB_PATH.length));
1061
+ if (grant === void 0 || grant.expiresAt <= this.#now() || grant.method !== request.method) {
1062
+ return new Response(null, { status: 403 });
1063
+ }
1064
+ if (grant.method === "GET") {
1065
+ const object = this.#objects.get(grant.name);
1066
+ if (object === void 0) return new Response(null, { status: 404 });
1067
+ return new Response(Buffer.from(object), {
1068
+ headers: { "content-type": "application/octet-stream" }
1069
+ });
1070
+ }
1071
+ if (this.#objects.has(grant.name)) {
1072
+ return new Response(null, { status: 409 });
1073
+ }
1074
+ const body = new Uint8Array(await request.arrayBuffer());
1075
+ if (body.length > MAX_BLOB_OBJECT_BYTES) {
1076
+ return new Response(null, { status: 413 });
1077
+ }
1078
+ this.#objects.set(grant.name, body);
1079
+ this.#storedAt.set(grant.name, this.#now());
1080
+ return new Response(null, { status: 200 });
1081
+ }
1082
+ /**
1083
+ * Every stored object, by name — for a test or an audit asserting what
1084
+ * this store holds ({@link MUSTS.BLOBS_SEALED}, C048). Not on
1085
+ * {@link BlobStore}: a relay never reads an object.
1086
+ */
1087
+ objects() {
1088
+ return this.#objects;
1089
+ }
1090
+ };
1091
+ var BlobStoreFailure = class extends Error {
1092
+ name = "BlobStoreFailure";
1093
+ constructor(cause) {
1094
+ super("the blob store could not answer", { cause });
1095
+ }
1096
+ };
1097
+ function guarded(target) {
1098
+ return new Proxy(target, {
1099
+ get(inner, property) {
1100
+ const value = Reflect.get(inner, property, inner);
1101
+ if (typeof value !== "function") return value;
1102
+ return async (...args) => {
1103
+ try {
1104
+ return await value.apply(
1105
+ inner,
1106
+ args
1107
+ );
1108
+ } catch (error) {
1109
+ throw new BlobStoreFailure(error);
1110
+ }
1111
+ };
1112
+ }
1113
+ });
1114
+ }
1115
+ var RelayBlobs = class {
1116
+ #store;
1117
+ #ledger;
1118
+ #now;
1119
+ constructor(deps) {
1120
+ this.#store = guarded(deps.store);
1121
+ this.#ledger = guarded(deps.ledger);
1122
+ this.#now = deps.now;
1123
+ }
1124
+ /** {@link BlobStore.serve}, when the store serves its own URLs. */
1125
+ async serve(request) {
1126
+ return this.#store.serve?.(request);
1127
+ }
1128
+ /**
1129
+ * An upload slot for one input of a job its site has not enqueued yet.
1130
+ *
1131
+ * `full` once the job has every input slot an `llm.vision` job may use.
1132
+ * Until the enqueue names a deadline the slot is bounded by the oldest an
1133
+ * envelope may be: past that nothing could open the job it is for.
1134
+ */
1135
+ async inputSlot(job, bytes) {
1136
+ const now = await this.#now();
1137
+ return this.#issue(
1138
+ job,
1139
+ { direction: "in", blob: mintBlobId(bytes) },
1140
+ MAX_IMAGES_IN,
1141
+ now + ENVELOPE_MAX_AGE_MS + BLOBS_KEPT_AFTER_DEADLINE_MS,
1142
+ bytes
1143
+ );
1144
+ }
1145
+ /**
1146
+ * An upload slot for one output of an `llm.image` job, under the lease
1147
+ * its device holds. The caller has checked the lease and the kind.
1148
+ *
1149
+ * `full` once this lease has every output slot the kind may use. Slots an
1150
+ * earlier lease was issued are deleted here: that grant ended, and no
1151
+ * result can reference what was uploaded under it.
1152
+ */
1153
+ async outputSlot(job, bytes) {
1154
+ return this.#issue(
1155
+ job,
1156
+ { direction: "out", blob: mintBlobId(bytes), leaseId: job.leaseId },
1157
+ MAX_IMAGES_OUT,
1158
+ job.deadlineAt + BLOBS_KEPT_AFTER_DEADLINE_MS,
1159
+ bytes
1160
+ );
1161
+ }
1162
+ async #issue(job, slot, max, deleteAt, bytes) {
1163
+ const { issued, displaced } = await this.#ledger.issue({
1164
+ siteId: job.siteId,
1165
+ jobId: job.jobId,
1166
+ slot,
1167
+ max,
1168
+ deleteAt
1169
+ });
1170
+ await this.#deleteObjects(job, displaced);
1171
+ if (!issued) return "full";
1172
+ const signed = await this.#store.slot(this.#address(job, slot), bytes);
1173
+ return { blob: slot.blob, url: signed.url, expiresAt: signed.expiresAt };
1174
+ }
1175
+ /**
1176
+ * A download URL for one stored blob, or `null`.
1177
+ *
1178
+ * `null` for an id this relay did not mint, an object that is not stored,
1179
+ * and one that is not the size its slot was issued for — the size is read
1180
+ * again here, so an object replaced after its job was offered is not
1181
+ * handed on. One answer for all three.
1182
+ */
1183
+ async downloadUrl(address) {
1184
+ const expected = slotBytesOf(address.blob);
1185
+ if (expected === null) return null;
1186
+ if (await this.#store.head(address) !== expected) return null;
1187
+ const signed = await this.#store.url(address);
1188
+ return { url: signed.url, expiresAt: signed.expiresAt };
1189
+ }
1190
+ /**
1191
+ * Why a job may not be offered, or `null` when it may — the `HEAD` before
1192
+ * offer ({@link MUSTS.BLOB_BUDGET_BEFORE_DOWNLOAD}'s last clause, C057).
1193
+ *
1194
+ * Every input slot this job was issued must hold an object of exactly the
1195
+ * size it was issued for: the relay reads the stored size and does not
1196
+ * trust the slot. A slot never filled refuses the job too, and so does an
1197
+ * `llm.vision` job with no input at all — the relay cannot read which
1198
+ * blobs the sealed payload names, so the slots are what "its blobs" means
1199
+ * here.
1200
+ *
1201
+ * A refused job's inputs are deleted with the refusal: it is not offered,
1202
+ * so nothing will read them, and a site that enqueues the same id again
1203
+ * starts from no slots.
1204
+ *
1205
+ * A job with no record is looked for in the store by name first, so a
1206
+ * ledger that forgot it (a restart) still checks what was stored and
1207
+ * still deletes it on time.
1208
+ */
1209
+ async inputFault(job) {
1210
+ const deleteAt = job.deadlineAt + BLOBS_KEPT_AFTER_DEADLINE_MS;
1211
+ let record = await this.#ledger.record(job.siteId, job.jobId);
1212
+ if (record === void 0) {
1213
+ for (const slot of await this.#store.list(job)) {
1214
+ if (slotBytesOf(slot.blob) === null) continue;
1215
+ await this.#ledger.issue({
1216
+ siteId: job.siteId,
1217
+ jobId: job.jobId,
1218
+ slot,
1219
+ max: Number.MAX_SAFE_INTEGER,
1220
+ deleteAt
1221
+ });
1222
+ }
1223
+ record = await this.#ledger.record(job.siteId, job.jobId);
1224
+ }
1225
+ const inputs = (record?.slots ?? []).filter(
1226
+ (slot) => slot.direction === "in"
1227
+ );
1228
+ let fault = null;
1229
+ if (job.kind === "llm.vision" && inputs.length === 0) {
1230
+ fault = "this llm.vision job has no stored input blob";
1231
+ }
1232
+ for (const slot of inputs) {
1233
+ if (fault !== null) break;
1234
+ fault = await this.#slotFault(job, slot);
1235
+ }
1236
+ if (fault !== null) {
1237
+ await this.#deleteObjects(job, inputs);
1238
+ await this.#ledger.drop({ ...job, direction: "in" });
1239
+ return fault;
1240
+ }
1241
+ await this.#ledger.bringForward({
1242
+ siteId: job.siteId,
1243
+ jobId: job.jobId,
1244
+ deleteAt
1245
+ });
1246
+ return null;
1247
+ }
1248
+ /**
1249
+ * Why an `ok` result may not be accepted, or `null` when it may — the
1250
+ * same check an input gets, on the outputs issued under this lease.
1251
+ */
1252
+ async outputFault(job) {
1253
+ const record = await this.#ledger.record(job.siteId, job.jobId);
1254
+ for (const slot of record?.slots ?? []) {
1255
+ if (slot.direction !== "out" || slot.leaseId !== job.leaseId) continue;
1256
+ const fault = await this.#slotFault(job, slot);
1257
+ if (fault !== null) return fault;
1258
+ }
1259
+ return null;
1260
+ }
1261
+ async #slotFault(job, slot) {
1262
+ const stored = await this.#store.head(this.#address(job, slot));
1263
+ if (stored === null) return `blob ${slot.blob} was never uploaded`;
1264
+ return stored === slotBytesOf(slot.blob) ? null : `blob ${slot.blob} is not the size its slot was issued for`;
1265
+ }
1266
+ /**
1267
+ * A result was accepted: the inputs go now, since nothing reads them
1268
+ * again. So do the outputs of a result that is not `ok`, which no
1269
+ * reference will ever name.
1270
+ */
1271
+ async resultAccepted(job, disposition) {
1272
+ const record = await this.#ledger.record(job.siteId, job.jobId);
1273
+ if (record === void 0) return;
1274
+ const going = record.slots.filter(
1275
+ (slot) => slot.direction === "in" || disposition !== "ok"
1276
+ );
1277
+ await this.#deleteObjects(job, going);
1278
+ await this.#ledger.drop({
1279
+ ...job,
1280
+ ...disposition === "ok" ? { direction: "in" } : {}
1281
+ });
1282
+ }
1283
+ /**
1284
+ * Results were handed to their site: each one's outputs now go within the
1285
+ * hour unless the site says sooner that it holds them. **Not now** — the
1286
+ * site downloads after it collects (C059).
1287
+ */
1288
+ async collected(siteId, jobIds) {
1289
+ if (jobIds.length === 0) return;
1290
+ const outputDeleteAt = await this.#now() + OUTPUT_KEPT_AFTER_COLLECTION_MS;
1291
+ for (const jobId of jobIds) {
1292
+ await this.#ledger.bringForward({ siteId, jobId, outputDeleteAt });
1293
+ }
1294
+ }
1295
+ /** The site holds these outputs: they are deleted now. */
1296
+ async received(job, blobs) {
1297
+ await this.#deleteObjects(
1298
+ job,
1299
+ blobs.map((blob) => ({ direction: "out", blob }))
1300
+ );
1301
+ await this.#ledger.drop({ ...job, direction: "out", blobs });
1302
+ }
1303
+ /**
1304
+ * Delete whatever the clock says is due, and count it.
1305
+ *
1306
+ * Outputs an hour after collection without `received`; everything a job
1307
+ * has left a day after its deadline. Then the objects no record covers —
1308
+ * a ledger that was lost, with nothing enqueued again to rebuild it —
1309
+ * once they are {@link ORPHAN_BLOB_AGE_MS} old, found from the store's
1310
+ * names and its stored times alone. The store's own lifecycle rule is the
1311
+ * floor under this, for the case where it does not run.
1312
+ */
1313
+ async sweep() {
1314
+ const now = await this.#now();
1315
+ let deleted = 0;
1316
+ for (const record of await this.#ledger.due(now)) {
1317
+ const all = record.deleteAt <= now;
1318
+ const going = record.slots.filter(
1319
+ (slot) => all || slot.direction === "out"
1320
+ );
1321
+ await this.#deleteObjects(record, going);
1322
+ await this.#ledger.drop({
1323
+ siteId: record.siteId,
1324
+ jobId: record.jobId,
1325
+ ...all ? {} : { direction: "out" }
1326
+ });
1327
+ deleted += going.length;
1328
+ }
1329
+ for (const { address } of await this.#store.storedBefore(
1330
+ now - ORPHAN_BLOB_AGE_MS
1331
+ )) {
1332
+ const record = await this.#ledger.record(address.siteId, address.jobId);
1333
+ const covered = record?.slots.some(
1334
+ (slot) => slot.direction === address.direction && slot.blob === address.blob
1335
+ );
1336
+ if (covered === true) continue;
1337
+ await this.#store.delete(address);
1338
+ deleted += 1;
1339
+ }
1340
+ return deleted;
1341
+ }
1342
+ #address(job, slot) {
1343
+ return {
1344
+ siteId: job.siteId,
1345
+ jobId: job.jobId,
1346
+ direction: slot.direction,
1347
+ blob: slot.blob
1348
+ };
1349
+ }
1350
+ async #deleteObjects(job, slots) {
1351
+ for (const slot of slots) {
1352
+ if (slotBytesOf(slot.blob) === null) continue;
1353
+ await this.#store.delete(this.#address(job, slot));
1354
+ }
1355
+ }
1356
+ };
1357
+
738
1358
  // src/debug.ts
739
1359
  var escape = (value) => value.replace(
740
1360
  /[&<>"]/g,
@@ -1177,10 +1797,17 @@ import {
1177
1797
  MAX_ENVELOPE_BYTES as MAX_ENVELOPE_BYTES3,
1178
1798
  PROTOCOL_VERSION as PROTOCOL_VERSION2,
1179
1799
  envelopeBytes as envelopeBytes2,
1800
+ isBlobObjectSize as isBlobObjectSize3,
1180
1801
  keyId as keyId2,
1181
1802
  JobStub,
1182
1803
  RequestSignature as RequestSignature2,
1183
1804
  SealedEnvelope,
1805
+ SiteBlobDownloadRequest,
1806
+ SiteBlobDownloadResponse,
1807
+ SiteBlobSlotRequest,
1808
+ SiteBlobSlotResponse,
1809
+ SiteBlobsReceivedRequest,
1810
+ SiteBlobsReceivedResponse,
1184
1811
  SiteEnqueueTools,
1185
1812
  SiteToolCalls,
1186
1813
  SiteToolResultRequest,
@@ -1352,6 +1979,8 @@ var SitePlane = class {
1352
1979
  "nothing can answer this right now \u2014 try again later"
1353
1980
  );
1354
1981
  }
1982
+ const imageRefusal = await this.#imageRefusal(siteId, request.stub);
1983
+ if (imageRefusal !== null) return imageRefusal;
1355
1984
  const job = await this.#deps.state.enqueue({
1356
1985
  id: request.stub.id,
1357
1986
  siteId,
@@ -1365,6 +1994,128 @@ var SitePlane = class {
1365
1994
  }
1366
1995
  );
1367
1996
  }
1997
+ /**
1998
+ * Why an image job may not be queued, or `null` — byollm_021 §2.
1999
+ *
2000
+ * **A relay with no blob store carries no images, and says so here.** An
2001
+ * `llm.image` job has no input, so nothing else would stop one reaching a
2002
+ * device: it would be offered, the device's backend would be paid for the
2003
+ * images, and the upload slot would answer `not-found` (Owl on #7875,
2004
+ * point 3). Refused before anything is queued instead.
2005
+ *
2006
+ * **The `HEAD` before offer** ({@link MUSTS.BLOB_BUDGET_BEFORE_DOWNLOAD},
2007
+ * C057): every input slot this job was issued must hold an object of the
2008
+ * size it was issued for, read from the store. Once, when the job is first
2009
+ * queued — a republish of a job already routing was checked when it
2010
+ * arrived, and its inputs may since have been deleted with its result.
2011
+ */
2012
+ async #imageRefusal(siteId, stub) {
2013
+ if (stub.kind !== "llm.vision" && stub.kind !== "llm.image") return null;
2014
+ const blobs = this.#deps.blobs;
2015
+ if (blobs === void 0) {
2016
+ return fail2(
2017
+ 400,
2018
+ "bad-request",
2019
+ `this relay carries no images, so it cannot route ${stub.kind}: it has no blob store`
2020
+ );
2021
+ }
2022
+ if (await this.#deps.state.job(siteId, stub.id) !== void 0) {
2023
+ return null;
2024
+ }
2025
+ const fault = await blobs.inputFault({
2026
+ siteId,
2027
+ jobId: stub.id,
2028
+ kind: stub.kind,
2029
+ deadlineAt: stub.deadlineAt
2030
+ });
2031
+ return fault === null ? null : fail2(400, "bad-request", `enqueue refused: ${fault}`);
2032
+ }
2033
+ // -- blobs — byollm_021 §2, "The cloud lane" -----------------------------
2034
+ //
2035
+ // Three, all signed with the site key and all about the caller's own
2036
+ // jobs: the site id every object is addressed under is the one the
2037
+ // signature proved, so a site reaches no other site's blobs by naming a
2038
+ // job id it does not own. Each is handed the blob decisions by the
2039
+ // router, which has no such route on a relay without a blob store.
2040
+ /**
2041
+ * `POST /relay/blobs` — an upload slot for one input of a job this site
2042
+ * is about to enqueue. The size is kept with the slot, in the blob id
2043
+ * this relay mints, and the stored object is held to it at enqueue.
2044
+ */
2045
+ blobSlot(blobs, auth, body) {
2046
+ return this.#authed(
2047
+ auth,
2048
+ body,
2049
+ SiteBlobSlotRequest,
2050
+ (request) => request.siteId,
2051
+ async (request, siteId) => {
2052
+ if (!isBlobObjectSize3(request.bytes)) {
2053
+ return fail2(400, "bad-request", SLOT_SIZE_MESSAGE);
2054
+ }
2055
+ if (await this.#deps.state.job(siteId, request.jobId) !== void 0) {
2056
+ return fail2(
2057
+ 409,
2058
+ "too-late",
2059
+ "this job is already queued; its inputs are uploaded before it is"
2060
+ );
2061
+ }
2062
+ const slot = await blobs.inputSlot(
2063
+ { siteId, jobId: request.jobId },
2064
+ request.bytes
2065
+ );
2066
+ if (slot === "full") {
2067
+ return fail2(
2068
+ 400,
2069
+ "bad-request",
2070
+ "this job has been issued every input slot an llm.vision job may use"
2071
+ );
2072
+ }
2073
+ return ok2(SiteBlobSlotResponse.parse(slot));
2074
+ }
2075
+ );
2076
+ }
2077
+ /**
2078
+ * `POST /relay/blobs/download` — a download URL for one output blob of
2079
+ * one of this site's jobs. One `not-found` for a blob that is not stored
2080
+ * under this site, this job and `out`, whatever the reason.
2081
+ */
2082
+ blobDownload(blobs, auth, body) {
2083
+ return this.#authed(
2084
+ auth,
2085
+ body,
2086
+ SiteBlobDownloadRequest,
2087
+ (request) => request.siteId,
2088
+ async (request, siteId) => {
2089
+ const signed = await blobs.downloadUrl({
2090
+ siteId,
2091
+ jobId: request.jobId,
2092
+ direction: "out",
2093
+ blob: request.blob
2094
+ });
2095
+ if (signed === null) {
2096
+ return fail2(404, "not-found", "no such output blob of this job");
2097
+ }
2098
+ return ok2(SiteBlobDownloadResponse.parse(signed));
2099
+ }
2100
+ );
2101
+ }
2102
+ /**
2103
+ * `POST /relay/blobs/received` — the site holds these outputs, so they
2104
+ * are deleted now ({@link MUSTS.BLOBS_GO_WITH_THE_JOB}). Idempotent, and
2105
+ * quiet about a blob that was already gone or never this job's.
2106
+ */
2107
+ blobsReceived(blobs, auth, body) {
2108
+ return this.#authed(
2109
+ auth,
2110
+ body,
2111
+ SiteBlobsReceivedRequest,
2112
+ (request) => request.siteId,
2113
+ async (request, siteId) => {
2114
+ await blobs.received({ siteId, jobId: request.jobId }, request.blobs);
2115
+ return ok2(SiteBlobsReceivedResponse.parse({ jobId: request.jobId }));
2116
+ }
2117
+ );
2118
+ }
1368
2119
  /**
1369
2120
  * What needs sealing, and who to seal it to.
1370
2121
  *
@@ -1512,7 +2263,12 @@ var SitePlane = class {
1512
2263
  QueryRequest,
1513
2264
  (request) => request.siteId,
1514
2265
  async (_request, site) => {
1515
- const jobs = (await this.#deps.state.finished(site)).map((job) => ({
2266
+ const finished = await this.#deps.state.finished(site);
2267
+ await this.#deps.blobs?.collected(
2268
+ site,
2269
+ finished.filter((job) => job.stub.kind === "llm.image").map((job) => job.id)
2270
+ ).catch(() => void 0);
2271
+ const jobs = finished.map((job) => ({
1516
2272
  jobId: job.id,
1517
2273
  envelope: job.result,
1518
2274
  disposition: job.disposition,
@@ -1553,6 +2309,7 @@ var Relay = class {
1553
2309
  #now;
1554
2310
  #basePath;
1555
2311
  #debug;
2312
+ #blobs;
1556
2313
  constructor(options) {
1557
2314
  this.state = options.store ?? new RelayState({
1558
2315
  now: options.now ?? Date.now,
@@ -1562,11 +2319,19 @@ var Relay = class {
1562
2319
  this.#now = options.now ?? Date.now;
1563
2320
  this.#basePath = (options.basePath ?? "/byollm").replace(/\/+$/, "");
1564
2321
  this.#debug = options.debug ?? false;
2322
+ this.#blobs = options.blobs === void 0 ? void 0 : new RelayBlobs({
2323
+ store: options.blobs.store,
2324
+ ledger: options.blobs.ledger ?? new MemoryBlobLedger(),
2325
+ // The routing store's clock, the one every other deadline here
2326
+ // is stamped from.
2327
+ now: () => this.state.now()
2328
+ });
1565
2329
  this.#daemon = new DaemonPlane({
1566
2330
  state: this.state,
1567
2331
  projection: this.projection,
1568
2332
  now: this.#now,
1569
2333
  leaseMs: options.leaseMs ?? 6e4,
2334
+ blobs: this.#blobs,
1570
2335
  pairingCodes: options.pairingCodes ?? new MemoryPairingCodes(() => this.#now()),
1571
2336
  ...options.verificationUrl === void 0 ? {} : { verificationUrl: options.verificationUrl },
1572
2337
  ...options.controlPlanePublic === void 0 ? {} : { controlPlanePublic: options.controlPlanePublic },
@@ -1583,6 +2348,7 @@ var Relay = class {
1583
2348
  state: this.state,
1584
2349
  projection: this.projection,
1585
2350
  now: this.#now,
2351
+ blobs: this.#blobs,
1586
2352
  ...options.satisfiable === void 0 ? {} : { satisfiable: options.satisfiable }
1587
2353
  });
1588
2354
  }
@@ -1601,10 +2367,25 @@ var Relay = class {
1601
2367
  */
1602
2368
  async sweep() {
1603
2369
  const requeued = await this.state.sweep();
1604
- return { requeued: requeued.map((j) => j.id) };
2370
+ const blobsDeleted = await this.#blobs?.sweep() ?? 0;
2371
+ return { requeued: requeued.map((j) => j.id), blobsDeleted };
1605
2372
  }
1606
2373
  /** The whole HTTP surface. */
1607
2374
  async handle(request) {
2375
+ try {
2376
+ return await this.#blobs?.serve(request) ?? await this.#route(request);
2377
+ } catch (error) {
2378
+ if (!(error instanceof BlobStoreFailure)) throw error;
2379
+ return json({
2380
+ status: 503,
2381
+ body: {
2382
+ error: "server-error",
2383
+ message: "the blob store could not answer just now \u2014 try again shortly"
2384
+ }
2385
+ });
2386
+ }
2387
+ }
2388
+ async #route(request) {
1608
2389
  const url = new URL(request.url);
1609
2390
  const path = url.pathname;
1610
2391
  if (path === "/debug" || path === `${this.#basePath}/debug`) {
@@ -1681,6 +2462,36 @@ var Relay = class {
1681
2462
  )
1682
2463
  );
1683
2464
  }
2465
+ const blobs = this.#blobs;
2466
+ if (blobs !== void 0) {
2467
+ if (path === "/relay/blobs") {
2468
+ return json(
2469
+ await this.#site.blobSlot(
2470
+ blobs,
2471
+ { ...siteAuth, endpoint: "blobs" },
2472
+ body
2473
+ )
2474
+ );
2475
+ }
2476
+ if (path === "/relay/blobs/download") {
2477
+ return json(
2478
+ await this.#site.blobDownload(
2479
+ blobs,
2480
+ { ...siteAuth, endpoint: "blobs/download" },
2481
+ body
2482
+ )
2483
+ );
2484
+ }
2485
+ if (path === "/relay/blobs/received") {
2486
+ return json(
2487
+ await this.#site.blobsReceived(
2488
+ blobs,
2489
+ { ...siteAuth, endpoint: "blobs/received" },
2490
+ body
2491
+ )
2492
+ );
2493
+ }
2494
+ }
1684
2495
  if (!path.startsWith(`${this.#basePath}/`)) {
1685
2496
  return json({ status: 404, body: { error: "not-found" } });
1686
2497
  }
@@ -1701,9 +2512,16 @@ var Relay = class {
1701
2512
  return json(await this.#daemon.toolCall(auth, body));
1702
2513
  case "tool-results":
1703
2514
  return json(await this.#daemon.toolResults(auth, body));
2515
+ case "blob-url":
2516
+ if (blobs === void 0) break;
2517
+ return json(await this.#daemon.blobUrl(blobs, auth, body));
2518
+ case "blob-slot":
2519
+ if (blobs === void 0) break;
2520
+ return json(await this.#daemon.blobSlot(blobs, auth, body));
1704
2521
  default:
1705
- return json({ status: 404, body: { error: "not-found" } });
2522
+ break;
1706
2523
  }
2524
+ return json({ status: 404, body: { error: "not-found" } });
1707
2525
  }
1708
2526
  };
1709
2527
  function safeJson(raw) {
@@ -1728,6 +2546,7 @@ var json = (result) => new Response(JSON.stringify(result.body), {
1728
2546
  });
1729
2547
  export {
1730
2548
  AWAITING_PAYLOAD_MS,
2549
+ BLOB_OBJECT_PREFIX,
1731
2550
  CHURN_EXPIRIES,
1732
2551
  CHURN_QUIET_MS,
1733
2552
  CHURN_WINDOW_MS,
@@ -1735,7 +2554,12 @@ export {
1735
2554
  DeviceRecord,
1736
2555
  EMPTY_FIXTURE,
1737
2556
  MAX_OUTSTANDING_PAIRINGS,
2557
+ MEMORY_BLOB_PATH,
2558
+ MEMORY_BLOB_URL_TTL_MS,
2559
+ MemoryBlobLedger,
2560
+ MemoryBlobStore,
1738
2561
  MemoryPairingCodes,
2562
+ ORPHAN_BLOB_AGE_MS,
1739
2563
  PAIRING_BUSY_MESSAGE,
1740
2564
  PAIRING_CODE_TTL_MS,
1741
2565
  Projection,
@@ -1747,10 +2571,15 @@ export {
1747
2571
  SEAL_ATTEMPTS_BEFORE_EVICTION,
1748
2572
  SiteRecord,
1749
2573
  UNSEALED_PER_PAIR,
2574
+ blobAddressOf,
2575
+ blobJobPrefix,
2576
+ blobObjectName,
1750
2577
  debugPage,
2578
+ mintBlobId,
1751
2579
  newDeviceCode,
1752
2580
  newUserCode,
1753
2581
  routeKey,
2582
+ slotBytesOf,
1754
2583
  subStateOf
1755
2584
  };
1756
2585
  //# sourceMappingURL=index.js.map