mlclaw 0.1.0

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.
Files changed (47) hide show
  1. package/.agents/skills/mlclaw/SKILL.md +214 -0
  2. package/.agents/skills/mlclaw/agents/openai.yaml +4 -0
  3. package/.gitattributes +35 -0
  4. package/Dockerfile +45 -0
  5. package/LICENSE +21 -0
  6. package/README.md +206 -0
  7. package/assets/mlclaw.svg +143 -0
  8. package/dist/hf-state-sync.js +9532 -0
  9. package/dist/mlclaw-space-runtime.js +5010 -0
  10. package/dist/mlclaw.mjs +16502 -0
  11. package/entrypoint.sh +87 -0
  12. package/mlclaw.ps1 +108 -0
  13. package/mlclaw.sh +117 -0
  14. package/openclaw.default.json +67 -0
  15. package/package.json +66 -0
  16. package/scripts/configure-huggingface-model.mjs +86 -0
  17. package/scripts/configure-telegram.mjs +55 -0
  18. package/scripts/report-telegram-probe.mjs +18 -0
  19. package/space/README.md +42 -0
  20. package/src/hf-bucket-client/client.ts +217 -0
  21. package/src/hf-state-sync/archive.ts +137 -0
  22. package/src/hf-state-sync/cli.ts +92 -0
  23. package/src/hf-state-sync/hub.ts +81 -0
  24. package/src/hf-state-sync/manifest.ts +67 -0
  25. package/src/hf-state-sync/paths.ts +73 -0
  26. package/src/hf-state-sync/restore.ts +109 -0
  27. package/src/hf-state-sync/snapshot.ts +133 -0
  28. package/src/hf-state-sync/sqlite.ts +57 -0
  29. package/src/hf-state-sync/supervise.ts +256 -0
  30. package/src/vendor/hfjs-xet/error.ts +52 -0
  31. package/src/vendor/hfjs-xet/types/public.ts +207 -0
  32. package/src/vendor/hfjs-xet/utils/ChunkCache.ts +102 -0
  33. package/src/vendor/hfjs-xet/utils/RangeList.ts +182 -0
  34. package/src/vendor/hfjs-xet/utils/SplicedBlob.ts +249 -0
  35. package/src/vendor/hfjs-xet/utils/XetBlob.ts +732 -0
  36. package/src/vendor/hfjs-xet/utils/checkCredentials.ts +21 -0
  37. package/src/vendor/hfjs-xet/utils/combineUint8Arrays.ts +13 -0
  38. package/src/vendor/hfjs-xet/utils/createXorbs.ts +782 -0
  39. package/src/vendor/hfjs-xet/utils/shardParser.ts +152 -0
  40. package/src/vendor/hfjs-xet/utils/sum.ts +9 -0
  41. package/src/vendor/hfjs-xet/utils/uploadShards.ts +443 -0
  42. package/src/vendor/hfjs-xet/utils/xetWriteToken.ts +101 -0
  43. package/src/vendor/hfjs-xet/vendor/lz4js/index.ts +540 -0
  44. package/src/vendor/hfjs-xet/vendor/lz4js/util.ts +57 -0
  45. package/src/vendor/hfjs-xet/vendor/lz4js/xxh32.ts +99 -0
  46. package/src/vendor/hfjs-xet/vendor/type-fest/basic.ts +34 -0
  47. package/tsconfig.json +16 -0
@@ -0,0 +1,782 @@
1
+ // @ts-nocheck -- vendored upstream code, kept verbatim; our strict tsconfig does not apply.
2
+ // Vendored from huggingface/huggingface.js@f8fdf6be (packages/hub/src/utils/createXorbs.ts), MIT License.
3
+ // Delete this directory when bucket support is upstreamed to @huggingface/hub.
4
+ import { bg4_split_bytes, XET_CHUNK_HEADER_BYTES, XetChunkCompressionScheme } from "./XetBlob";
5
+ import { compress as lz4_compress } from "../vendor/lz4js";
6
+ import { ChunkCache } from "./ChunkCache";
7
+ import { xetWriteToken, type XetWriteTokenParams } from "./xetWriteToken";
8
+ import type { ShardData } from "./shardParser";
9
+ import { parseShardData } from "./shardParser";
10
+ import { SplicedBlob } from "./SplicedBlob";
11
+ import {
12
+ createChunker,
13
+ nextBlock,
14
+ finalize,
15
+ hashToHex,
16
+ hexToBytes,
17
+ xorbHash,
18
+ fileHash,
19
+ hmac,
20
+ verificationHash,
21
+ type Chunk,
22
+ } from "@huggingface/xetchunk-wasm";
23
+
24
+ const TARGET_CHUNK_SIZE = 64 * 1024;
25
+ const MAX_CHUNK_SIZE = 2 * TARGET_CHUNK_SIZE;
26
+ const XORB_SIZE = 64 * 1024 * 1024;
27
+ const MAX_XORB_CHUNKS = 8 * 1024;
28
+ const INTERVAL_BETWEEN_REMOTE_DEDUP = 4_000_000; // 4MB
29
+ /**
30
+ * 0 = only show progress when uploading the xorb
31
+ * 1 = only show progress when processing the file
32
+ * 0.5 = show progress when uploading the xorb and when processing the file
33
+ */
34
+ const PROCESSING_PROGRESS_RATIO = 0.1;
35
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
36
+ const UPLOADING_PROGRESS_RATIO = 1 - PROCESSING_PROGRESS_RATIO;
37
+
38
+ function computeXorbHashHex(chunks: { hash: string; length: number }[]): string {
39
+ const chunkObjs: Chunk[] = chunks.map((c) => ({ hash: hexToBytes(c.hash), length: c.length }));
40
+ return hashToHex(xorbHash(chunkObjs));
41
+ }
42
+
43
+ function computeHmacHex(hash: string, key: string): string {
44
+ return hashToHex(hmac(hexToBytes(hash), hexToBytes(key)));
45
+ }
46
+
47
+ function computeVerificationHashHex(hashes: string[]): string {
48
+ return hashToHex(verificationHash(hashes.map(hexToBytes)));
49
+ }
50
+
51
+ function computeFileHashHex(chunks: { hash: string; length: number }[]): string {
52
+ const chunkObjs: Chunk[] = chunks.map((c) => ({ hash: hexToBytes(c.hash), length: c.length }));
53
+ return hashToHex(fileHash(chunkObjs));
54
+ }
55
+
56
+ function addDataToChunker(
57
+ data: Uint8Array,
58
+ chunker: ReturnType<typeof createChunker>,
59
+ ): { hash: string; length: number; dedup: boolean }[] {
60
+ return nextBlock(chunker, data).map((c) => ({ hash: hashToHex(c.hash), length: c.length, dedup: false }));
61
+ }
62
+
63
+ function finalizeChunker(
64
+ chunker: ReturnType<typeof createChunker>,
65
+ ): { hash: string; length: number; dedup: boolean }[] {
66
+ const last = finalize(chunker);
67
+ if (!last) {
68
+ return [];
69
+ }
70
+ return [{ hash: hashToHex(last.hash), length: last.length, dedup: false }];
71
+ }
72
+
73
+ interface XorbEvent {
74
+ event: "xorb";
75
+ xorb: Uint8Array;
76
+ hash: string;
77
+ id: number;
78
+ chunks: Array<{ hash: string; length: number }>;
79
+ files: Array<{
80
+ path: string;
81
+ progress: number;
82
+ lastSentProgress: number;
83
+ }>;
84
+ }
85
+
86
+ export class CurrentXorbInfo {
87
+ id: number;
88
+ offset: number;
89
+ chunks: Array<{ hash: string; length: number; offset: number }>;
90
+
91
+ fileProcessedBytes: Record<string, number>;
92
+ fileUploadedBytes: Record<string, number>;
93
+ fileSize: Record<string, number>;
94
+ data: Uint8Array;
95
+ immutableData: {
96
+ chunkIndex: number;
97
+ offset: number;
98
+ } | null;
99
+
100
+ constructor() {
101
+ this.id = 0;
102
+ this.offset = 0;
103
+ this.chunks = [];
104
+ this.fileProcessedBytes = {};
105
+ this.fileUploadedBytes = {};
106
+ this.fileSize = {};
107
+ this.data = new Uint8Array(XORB_SIZE);
108
+ this.immutableData = null;
109
+ }
110
+
111
+ event(computeXorbHash: (chunks: { hash: string; length: number }[]) => string): XorbEvent {
112
+ const xorbChunksCleaned = this.chunks.map((chunk) => ({
113
+ hash: chunk.hash,
114
+ length: chunk.length,
115
+ }));
116
+
117
+ return {
118
+ event: "xorb" as const,
119
+ xorb: this.data.subarray(0, this.offset),
120
+ hash: computeXorbHash(xorbChunksCleaned),
121
+ chunks: xorbChunksCleaned,
122
+ id: this.id,
123
+ files: Object.entries(this.fileProcessedBytes).map(([path, processedBytes]) => ({
124
+ path,
125
+ progress: processedBytes / this.fileSize[path],
126
+ lastSentProgress:
127
+ ((this.fileUploadedBytes[path] ?? 0) +
128
+ (processedBytes - (this.fileUploadedBytes[path] ?? 0)) * PROCESSING_PROGRESS_RATIO) /
129
+ this.fileSize[path],
130
+ })),
131
+ };
132
+ }
133
+ }
134
+
135
+ export async function* createXorbs(
136
+ fileSources: AsyncGenerator<{ content: Blob; path: string; sha256?: string }>,
137
+ params: XetWriteTokenParams & {
138
+ yieldCallback?: (event: { event: "fileProgress"; path: string; progress: number }) => void;
139
+ },
140
+ ): AsyncGenerator<
141
+ | XorbEvent
142
+ | {
143
+ event: "file";
144
+ path: string;
145
+ hash: string;
146
+ sha256?: string;
147
+ /** Percentage of file bytes that were deduplicated (0-1) */
148
+ dedupRatio: number;
149
+ representation: Array<{
150
+ xorbId: number | string; // either xorb id (for local xorbs) or xorb hash (for remote xorbs)
151
+ indexStart: number;
152
+ indexEnd: number;
153
+ /** Unpacked length */
154
+ length: number;
155
+ rangeHash: string;
156
+ }>;
157
+ },
158
+ void,
159
+ undefined
160
+ > {
161
+ const alreadyDoneFileSha256s: Set<string> = new Set();
162
+ let xorbId = 0;
163
+ const chunkCache = new ChunkCache();
164
+ let xorb = new CurrentXorbInfo();
165
+
166
+ const nextXorb = (currentFile: { path: string; uploadedBytes: number; size: number }): XorbEvent => {
167
+ const event = xorb.event(computeXorbHashHex);
168
+
169
+ xorbId++;
170
+ xorb = new CurrentXorbInfo();
171
+ xorb.id = xorbId;
172
+ xorb.fileUploadedBytes = {
173
+ [currentFile.path]: currentFile.uploadedBytes,
174
+ };
175
+ xorb.fileSize[currentFile.path] = currentFile.size;
176
+
177
+ return event;
178
+ };
179
+
180
+ const pendingFileEvents: Array<{
181
+ event: "file";
182
+ path: string;
183
+ hash: string;
184
+ dedupRatio: number;
185
+ sha256?: string;
186
+ representation: Array<{
187
+ xorbId: number | string;
188
+ indexStart: number;
189
+ indexEnd: number;
190
+ length: number;
191
+ rangeHash: string;
192
+ }>;
193
+ }> = [];
194
+
195
+ const remoteXorbHashes: string[] = [""]; // starts at index 1 (to simplify implem a bit)
196
+
197
+ for await (const fileSource of fileSources) {
198
+ params.yieldCallback?.({
199
+ event: "fileProgress",
200
+ path: fileSource.path,
201
+ progress: 0,
202
+ });
203
+ if (fileSource.sha256 && alreadyDoneFileSha256s.has(fileSource.sha256)) {
204
+ params.yieldCallback?.({
205
+ event: "fileProgress",
206
+ path: fileSource.path,
207
+ progress: 1,
208
+ });
209
+ continue;
210
+ }
211
+ if (fileSource.sha256) {
212
+ alreadyDoneFileSha256s.add(fileSource.sha256);
213
+ }
214
+
215
+ const chunker = createChunker(TARGET_CHUNK_SIZE);
216
+ {
217
+ xorb.fileSize[fileSource.path] = fileSource.content.size;
218
+
219
+ // Load dedup info for the first chunk of the file, if it's potentially modified by the splice
220
+ if (fileSource.content instanceof SplicedBlob && fileSource.content.firstSpliceIndex < MAX_CHUNK_SIZE) {
221
+ await loadDedupInfoToCache(
222
+ fileSource.content.originalBlob.slice(0, MAX_CHUNK_SIZE),
223
+ remoteXorbHashes,
224
+ params,
225
+ chunkCache,
226
+ computeHmacHex,
227
+ {
228
+ maxChunks: 1,
229
+ isAtBeginning: true,
230
+ },
231
+ );
232
+ }
233
+ let bytesSinceRemoteDedup = Infinity;
234
+ let bytesSinceLastProgressEvent = 0;
235
+ let isFirstFileChunk = true;
236
+ const sourceChunks: Array<Uint8Array> = [];
237
+
238
+ const reader = fileSource.content.stream().getReader();
239
+ let processedBytes = 0;
240
+ let dedupedBytes = 0; // Track bytes that were deduplicated
241
+ // Needed to compute the final file hash
242
+ // todo: have the wasm function to compute file hash be able to take data chunk by chunk instead of all at once
243
+ const fileChunks: Array<{ hash: string; length: number }> = [];
244
+ // Collect chunk metadata to build representation at the end
245
+ // todo: build partial representation at the end of each xorb, to avoid having to store all chunks in memory
246
+ const chunkMetadata: Array<{
247
+ xorbId: number | string;
248
+ chunkIndex: number;
249
+ length: number;
250
+ }> = [];
251
+
252
+ const addChunks = async function* (chunks: Array<{ hash: string; length: number; dedup: boolean }>) {
253
+ for (const chunk of chunks) {
254
+ if (isFirstFileChunk) {
255
+ chunk.dedup = true;
256
+ isFirstFileChunk = false;
257
+ }
258
+ let chunkIndex = xorb.chunks.length;
259
+ let chunkXorbId = xorbId;
260
+
261
+ // Remove chunks from source data
262
+ const chunkToCopy = removeChunkFromSourceData(sourceChunks, chunk.length);
263
+
264
+ let cacheData = chunkCache.getChunk(chunk.hash, computeHmacHex);
265
+ if (cacheData === undefined && chunk.dedup && bytesSinceRemoteDedup >= INTERVAL_BETWEEN_REMOTE_DEDUP) {
266
+ const token = await xetWriteToken(params);
267
+ bytesSinceRemoteDedup = 0;
268
+
269
+ const shardResp = await (params.fetch ?? fetch)(token.casUrl + "/v1/chunks/default/" + chunk.hash, {
270
+ headers: {
271
+ Authorization: `Bearer ${token.accessToken}`,
272
+ },
273
+ });
274
+
275
+ // todo: handle non-404 non-429 errors, eg throw error
276
+ if (shardResp.ok) {
277
+ const shard = await shardResp.blob();
278
+ const shardData = await parseShardData(shard);
279
+
280
+ for (const xorb of shardData.xorbs) {
281
+ const remoteXorbId = -remoteXorbHashes.length;
282
+ remoteXorbHashes.push(xorb.hash);
283
+ let i = 0;
284
+ for (const chunk of xorb.chunks) {
285
+ chunkCache.addChunkToCache(chunk.hash, remoteXorbId, i++, shardData.hmacKey);
286
+ }
287
+ }
288
+ cacheData = chunkCache.getChunk(chunk.hash, computeHmacHex);
289
+
290
+ // We backtrack a bit to check if new dedup info contains older chunks
291
+ const oldDedupedBytes = dedupedBytes;
292
+ dedupedBytes = backtrackDedup(xorb, computeHmacHex, shardData, chunkCache, chunkMetadata, dedupedBytes);
293
+
294
+ if (dedupedBytes > oldDedupedBytes) {
295
+ xorb.fileUploadedBytes[fileSource.path] ??= 0;
296
+ xorb.fileUploadedBytes[fileSource.path] += dedupedBytes - oldDedupedBytes;
297
+ }
298
+ }
299
+ }
300
+ if (cacheData === undefined) {
301
+ if (!writeChunk(xorb, chunkToCopy, chunk.hash)) {
302
+ // Failure to write chunk, maybe because it went over xorb size limit
303
+ yield nextXorb({ path: fileSource.path, uploadedBytes: processedBytes, size: fileSource.content.size });
304
+
305
+ chunkIndex = 0;
306
+ chunkXorbId = xorbId;
307
+
308
+ for (const event of pendingFileEvents) {
309
+ event.representation = event.representation.map((rep) => ({
310
+ ...rep,
311
+ xorbId: (rep.xorbId as number) >= 0 ? rep.xorbId : remoteXorbHashes[-rep.xorbId],
312
+ }));
313
+ yield event;
314
+ }
315
+ pendingFileEvents.length = 0;
316
+
317
+ if (!writeChunk(xorb, chunkToCopy, chunk.hash)) {
318
+ throw new Error("Failed to write chunk into xorb");
319
+ }
320
+ }
321
+
322
+ chunkCache.addChunkToCache(chunk.hash, xorbId, chunkIndex, null);
323
+ } else {
324
+ chunkXorbId = cacheData.xorbIndex;
325
+ chunkIndex = cacheData.chunkIndex;
326
+ dedupedBytes += chunk.length; // Track deduplicated bytes
327
+ xorb.fileUploadedBytes[fileSource.path] ??= 0;
328
+ xorb.fileUploadedBytes[fileSource.path] += chunk.length;
329
+ }
330
+
331
+ bytesSinceRemoteDedup += chunk.length;
332
+ bytesSinceLastProgressEvent += chunk.length;
333
+
334
+ // Collect metadata for building representation at the end
335
+ fileChunks.push({ hash: chunk.hash, length: chunk.length });
336
+ chunkMetadata.push({
337
+ xorbId: chunkXorbId,
338
+ chunkIndex: chunkIndex,
339
+ length: chunk.length,
340
+ });
341
+
342
+ xorb.fileProcessedBytes[fileSource.path] = processedBytes;
343
+
344
+ if (bytesSinceLastProgressEvent >= 1_000_000) {
345
+ // Emit half of the progress when processed locally, other half when uploading the xorb
346
+ bytesSinceLastProgressEvent = 0;
347
+ params.yieldCallback?.({
348
+ event: "fileProgress",
349
+ path: fileSource.path,
350
+ progress:
351
+ ((xorb.fileUploadedBytes[fileSource.path] ?? 0) +
352
+ (xorb.fileProcessedBytes[fileSource.path] - (xorb.fileUploadedBytes[fileSource.path] ?? 0)) *
353
+ PROCESSING_PROGRESS_RATIO) /
354
+ fileSource.content.size,
355
+ });
356
+ }
357
+
358
+ if (xorb.chunks.length >= MAX_XORB_CHUNKS) {
359
+ yield nextXorb({ path: fileSource.path, uploadedBytes: processedBytes, size: fileSource.content.size });
360
+
361
+ for (const event of pendingFileEvents) {
362
+ event.representation = event.representation.map((rep) => ({
363
+ ...rep,
364
+ xorbId: (rep.xorbId as number) >= 0 ? rep.xorbId : remoteXorbHashes[-rep.xorbId],
365
+ }));
366
+ yield event;
367
+ }
368
+ pendingFileEvents.length = 0;
369
+ }
370
+ }
371
+ };
372
+
373
+ while (true) {
374
+ const { done, value } = await reader.read();
375
+ if (done) {
376
+ yield* addChunks(finalizeChunker(chunker));
377
+ break;
378
+ }
379
+ processedBytes += value.length;
380
+ sourceChunks.push(value);
381
+ yield* addChunks(addDataToChunker(value, chunker));
382
+ }
383
+
384
+ const fileRepresentation = buildFileRepresentation(chunkMetadata, fileChunks, computeVerificationHashHex);
385
+ xorb.immutableData = {
386
+ chunkIndex: xorb.chunks.length,
387
+ offset: xorb.offset,
388
+ };
389
+ const dedupRatio = fileSource.content.size > 0 ? dedupedBytes / fileSource.content.size : 0;
390
+
391
+ pendingFileEvents.push({
392
+ event: "file" as const,
393
+ path: fileSource.path,
394
+ hash: computeFileHashHex(fileChunks),
395
+ sha256: fileSource.sha256,
396
+ dedupRatio,
397
+ representation: fileRepresentation,
398
+ });
399
+ }
400
+ }
401
+
402
+ if (xorb.offset > 0) {
403
+ yield xorb.event(computeXorbHashHex);
404
+ }
405
+
406
+ for (const event of pendingFileEvents) {
407
+ event.representation = event.representation.map((rep) => ({
408
+ ...rep,
409
+ xorbId: (rep.xorbId as number) >= 0 ? rep.xorbId : remoteXorbHashes[-rep.xorbId],
410
+ }));
411
+ yield event;
412
+ }
413
+ }
414
+
415
+ export function backtrackDedup(
416
+ xorb: CurrentXorbInfo,
417
+ computeHmac: (hash: string, key: string) => string,
418
+ shardData: ShardData,
419
+ chunkCache: ChunkCache,
420
+ chunkMetadata: { xorbId: number | string; chunkIndex: number; length: number }[],
421
+ dedupedBytes: number,
422
+ ): number {
423
+ const chunkIndexesToBacktrackFor = new Map<number, { xorbId: number; chunkIndex: number }>();
424
+ for (
425
+ let chunkToRecheckIndex = xorb.immutableData?.chunkIndex ?? 0;
426
+ chunkToRecheckIndex < xorb.chunks.length;
427
+ chunkToRecheckIndex++
428
+ ) {
429
+ const chunk = xorb.chunks[chunkToRecheckIndex];
430
+ const hmacHash = computeHmac(chunk.hash, shardData.hmacKey);
431
+ const cacheData = chunkCache.getChunk(hmacHash, null);
432
+ if (cacheData !== undefined) {
433
+ chunkIndexesToBacktrackFor.set(chunkToRecheckIndex, {
434
+ xorbId: cacheData.xorbIndex,
435
+ chunkIndex: cacheData.chunkIndex,
436
+ });
437
+ chunkCache.removeChunkFromCache(chunk.hash);
438
+ }
439
+ }
440
+
441
+ // Use remote dedup info to update chunk metadata for file representation
442
+ for (const metadata of chunkMetadata) {
443
+ if (metadata.xorbId === xorb.id && chunkIndexesToBacktrackFor.has(metadata.chunkIndex)) {
444
+ const backtrackData = chunkIndexesToBacktrackFor.get(metadata.chunkIndex);
445
+ if (backtrackData !== undefined) {
446
+ metadata.xorbId = backtrackData.xorbId;
447
+ metadata.chunkIndex = backtrackData.chunkIndex;
448
+ dedupedBytes += metadata.length;
449
+ }
450
+ }
451
+ }
452
+
453
+ // Remove chunks that were backtracked from xorbChunks
454
+ const xorbRangesToErase: Array<{ start: number; end: number }> = [];
455
+ for (let i = 0; i < xorb.chunks.length; i++) {
456
+ const chunk = xorb.chunks[i];
457
+ if (chunkIndexesToBacktrackFor.has(i)) {
458
+ xorbRangesToErase.push({
459
+ start: chunk.offset,
460
+ end: i < xorb.chunks.length - 1 ? xorb.chunks[i + 1].offset : xorb.offset,
461
+ });
462
+ }
463
+ }
464
+ const xorbRangesToKeep: Array<{ start: number; end: number }> = [];
465
+ let currentStart = 0;
466
+ for (let i = 0; i < xorbRangesToErase.length; i++) {
467
+ const range = xorbRangesToErase[i];
468
+ if (currentStart !== range.start) {
469
+ xorbRangesToKeep.push({ start: currentStart, end: range.start });
470
+ }
471
+ currentStart = range.end;
472
+ }
473
+ if (currentStart !== xorb.offset) {
474
+ xorbRangesToKeep.push({ start: currentStart, end: xorb.offset });
475
+ }
476
+
477
+ let currentOffset = 0;
478
+ for (const range of xorbRangesToKeep) {
479
+ if (range.start !== currentOffset) {
480
+ xorb.data.set(xorb.data.subarray(range.start, range.end), currentOffset);
481
+ }
482
+ currentOffset += range.end - range.start;
483
+ }
484
+ const newXorbChunks: Array<{ hash: string; length: number; offset: number }> = [];
485
+ const oldIndexToNewIndex = new Map<number, number>();
486
+ let erasedOffset = 0;
487
+ for (let i = 0; i < xorb.chunks.length; i++) {
488
+ const chunk = xorb.chunks[i];
489
+ if (chunkIndexesToBacktrackFor.has(i)) {
490
+ if (i < xorb.chunks.length - 1) {
491
+ erasedOffset += xorb.chunks[i + 1].offset - chunk.offset;
492
+ }
493
+ } else {
494
+ newXorbChunks.push({
495
+ hash: chunk.hash,
496
+ length: chunk.length,
497
+ offset: chunk.offset - erasedOffset,
498
+ });
499
+ // Only need a mapping if index changed (at least one previous chunk was erased)
500
+ if (erasedOffset > 0) {
501
+ oldIndexToNewIndex.set(i, newXorbChunks.length - 1);
502
+ }
503
+ }
504
+ }
505
+ xorb.chunks = newXorbChunks;
506
+ xorb.offset = currentOffset;
507
+ // Update chunkMetadata and chunkCache with new chunk indexes for the current xorb chunks
508
+ for (const chunk of chunkMetadata) {
509
+ if (chunk.xorbId === xorb.id) {
510
+ const newIndex = oldIndexToNewIndex.get(chunk.chunkIndex);
511
+ if (newIndex !== undefined) {
512
+ const cached = chunkCache.getChunk(xorb.chunks[newIndex].hash, null);
513
+ if (cached !== undefined && cached.xorbIndex === chunk.xorbId && cached.chunkIndex === chunk.chunkIndex) {
514
+ chunkCache.updateChunkIndex(xorb.chunks[newIndex].hash, newIndex);
515
+ }
516
+ chunk.chunkIndex = newIndex;
517
+ }
518
+ }
519
+ }
520
+ return dedupedBytes;
521
+ }
522
+
523
+ /**
524
+ * Removes and returns a chunk of the specified length from the sourceChunks array.
525
+ */
526
+ function removeChunkFromSourceData(sourceChunks: Array<Uint8Array>, chunkLength: number): Uint8Array {
527
+ if (chunkLength === sourceChunks[0].length) {
528
+ const chunkToCopy = sourceChunks[0];
529
+ sourceChunks.shift();
530
+ return chunkToCopy;
531
+ } else if (chunkLength < sourceChunks[0].length) {
532
+ const chunkToCopy = sourceChunks[0].subarray(0, chunkLength);
533
+ sourceChunks[0] = sourceChunks[0].subarray(chunkLength);
534
+ return chunkToCopy;
535
+ } else {
536
+ const chunkToCopy = new Uint8Array(chunkLength);
537
+ let copyOffset = 0;
538
+ let index = 0;
539
+ let toSlice = -1;
540
+ while (copyOffset < chunkLength) {
541
+ const nToCopy = Math.min(sourceChunks[index].length, chunkLength - copyOffset);
542
+ chunkToCopy.set(sourceChunks[index].subarray(0, nToCopy), copyOffset);
543
+ copyOffset += nToCopy;
544
+
545
+ if (nToCopy === sourceChunks[index].length) {
546
+ index++;
547
+ } else {
548
+ toSlice = nToCopy;
549
+ }
550
+ }
551
+ sourceChunks.splice(0, index);
552
+ if (toSlice !== -1) {
553
+ sourceChunks[0] = sourceChunks[0].subarray(toSlice);
554
+ }
555
+ return chunkToCopy;
556
+ }
557
+ }
558
+
559
+ /**
560
+ * Write a chunk header to the xorb and return the offset of where to write the next chunk
561
+ *
562
+ * If it returns 0, it means there wasn't enough space in the xorb
563
+ */
564
+ function writeChunk(xorb: CurrentXorbInfo, chunk: Uint8Array, hash: string): boolean {
565
+ const regularCompressedChunk = lz4_compress(chunk);
566
+ const bgCompressedChunk = lz4_compress(bg4_split_bytes(chunk));
567
+ const compressedChunk =
568
+ bgCompressedChunk.length < regularCompressedChunk.length ? bgCompressedChunk : regularCompressedChunk;
569
+ const chunkToWrite = compressedChunk.length < chunk.length ? compressedChunk : chunk;
570
+
571
+ if (xorb.offset + XET_CHUNK_HEADER_BYTES + chunkToWrite.length > XORB_SIZE) {
572
+ return false;
573
+ }
574
+
575
+ xorb.data[xorb.offset] = 0;
576
+ xorb.data[xorb.offset + 1] = chunkToWrite.length & 0xff;
577
+ xorb.data[xorb.offset + 2] = (chunkToWrite.length >> 8) & 0xff;
578
+ xorb.data[xorb.offset + 3] = (chunkToWrite.length >> 16) & 0xff;
579
+ xorb.data[xorb.offset + 4] =
580
+ chunkToWrite.length < chunk.length
581
+ ? bgCompressedChunk.length < regularCompressedChunk.length
582
+ ? XetChunkCompressionScheme.ByteGroupingLZ4
583
+ : XetChunkCompressionScheme.LZ4
584
+ : XetChunkCompressionScheme.None;
585
+ xorb.data[xorb.offset + 5] = chunk.length & 0xff;
586
+ xorb.data[xorb.offset + 6] = (chunk.length >> 8) & 0xff;
587
+ xorb.data[xorb.offset + 7] = (chunk.length >> 16) & 0xff;
588
+
589
+ xorb.data.set(chunkToWrite, xorb.offset + XET_CHUNK_HEADER_BYTES);
590
+
591
+ xorb.chunks.push({ hash, length: chunk.length, offset: xorb.offset });
592
+ xorb.offset += XET_CHUNK_HEADER_BYTES + chunkToWrite.length;
593
+ return true;
594
+ }
595
+
596
+ // Build file representation from collected metadata
597
+ const buildFileRepresentation = (
598
+ metadata: Array<{ xorbId: number | string; chunkIndex: number; length: number }>,
599
+ chunks: Array<{ hash: string; length: number }>,
600
+ computeVerificationHash: (hashes: string[]) => string,
601
+ ): Array<{
602
+ xorbId: number | string;
603
+ indexStart: number;
604
+ indexEnd: number;
605
+ length: number;
606
+ rangeHash: string;
607
+ }> => {
608
+ if (metadata.length === 0) {
609
+ return [];
610
+ }
611
+
612
+ const representation: Array<{
613
+ xorbId: number | string;
614
+ indexStart: number;
615
+ indexEnd: number;
616
+ length: number;
617
+ rangeHash: string;
618
+ }> = [];
619
+
620
+ let currentRange = {
621
+ xorbId: metadata[0].xorbId,
622
+ indexStart: metadata[0].chunkIndex,
623
+ indexEnd: metadata[0].chunkIndex + 1,
624
+ length: metadata[0].length,
625
+ chunkHashStart: 0,
626
+ };
627
+
628
+ for (let i = 1; i < metadata.length; i++) {
629
+ const chunk = metadata[i];
630
+
631
+ // Check if this chunk continues the current range
632
+ if (currentRange.xorbId === chunk.xorbId && currentRange.indexEnd === chunk.chunkIndex) {
633
+ // Extend current range
634
+ currentRange.indexEnd = chunk.chunkIndex + 1;
635
+ currentRange.length += chunk.length;
636
+ } else {
637
+ // Finalize current range and start a new one
638
+ const rangeHash = computeVerificationHash(chunks.slice(currentRange.chunkHashStart, i).map((x) => x.hash));
639
+ representation.push({
640
+ xorbId: currentRange.xorbId,
641
+ indexStart: currentRange.indexStart,
642
+ indexEnd: currentRange.indexEnd,
643
+ length: currentRange.length,
644
+ rangeHash,
645
+ });
646
+
647
+ currentRange = {
648
+ xorbId: chunk.xorbId,
649
+ indexStart: chunk.chunkIndex,
650
+ indexEnd: chunk.chunkIndex + 1,
651
+ length: chunk.length,
652
+ chunkHashStart: i,
653
+ };
654
+ }
655
+ }
656
+
657
+ // Finalize the last range
658
+ const rangeHash = computeVerificationHash(chunks.slice(currentRange.chunkHashStart).map((x) => x.hash));
659
+ representation.push({
660
+ xorbId: currentRange.xorbId,
661
+ indexStart: currentRange.indexStart,
662
+ indexEnd: currentRange.indexEnd,
663
+ length: currentRange.length,
664
+ rangeHash,
665
+ });
666
+
667
+ return representation;
668
+ };
669
+
670
+ /**
671
+ * Helper to load dedup info for blob contents into cache.
672
+ * Processes the blob's contents, chunks it, and loads dedup info into cache without writing to xorb.
673
+ *
674
+ * For now this is optimized for when the replacement data is at the very beginning of the file
675
+ *
676
+ * todo: handle when it's not at the beginning of the file by backingtracking xorb contents
677
+ * todo: handle when it's not at the beginning of the file by using previous content to chunk at the same boundaries as it would have in the original file
678
+ */
679
+ async function loadDedupInfoToCache(
680
+ content: Blob,
681
+ /** Will be mutated */
682
+ remoteXorbHashes: string[],
683
+ params: XetWriteTokenParams,
684
+ chunkCache: ChunkCache,
685
+ computeHmacHex: (hash: string, key: string) => string,
686
+
687
+ opts?: {
688
+ isAtBeginning?: boolean;
689
+ /**
690
+ * The end position of the content to process
691
+ *
692
+ * Will process content up to the end of the chunk after this position
693
+ */
694
+ end?: number;
695
+ /**
696
+ * The maximum number of chunks to process
697
+ *
698
+ * Will process content up to the end of the chunk after this position
699
+ */
700
+ maxChunks?: number;
701
+ },
702
+ ): Promise<void> {
703
+ const chunker = createChunker(TARGET_CHUNK_SIZE);
704
+ const cache = chunkCache;
705
+
706
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
707
+ let dedupedBytes = 0;
708
+ let chunksProcessed = 0;
709
+ let totalBytes = 0;
710
+ let bytesSinceRemoteDedup = Infinity;
711
+ const sourceChunks: Array<Uint8Array> = [];
712
+
713
+ const reader = content.stream().getReader();
714
+
715
+ const processChunks = async (chunks: Array<{ hash: string; length: number; dedup: boolean }>) => {
716
+ for (const chunk of chunks) {
717
+ chunksProcessed++;
718
+ if (opts?.isAtBeginning && chunksProcessed === 1) {
719
+ chunk.dedup = true;
720
+ }
721
+ totalBytes += chunk.length;
722
+
723
+ removeChunkFromSourceData(sourceChunks, chunk.length);
724
+
725
+ let cacheData = cache.getChunk(chunk.hash, computeHmacHex);
726
+
727
+ if (cacheData !== undefined) {
728
+ dedupedBytes += chunk.length;
729
+ bytesSinceRemoteDedup += chunk.length;
730
+ continue;
731
+ }
732
+
733
+ if (chunk.dedup && bytesSinceRemoteDedup >= INTERVAL_BETWEEN_REMOTE_DEDUP) {
734
+ const token = await xetWriteToken(params);
735
+ bytesSinceRemoteDedup = 0;
736
+
737
+ const shardResp = await (params.fetch ?? fetch)(token.casUrl + "/v1/chunks/default/" + chunk.hash, {
738
+ headers: {
739
+ Authorization: `Bearer ${token.accessToken}`,
740
+ },
741
+ });
742
+
743
+ if (shardResp.ok) {
744
+ const shard = await shardResp.blob();
745
+ const shardData = await parseShardData(shard);
746
+
747
+ for (const xorb of shardData.xorbs) {
748
+ const remoteXorbId = -remoteXorbHashes.length;
749
+ remoteXorbHashes.push(xorb.hash);
750
+ let i = 0;
751
+ for (const xorbChunk of xorb.chunks) {
752
+ cache.addChunkToCache(xorbChunk.hash, remoteXorbId, i++, shardData.hmacKey);
753
+ }
754
+ }
755
+ cacheData = cache.getChunk(chunk.hash, computeHmacHex);
756
+ }
757
+ }
758
+
759
+ if (cacheData !== undefined) {
760
+ dedupedBytes += chunk.length;
761
+ }
762
+
763
+ bytesSinceRemoteDedup += chunk.length;
764
+ }
765
+ };
766
+
767
+ while (true) {
768
+ if (opts?.end !== undefined && totalBytes >= opts.end) {
769
+ break;
770
+ }
771
+ if (opts?.maxChunks !== undefined && chunksProcessed >= opts.maxChunks) {
772
+ break;
773
+ }
774
+ const { done, value } = await reader.read();
775
+ if (done) {
776
+ await processChunks(finalizeChunker(chunker));
777
+ break;
778
+ }
779
+ sourceChunks.push(value);
780
+ await processChunks(addDataToChunker(value, chunker));
781
+ }
782
+ }