@memoryrouter/cli 0.1.0 → 0.1.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/LICENSE +21 -0
- package/README.md +85 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1531 -5
- package/package.json +29 -13
package/dist/index.js
CHANGED
|
@@ -171,8 +171,11 @@ var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
|
171
171
|
".swift",
|
|
172
172
|
".kt",
|
|
173
173
|
// modern langs
|
|
174
|
-
".mdx"
|
|
174
|
+
".mdx",
|
|
175
175
|
// mdx docs
|
|
176
|
+
".pdf",
|
|
177
|
+
".docx"
|
|
178
|
+
// binary docs (extracted to text)
|
|
176
179
|
]);
|
|
177
180
|
var MAX_ITEM_CHARS = 5e4;
|
|
178
181
|
var TARGET_CHUNK_CHARS = 8e3;
|
|
@@ -197,8 +200,28 @@ function chunkText(text, maxChars) {
|
|
|
197
200
|
if (current.trim()) chunks.push(current.trim());
|
|
198
201
|
return chunks;
|
|
199
202
|
}
|
|
203
|
+
async function extractText(filePath) {
|
|
204
|
+
const ext = path2.extname(filePath).toLowerCase();
|
|
205
|
+
if (ext === ".pdf") {
|
|
206
|
+
const { PDFParse } = await import("pdf-parse");
|
|
207
|
+
const buffer = await fsp.readFile(filePath);
|
|
208
|
+
const parser = new PDFParse({ data: buffer });
|
|
209
|
+
try {
|
|
210
|
+
const data = await parser.getText();
|
|
211
|
+
return data.text;
|
|
212
|
+
} finally {
|
|
213
|
+
await parser.destroy();
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (ext === ".docx") {
|
|
217
|
+
const mammoth = await import("mammoth");
|
|
218
|
+
const result = await mammoth.extractRawText({ path: filePath });
|
|
219
|
+
return result.value;
|
|
220
|
+
}
|
|
221
|
+
return fsp.readFile(filePath, "utf-8");
|
|
222
|
+
}
|
|
200
223
|
async function fileToLines(filePath) {
|
|
201
|
-
const content = await
|
|
224
|
+
const content = await extractText(filePath);
|
|
202
225
|
const stat = await fsp.stat(filePath);
|
|
203
226
|
const timestamp = Math.floor(stat.mtimeMs);
|
|
204
227
|
const filename = path2.basename(filePath);
|
|
@@ -212,8 +235,8 @@ async function fileToLines(filePath) {
|
|
|
212
235
|
}];
|
|
213
236
|
}
|
|
214
237
|
const chunks = chunkText(trimmed, TARGET_CHUNK_CHARS);
|
|
215
|
-
return chunks.map((
|
|
216
|
-
content: `[${filename} part ${i + 1}/${chunks.length}] ${
|
|
238
|
+
return chunks.map((chunk2, i) => ({
|
|
239
|
+
content: `[${filename} part ${i + 1}/${chunks.length}] ${chunk2}`,
|
|
217
240
|
role: "user",
|
|
218
241
|
timestamp
|
|
219
242
|
}));
|
|
@@ -380,9 +403,1484 @@ Sending ${batches.length} batch${batches.length > 1 ? "es" : ""}...`);
|
|
|
380
403
|
}
|
|
381
404
|
}
|
|
382
405
|
|
|
406
|
+
// src/chatgpt/source.ts
|
|
407
|
+
import fs6 from "fs";
|
|
408
|
+
import os2 from "os";
|
|
409
|
+
import path5 from "path";
|
|
410
|
+
import crypto from "crypto";
|
|
411
|
+
|
|
412
|
+
// src/chatgpt/zip.ts
|
|
413
|
+
import fs3 from "fs";
|
|
414
|
+
import path3 from "path";
|
|
415
|
+
import zlib from "zlib";
|
|
416
|
+
import { once } from "events";
|
|
417
|
+
var DEFAULT_ZIP_LIMITS = {
|
|
418
|
+
maxArchiveBytes: 2 * 1024 * 1024 * 1024,
|
|
419
|
+
// 2 GiB archive file
|
|
420
|
+
maxEntries: 2e5,
|
|
421
|
+
maxEntryBytes: 512 * 1024 * 1024,
|
|
422
|
+
// 512 MiB per entry (a single conversations.json shard)
|
|
423
|
+
maxTotalBytes: 4 * 1024 * 1024 * 1024,
|
|
424
|
+
// 4 GiB extracted total
|
|
425
|
+
maxRatio: 200,
|
|
426
|
+
// uncompressed/compressed ceiling per entry (bomb guard)
|
|
427
|
+
maxDepth: 24,
|
|
428
|
+
maxCentralDirBytes: 64 * 1024 * 1024
|
|
429
|
+
// 64 MiB central directory (bounds pre-alloc)
|
|
430
|
+
};
|
|
431
|
+
var ArchiveError = class extends Error {
|
|
432
|
+
constructor(message) {
|
|
433
|
+
super(message);
|
|
434
|
+
this.name = "ArchiveError";
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
var SIG_EOCD = 101010256;
|
|
438
|
+
var SIG_EOCD64_LOCATOR = 117853008;
|
|
439
|
+
var SIG_CENTRAL = 33639248;
|
|
440
|
+
var SIG_LOCAL = 67324752;
|
|
441
|
+
var S_IFMT = 61440;
|
|
442
|
+
var S_IFLNK = 40960;
|
|
443
|
+
var S_IFREG = 32768;
|
|
444
|
+
var S_IFDIR = 16384;
|
|
445
|
+
var GPF_ENCRYPTED = 1;
|
|
446
|
+
var GPF_DATA_DESCRIPTOR = 8;
|
|
447
|
+
var GPF_ENHANCED_DEFLATE = 16;
|
|
448
|
+
var GPF_PATCHED = 32;
|
|
449
|
+
var GPF_STRONG_ENCRYPTION = 64;
|
|
450
|
+
var GPF_UNSUPPORTED_MASK = GPF_ENCRYPTED | GPF_DATA_DESCRIPTOR | GPF_ENHANCED_DEFLATE | GPF_PATCHED | GPF_STRONG_ENCRYPTION;
|
|
451
|
+
var CRC32_TABLE = (() => {
|
|
452
|
+
const table = new Uint32Array(256);
|
|
453
|
+
for (let n = 0; n < 256; n++) {
|
|
454
|
+
let c = n;
|
|
455
|
+
for (let k = 0; k < 8; k++) {
|
|
456
|
+
c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
457
|
+
}
|
|
458
|
+
table[n] = c >>> 0;
|
|
459
|
+
}
|
|
460
|
+
return table;
|
|
461
|
+
})();
|
|
462
|
+
function crc32Update(crc, buf) {
|
|
463
|
+
let c = crc ^ 4294967295;
|
|
464
|
+
for (let i = 0; i < buf.length; i++) {
|
|
465
|
+
c = CRC32_TABLE[(c ^ buf[i]) & 255] ^ c >>> 8;
|
|
466
|
+
}
|
|
467
|
+
return (c ^ 4294967295) >>> 0;
|
|
468
|
+
}
|
|
469
|
+
function sanitizeEntryName(rawName, maxDepth) {
|
|
470
|
+
if (rawName.includes("\0")) throw new ArchiveError(`Entry name contains NUL byte`);
|
|
471
|
+
const name = rawName.replace(/\\/g, "/");
|
|
472
|
+
if (name.startsWith("/")) throw new ArchiveError(`Absolute path rejected: ${rawName}`);
|
|
473
|
+
if (/^[a-zA-Z]:/.test(name)) throw new ArchiveError(`Drive-letter path rejected: ${rawName}`);
|
|
474
|
+
const parts = name.split("/").filter((p) => p !== "" && p !== ".");
|
|
475
|
+
if (parts.some((p) => p === "..")) throw new ArchiveError(`Path traversal rejected: ${rawName}`);
|
|
476
|
+
if (parts.length > maxDepth) throw new ArchiveError(`Path nesting too deep: ${rawName}`);
|
|
477
|
+
return parts.join("/");
|
|
478
|
+
}
|
|
479
|
+
function readExact(fd, position, length) {
|
|
480
|
+
const buf = Buffer.allocUnsafe(length);
|
|
481
|
+
let read = 0;
|
|
482
|
+
while (read < length) {
|
|
483
|
+
const n = fs3.readSync(fd, buf, read, length - read, position + read);
|
|
484
|
+
if (n === 0) throw new ArchiveError("Unexpected end of archive while reading");
|
|
485
|
+
read += n;
|
|
486
|
+
}
|
|
487
|
+
return buf;
|
|
488
|
+
}
|
|
489
|
+
function readEocd(fd, fileSize) {
|
|
490
|
+
const maxTail = Math.min(fileSize, 65557);
|
|
491
|
+
const tail = readExact(fd, fileSize - maxTail, maxTail);
|
|
492
|
+
const tailStart = fileSize - maxTail;
|
|
493
|
+
for (let i = tail.length - 22; i >= 0; i--) {
|
|
494
|
+
if (tail.readUInt32LE(i) === SIG_EOCD) {
|
|
495
|
+
const diskNumber = tail.readUInt16LE(i + 4);
|
|
496
|
+
const cdStartDisk = tail.readUInt16LE(i + 6);
|
|
497
|
+
const diskEntryCount = tail.readUInt16LE(i + 8);
|
|
498
|
+
const entryCount = tail.readUInt16LE(i + 10);
|
|
499
|
+
const cdSize = tail.readUInt32LE(i + 12);
|
|
500
|
+
const cdOffset = tail.readUInt32LE(i + 16);
|
|
501
|
+
const commentLen = tail.readUInt16LE(i + 20);
|
|
502
|
+
if (entryCount === 65535 || cdSize === 4294967295 || cdOffset === 4294967295) {
|
|
503
|
+
throw new ArchiveError("ZIP64 archive not supported \u2014 extract it and import the folder instead");
|
|
504
|
+
}
|
|
505
|
+
for (let j = i - 20; j >= 0; j--) {
|
|
506
|
+
if (tail.readUInt32LE(j) === SIG_EOCD64_LOCATOR) {
|
|
507
|
+
throw new ArchiveError("ZIP64 archive not supported \u2014 extract it and import the folder instead");
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
if (diskNumber !== 0 || cdStartDisk !== 0 || diskEntryCount !== entryCount) {
|
|
511
|
+
throw new ArchiveError("Multi-disk (spanned) archive not supported");
|
|
512
|
+
}
|
|
513
|
+
if (i + 22 + commentLen > tail.length) {
|
|
514
|
+
throw new ArchiveError("EOCD comment length exceeds archive tail");
|
|
515
|
+
}
|
|
516
|
+
return { entryCount, cdSize, cdOffset, eocdOffset: tailStart + i };
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
throw new ArchiveError("Not a ZIP archive (no End Of Central Directory record found)");
|
|
520
|
+
}
|
|
521
|
+
function readCentralDirectory(fd, cdOffset, cdSize, limits) {
|
|
522
|
+
const cd = readExact(fd, cdOffset, cdSize);
|
|
523
|
+
const entries = [];
|
|
524
|
+
let p = 0;
|
|
525
|
+
while (p + 46 <= cd.length) {
|
|
526
|
+
if (cd.readUInt32LE(p) !== SIG_CENTRAL) break;
|
|
527
|
+
const flags = cd.readUInt16LE(p + 8);
|
|
528
|
+
const method = cd.readUInt16LE(p + 10);
|
|
529
|
+
const crc32 = cd.readUInt32LE(p + 16) >>> 0;
|
|
530
|
+
const compSize = cd.readUInt32LE(p + 20);
|
|
531
|
+
const uncompSize = cd.readUInt32LE(p + 24);
|
|
532
|
+
const nameLen = cd.readUInt16LE(p + 28);
|
|
533
|
+
const extraLen = cd.readUInt16LE(p + 30);
|
|
534
|
+
const commentLen = cd.readUInt16LE(p + 32);
|
|
535
|
+
const externalAttrs = cd.readUInt32LE(p + 38);
|
|
536
|
+
const localHeaderOffset = cd.readUInt32LE(p + 42);
|
|
537
|
+
if (p + 46 + nameLen + extraLen + commentLen > cd.length) {
|
|
538
|
+
throw new ArchiveError("Central directory record overruns declared central directory");
|
|
539
|
+
}
|
|
540
|
+
const name = cd.toString("utf8", p + 46, p + 46 + nameLen);
|
|
541
|
+
const unixMode = externalAttrs >>> 16 & 65535;
|
|
542
|
+
entries.push({
|
|
543
|
+
name,
|
|
544
|
+
flags,
|
|
545
|
+
method,
|
|
546
|
+
crc32,
|
|
547
|
+
compSize,
|
|
548
|
+
uncompSize,
|
|
549
|
+
localHeaderOffset,
|
|
550
|
+
unixMode,
|
|
551
|
+
isDir: name.endsWith("/")
|
|
552
|
+
});
|
|
553
|
+
if (entries.length > limits.maxEntries) {
|
|
554
|
+
throw new ArchiveError(`Too many entries (> ${limits.maxEntries})`);
|
|
555
|
+
}
|
|
556
|
+
p += 46 + nameLen + extraLen + commentLen;
|
|
557
|
+
}
|
|
558
|
+
if (p !== cd.length) {
|
|
559
|
+
throw new ArchiveError("Central directory has trailing slack or a truncated record");
|
|
560
|
+
}
|
|
561
|
+
return entries;
|
|
562
|
+
}
|
|
563
|
+
function validateEntries(entries, limits) {
|
|
564
|
+
let total = 0;
|
|
565
|
+
const seen = /* @__PURE__ */ new Set();
|
|
566
|
+
for (const e of entries) {
|
|
567
|
+
const safe = sanitizeEntryName(e.name, limits.maxDepth);
|
|
568
|
+
if (e.flags & GPF_ENCRYPTED) throw new ArchiveError(`Encrypted entry rejected: ${e.name}`);
|
|
569
|
+
if (e.flags & GPF_STRONG_ENCRYPTION) throw new ArchiveError(`Encrypted entry rejected: ${e.name}`);
|
|
570
|
+
if (e.flags & GPF_DATA_DESCRIPTOR) {
|
|
571
|
+
throw new ArchiveError(`Streaming (data-descriptor) entry rejected: ${e.name}`);
|
|
572
|
+
}
|
|
573
|
+
if (e.flags & GPF_UNSUPPORTED_MASK) {
|
|
574
|
+
throw new ArchiveError(`Unsupported general-purpose flags (0x${e.flags.toString(16)}) in ${e.name}`);
|
|
575
|
+
}
|
|
576
|
+
if (!e.isDir) {
|
|
577
|
+
const key = safe.toLowerCase();
|
|
578
|
+
if (seen.has(key)) throw new ArchiveError(`Duplicate conflicting entry path: ${e.name}`);
|
|
579
|
+
seen.add(key);
|
|
580
|
+
}
|
|
581
|
+
if (e.unixMode !== 0) {
|
|
582
|
+
const fmt = e.unixMode & S_IFMT;
|
|
583
|
+
if (fmt === S_IFLNK) throw new ArchiveError(`Symlink entry rejected: ${e.name}`);
|
|
584
|
+
if (fmt !== 0 && fmt !== S_IFREG && fmt !== S_IFDIR) {
|
|
585
|
+
throw new ArchiveError(`Special (non-regular) entry rejected: ${e.name}`);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (e.isDir) continue;
|
|
589
|
+
if (e.method !== 0 && e.method !== 8) {
|
|
590
|
+
throw new ArchiveError(`Unsupported compression method ${e.method} in ${e.name}`);
|
|
591
|
+
}
|
|
592
|
+
if (e.uncompSize > limits.maxEntryBytes) {
|
|
593
|
+
throw new ArchiveError(`Entry too large (${e.uncompSize} > ${limits.maxEntryBytes}): ${e.name}`);
|
|
594
|
+
}
|
|
595
|
+
if (e.compSize > 0 && e.uncompSize / e.compSize > limits.maxRatio) {
|
|
596
|
+
throw new ArchiveError(`Suspicious compression ratio in ${e.name} (possible zip bomb)`);
|
|
597
|
+
}
|
|
598
|
+
total += e.uncompSize;
|
|
599
|
+
if (total > limits.maxTotalBytes) {
|
|
600
|
+
throw new ArchiveError(`Total uncompressed size exceeds ${limits.maxTotalBytes}`);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
function readAndVerifyLocalHeader(fd, entry, limits) {
|
|
605
|
+
const local = readExact(fd, entry.localHeaderOffset, 30);
|
|
606
|
+
if (local.readUInt32LE(0) !== SIG_LOCAL) {
|
|
607
|
+
throw new ArchiveError(`Corrupt local header for ${entry.name}`);
|
|
608
|
+
}
|
|
609
|
+
const localFlags = local.readUInt16LE(6);
|
|
610
|
+
const localMethod = local.readUInt16LE(8);
|
|
611
|
+
const localCompSize = local.readUInt32LE(18);
|
|
612
|
+
const localUncompSize = local.readUInt32LE(22);
|
|
613
|
+
const nameLen = local.readUInt16LE(26);
|
|
614
|
+
const extraLen = local.readUInt16LE(28);
|
|
615
|
+
if (localFlags & GPF_ENCRYPTED) throw new ArchiveError(`Encrypted entry rejected: ${entry.name}`);
|
|
616
|
+
if (localFlags & GPF_DATA_DESCRIPTOR) {
|
|
617
|
+
throw new ArchiveError(`Streaming (data-descriptor) entry rejected: ${entry.name}`);
|
|
618
|
+
}
|
|
619
|
+
if (localFlags & GPF_UNSUPPORTED_MASK) {
|
|
620
|
+
throw new ArchiveError(`Unsupported general-purpose flags in local header of ${entry.name}`);
|
|
621
|
+
}
|
|
622
|
+
if (localMethod !== entry.method) {
|
|
623
|
+
throw new ArchiveError(`Local/central compression method mismatch for ${entry.name}`);
|
|
624
|
+
}
|
|
625
|
+
const nameBuf = readExact(fd, entry.localHeaderOffset + 30, nameLen);
|
|
626
|
+
const localName = nameBuf.toString("utf8");
|
|
627
|
+
if (localName !== entry.name) {
|
|
628
|
+
throw new ArchiveError(`Local/central filename mismatch for ${entry.name}`);
|
|
629
|
+
}
|
|
630
|
+
if (localCompSize !== entry.compSize) {
|
|
631
|
+
throw new ArchiveError(`Local/central compressed-size mismatch for ${entry.name}`);
|
|
632
|
+
}
|
|
633
|
+
if (localUncompSize !== entry.uncompSize) {
|
|
634
|
+
throw new ArchiveError(`Local/central uncompressed-size mismatch for ${entry.name}`);
|
|
635
|
+
}
|
|
636
|
+
sanitizeEntryName(localName, limits.maxDepth);
|
|
637
|
+
return entry.localHeaderOffset + 30 + nameLen + extraLen;
|
|
638
|
+
}
|
|
639
|
+
async function extractEntry(fd, entry, destPath, limits, runningTotalStart) {
|
|
640
|
+
const dataOffset = readAndVerifyLocalHeader(fd, entry, limits);
|
|
641
|
+
fs3.mkdirSync(path3.dirname(destPath), { recursive: true });
|
|
642
|
+
let out;
|
|
643
|
+
try {
|
|
644
|
+
out = fs3.openSync(destPath, "wx");
|
|
645
|
+
} catch (err) {
|
|
646
|
+
if (err.code === "EEXIST") {
|
|
647
|
+
throw new ArchiveError(`Destination already exists (refusing to overwrite): ${destPath}`);
|
|
648
|
+
}
|
|
649
|
+
throw err;
|
|
650
|
+
}
|
|
651
|
+
let written = 0;
|
|
652
|
+
let crc = 0;
|
|
653
|
+
let cleanupNeeded = true;
|
|
654
|
+
const cap = limits.maxEntryBytes;
|
|
655
|
+
const CHUNK = 1 << 20;
|
|
656
|
+
const cleanup = () => {
|
|
657
|
+
try {
|
|
658
|
+
fs3.closeSync(out);
|
|
659
|
+
} catch {
|
|
660
|
+
}
|
|
661
|
+
if (cleanupNeeded) {
|
|
662
|
+
try {
|
|
663
|
+
fs3.rmSync(destPath, { force: true });
|
|
664
|
+
} catch {
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
};
|
|
668
|
+
const pushOut = (chunk2) => {
|
|
669
|
+
written += chunk2.length;
|
|
670
|
+
if (written > cap) throw new ArchiveError(`Entry expanded beyond ${cap} bytes: ${entry.name}`);
|
|
671
|
+
if (runningTotalStart + written > limits.maxTotalBytes) {
|
|
672
|
+
throw new ArchiveError(`Total uncompressed size exceeds ${limits.maxTotalBytes}`);
|
|
673
|
+
}
|
|
674
|
+
crc = crc32Update(crc, chunk2);
|
|
675
|
+
fs3.writeSync(out, chunk2);
|
|
676
|
+
};
|
|
677
|
+
try {
|
|
678
|
+
if (entry.method === 0) {
|
|
679
|
+
let remaining = entry.compSize;
|
|
680
|
+
let pos = dataOffset;
|
|
681
|
+
while (remaining > 0) {
|
|
682
|
+
const n = Math.min(CHUNK, remaining);
|
|
683
|
+
pushOut(readExact(fd, pos, n));
|
|
684
|
+
pos += n;
|
|
685
|
+
remaining -= n;
|
|
686
|
+
}
|
|
687
|
+
} else {
|
|
688
|
+
const stream = zlib.createInflateRaw();
|
|
689
|
+
let dataError = null;
|
|
690
|
+
stream.on("data", (c) => {
|
|
691
|
+
try {
|
|
692
|
+
pushOut(c);
|
|
693
|
+
} catch (err) {
|
|
694
|
+
dataError = err;
|
|
695
|
+
stream.destroy(err);
|
|
696
|
+
}
|
|
697
|
+
});
|
|
698
|
+
const ended = new Promise((resolve, reject) => {
|
|
699
|
+
stream.on("error", reject);
|
|
700
|
+
stream.on("end", resolve);
|
|
701
|
+
});
|
|
702
|
+
try {
|
|
703
|
+
let remaining = entry.compSize;
|
|
704
|
+
let pos = dataOffset;
|
|
705
|
+
while (remaining > 0) {
|
|
706
|
+
const n = Math.min(CHUNK, remaining);
|
|
707
|
+
const buf = readExact(fd, pos, n);
|
|
708
|
+
pos += n;
|
|
709
|
+
remaining -= n;
|
|
710
|
+
if (!stream.write(buf)) {
|
|
711
|
+
await Promise.race([once(stream, "drain"), ended]);
|
|
712
|
+
}
|
|
713
|
+
if (dataError) throw dataError;
|
|
714
|
+
}
|
|
715
|
+
stream.end();
|
|
716
|
+
await ended;
|
|
717
|
+
} catch (err) {
|
|
718
|
+
stream.destroy();
|
|
719
|
+
throw dataError ?? err;
|
|
720
|
+
}
|
|
721
|
+
if (dataError) throw dataError;
|
|
722
|
+
}
|
|
723
|
+
if (written !== entry.uncompSize) {
|
|
724
|
+
throw new ArchiveError(
|
|
725
|
+
`Uncompressed size mismatch for ${entry.name} (declared ${entry.uncompSize}, actual ${written})`
|
|
726
|
+
);
|
|
727
|
+
}
|
|
728
|
+
if (crc !== entry.crc32) {
|
|
729
|
+
throw new ArchiveError(`CRC-32 mismatch for ${entry.name} (data corrupt or tampered)`);
|
|
730
|
+
}
|
|
731
|
+
cleanupNeeded = false;
|
|
732
|
+
return written;
|
|
733
|
+
} finally {
|
|
734
|
+
cleanup();
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
function readAndVerifyDirectory(fd, fileSize, limits) {
|
|
738
|
+
const eocd = readEocd(fd, fileSize);
|
|
739
|
+
if (eocd.cdSize > limits.maxCentralDirBytes) {
|
|
740
|
+
throw new ArchiveError(`Central directory too large (${eocd.cdSize} > ${limits.maxCentralDirBytes})`);
|
|
741
|
+
}
|
|
742
|
+
if (eocd.cdOffset > fileSize || eocd.cdSize > fileSize || eocd.cdOffset + eocd.cdSize > fileSize) {
|
|
743
|
+
throw new ArchiveError("Central directory out of bounds");
|
|
744
|
+
}
|
|
745
|
+
if (eocd.cdOffset + eocd.cdSize !== eocd.eocdOffset) {
|
|
746
|
+
throw new ArchiveError("Central directory does not abut the EOCD (structural slack)");
|
|
747
|
+
}
|
|
748
|
+
const entries = readCentralDirectory(fd, eocd.cdOffset, eocd.cdSize, limits);
|
|
749
|
+
if (entries.length !== eocd.entryCount) {
|
|
750
|
+
throw new ArchiveError(
|
|
751
|
+
`EOCD entry-count mismatch (declared ${eocd.entryCount}, parsed ${entries.length})`
|
|
752
|
+
);
|
|
753
|
+
}
|
|
754
|
+
validateEntries(entries, limits);
|
|
755
|
+
return entries;
|
|
756
|
+
}
|
|
757
|
+
async function safeExtract(zipPath, destDir, select, limits = DEFAULT_ZIP_LIMITS) {
|
|
758
|
+
const stat = fs3.statSync(zipPath);
|
|
759
|
+
if (!stat.isFile()) throw new ArchiveError(`Not a file: ${zipPath}`);
|
|
760
|
+
if (stat.size > limits.maxArchiveBytes) {
|
|
761
|
+
throw new ArchiveError(`Archive too large (${stat.size} > ${limits.maxArchiveBytes})`);
|
|
762
|
+
}
|
|
763
|
+
const fd = fs3.openSync(zipPath, "r");
|
|
764
|
+
try {
|
|
765
|
+
const entries = readAndVerifyDirectory(fd, stat.size, limits);
|
|
766
|
+
fs3.mkdirSync(destDir, { recursive: true });
|
|
767
|
+
const resolvedRoot = path3.resolve(destDir);
|
|
768
|
+
const extractedFiles = [];
|
|
769
|
+
let totalUncompressed = 0;
|
|
770
|
+
for (const entry of entries) {
|
|
771
|
+
if (entry.isDir) continue;
|
|
772
|
+
const safeName = sanitizeEntryName(entry.name, limits.maxDepth);
|
|
773
|
+
if (!select(safeName)) continue;
|
|
774
|
+
const destPath = path3.resolve(resolvedRoot, safeName);
|
|
775
|
+
if (destPath !== resolvedRoot && !destPath.startsWith(resolvedRoot + path3.sep)) {
|
|
776
|
+
throw new ArchiveError(`Refusing to write outside destination: ${entry.name}`);
|
|
777
|
+
}
|
|
778
|
+
totalUncompressed += await extractEntry(fd, entry, destPath, limits, totalUncompressed);
|
|
779
|
+
extractedFiles.push(safeName);
|
|
780
|
+
}
|
|
781
|
+
return {
|
|
782
|
+
extractedFiles,
|
|
783
|
+
totalEntries: entries.filter((e) => !e.isDir).length,
|
|
784
|
+
totalUncompressedBytes: totalUncompressed
|
|
785
|
+
};
|
|
786
|
+
} finally {
|
|
787
|
+
fs3.closeSync(fd);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// src/chatgpt/discover.ts
|
|
792
|
+
import fs4 from "fs";
|
|
793
|
+
import path4 from "path";
|
|
794
|
+
var MAX_WALK_ENTRIES = 5e5;
|
|
795
|
+
var MAX_WALK_DEPTH = 64;
|
|
796
|
+
var MAX_WALK_TOTAL_BYTES = 8 * 1024 * 1024 * 1024;
|
|
797
|
+
function isConversationShard(relPath) {
|
|
798
|
+
const base = path4.basename(relPath).toLowerCase();
|
|
799
|
+
if (/^conversations([-_ ]?\d+| \(\d+\))?\.json$/.test(base)) return true;
|
|
800
|
+
const parts = relPath.split(/[\\/]/);
|
|
801
|
+
if (parts.length >= 2 && parts[parts.length - 2].toLowerCase() === "conversations" && base.endsWith(".json")) {
|
|
802
|
+
return true;
|
|
803
|
+
}
|
|
804
|
+
return false;
|
|
805
|
+
}
|
|
806
|
+
function isMemoryFile(relPath) {
|
|
807
|
+
const base = path4.basename(relPath).toLowerCase();
|
|
808
|
+
return base.endsWith(".json") && /memor/.test(base);
|
|
809
|
+
}
|
|
810
|
+
function naturalKey(name) {
|
|
811
|
+
return name.toLowerCase().replace(/\d+/g, (n) => n.padStart(12, "0"));
|
|
812
|
+
}
|
|
813
|
+
function walk(dir, root, depth, state) {
|
|
814
|
+
if (depth > MAX_WALK_DEPTH) throw new Error(`Export directory nested too deep (> ${MAX_WALK_DEPTH})`);
|
|
815
|
+
const entries = fs4.readdirSync(dir, { withFileTypes: true });
|
|
816
|
+
for (const entry of entries) {
|
|
817
|
+
if (state.files.length > MAX_WALK_ENTRIES) throw new Error("Too many files in export directory");
|
|
818
|
+
const full = path4.join(dir, entry.name);
|
|
819
|
+
if (entry.isSymbolicLink()) {
|
|
820
|
+
state.symlinks++;
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
if (entry.isDirectory()) {
|
|
824
|
+
walk(full, root, depth + 1, state);
|
|
825
|
+
} else if (entry.isFile()) {
|
|
826
|
+
const size = fs4.statSync(full).size;
|
|
827
|
+
state.totalBytes += size;
|
|
828
|
+
if (state.totalBytes > MAX_WALK_TOTAL_BYTES) {
|
|
829
|
+
throw new Error(`Export directory too large (> ${MAX_WALK_TOTAL_BYTES} bytes)`);
|
|
830
|
+
}
|
|
831
|
+
state.files.push(full);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
function discoverArchive(root) {
|
|
836
|
+
const stat = fs4.lstatSync(root);
|
|
837
|
+
if (stat.isSymbolicLink()) throw new Error(`Refusing to follow symlinked path: ${root}`);
|
|
838
|
+
const state = { files: [], symlinks: 0, totalBytes: 0 };
|
|
839
|
+
let base;
|
|
840
|
+
if (stat.isFile()) {
|
|
841
|
+
state.files.push(root);
|
|
842
|
+
base = path4.dirname(root);
|
|
843
|
+
} else if (stat.isDirectory()) {
|
|
844
|
+
base = root;
|
|
845
|
+
walk(root, root, 0, state);
|
|
846
|
+
} else {
|
|
847
|
+
throw new Error(`Not a file or directory: ${root}`);
|
|
848
|
+
}
|
|
849
|
+
const conversationShards = [];
|
|
850
|
+
const memoryFiles = [];
|
|
851
|
+
const ignoredFiles = [];
|
|
852
|
+
for (const abs of state.files) {
|
|
853
|
+
const rel = path4.relative(base, abs) || path4.basename(abs);
|
|
854
|
+
if (isConversationShard(rel)) conversationShards.push(abs);
|
|
855
|
+
else if (isMemoryFile(rel)) memoryFiles.push(abs);
|
|
856
|
+
else if (abs.toLowerCase().endsWith(".json")) ignoredFiles.push(abs);
|
|
857
|
+
}
|
|
858
|
+
const relKey = (abs) => naturalKey(path4.relative(base, abs));
|
|
859
|
+
conversationShards.sort((a, b) => relKey(a).localeCompare(relKey(b)));
|
|
860
|
+
memoryFiles.sort((a, b) => relKey(a).localeCompare(relKey(b)));
|
|
861
|
+
ignoredFiles.sort((a, b) => relKey(a).localeCompare(relKey(b)));
|
|
862
|
+
if (conversationShards.length === 0) {
|
|
863
|
+
throw new Error(
|
|
864
|
+
"No conversations.json (or numbered conversation shards) found. Point at your extracted ChatGPT export folder or the export .zip."
|
|
865
|
+
);
|
|
866
|
+
}
|
|
867
|
+
return { root, conversationShards, memoryFiles, ignoredFiles, symlinksSkipped: state.symlinks };
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// src/chatgpt/load.ts
|
|
871
|
+
import fs5 from "fs";
|
|
872
|
+
|
|
873
|
+
// src/chatgpt/ids.ts
|
|
874
|
+
import { createHash } from "crypto";
|
|
875
|
+
var PARSER_VERSION = 1;
|
|
876
|
+
var CHUNK_VERSION = 1;
|
|
877
|
+
var SOURCE_PLATFORM = "chatgpt";
|
|
878
|
+
function sha256hex(input) {
|
|
879
|
+
return createHash("sha256").update(input, "utf8").digest("hex");
|
|
880
|
+
}
|
|
881
|
+
function canonicalJson(value) {
|
|
882
|
+
return JSON.stringify(sortKeys(value));
|
|
883
|
+
}
|
|
884
|
+
function sortKeys(value) {
|
|
885
|
+
if (Array.isArray(value)) return value.map(sortKeys);
|
|
886
|
+
if (value && typeof value === "object") {
|
|
887
|
+
const out = {};
|
|
888
|
+
for (const key of Object.keys(value).sort()) {
|
|
889
|
+
out[key] = sortKeys(value[key]);
|
|
890
|
+
}
|
|
891
|
+
return out;
|
|
892
|
+
}
|
|
893
|
+
return value;
|
|
894
|
+
}
|
|
895
|
+
function normalizeText(input) {
|
|
896
|
+
return input.normalize("NFC").replace(/\r\n?/g, "\n").trim();
|
|
897
|
+
}
|
|
898
|
+
function normalizeTitle(input) {
|
|
899
|
+
return normalizeText(input).replace(/\s+/g, " ");
|
|
900
|
+
}
|
|
901
|
+
function vaultFingerprint(memoryKey) {
|
|
902
|
+
return `mrvault_${sha256hex(memoryKey).slice(0, 16)}`;
|
|
903
|
+
}
|
|
904
|
+
function externalId(conversationId, messageId) {
|
|
905
|
+
return `${SOURCE_PLATFORM}:${escapeIdPart(conversationId)}:${escapeIdPart(messageId)}:v${PARSER_VERSION}`;
|
|
906
|
+
}
|
|
907
|
+
function escapeIdPart(s) {
|
|
908
|
+
return s.replace(/%/g, "%25").replace(/:/g, "%3A");
|
|
909
|
+
}
|
|
910
|
+
function recordHash(fields) {
|
|
911
|
+
return sha256hex(
|
|
912
|
+
canonicalJson({
|
|
913
|
+
conversationId: fields.conversationId,
|
|
914
|
+
messageId: fields.messageId,
|
|
915
|
+
role: fields.role,
|
|
916
|
+
text: normalizeText(fields.text),
|
|
917
|
+
timestamp: fields.timestamp,
|
|
918
|
+
v: PARSER_VERSION
|
|
919
|
+
})
|
|
920
|
+
).slice(0, 32);
|
|
921
|
+
}
|
|
922
|
+
function conversationContentHash(fields) {
|
|
923
|
+
return sha256hex(canonicalJson(fields)).slice(0, 32);
|
|
924
|
+
}
|
|
925
|
+
function archiveContentId(conversationContentHashes) {
|
|
926
|
+
const canonical = [...conversationContentHashes].sort().join("\n");
|
|
927
|
+
return `arc_${sha256hex(`v${PARSER_VERSION}
|
|
928
|
+
${canonical}`).slice(0, 24)}`;
|
|
929
|
+
}
|
|
930
|
+
function deriveImportId(archiveId, fingerprint) {
|
|
931
|
+
return `imp_${sha256hex(`${archiveId}|${fingerprint}|p${PARSER_VERSION}|c${CHUNK_VERSION}`).slice(0, 24)}`;
|
|
932
|
+
}
|
|
933
|
+
function previewDigest(preview) {
|
|
934
|
+
return `pvd_${sha256hex(canonicalJson(preview)).slice(0, 32)}`;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// src/chatgpt/parser.ts
|
|
938
|
+
function toMs(seconds, fallback) {
|
|
939
|
+
if (typeof seconds === "number" && isFinite(seconds) && seconds > 0) return Math.round(seconds * 1e3);
|
|
940
|
+
return fallback;
|
|
941
|
+
}
|
|
942
|
+
function extractText2(content) {
|
|
943
|
+
if (!content) return { text: null, reason: "no_content", unsupportedParts: 0 };
|
|
944
|
+
const type = content.content_type || "text";
|
|
945
|
+
if (Array.isArray(content.parts)) {
|
|
946
|
+
const strings = content.parts.filter((p) => typeof p === "string");
|
|
947
|
+
const unsupportedParts = content.parts.length - strings.length;
|
|
948
|
+
const joined = normalizeText(strings.join("\n"));
|
|
949
|
+
if (joined) return { text: joined, unsupportedParts };
|
|
950
|
+
if (content.parts.length > 0) return { text: null, reason: `unsupported_content:${type}`, unsupportedParts };
|
|
951
|
+
return { text: null, reason: "empty", unsupportedParts: 0 };
|
|
952
|
+
}
|
|
953
|
+
if (typeof content.text === "string" && normalizeText(content.text)) {
|
|
954
|
+
return { text: normalizeText(content.text), unsupportedParts: 0 };
|
|
955
|
+
}
|
|
956
|
+
if (typeof content.result === "string" && normalizeText(content.result)) {
|
|
957
|
+
return { text: normalizeText(content.result), unsupportedParts: 0 };
|
|
958
|
+
}
|
|
959
|
+
return { text: null, reason: `unsupported_content:${type}`, unsupportedParts: 0 };
|
|
960
|
+
}
|
|
961
|
+
function conversationIdOf(conv, mapping) {
|
|
962
|
+
const explicit = conv.conversation_id || conv.id;
|
|
963
|
+
if (explicit) return explicit;
|
|
964
|
+
const firstNode = Object.keys(mapping).sort()[0] || "";
|
|
965
|
+
return `conv_${sha256hex(`${conv.title || ""}|${conv.create_time || 0}|${firstNode}`).slice(0, 16)}`;
|
|
966
|
+
}
|
|
967
|
+
function buildChildAdjacency(mapping) {
|
|
968
|
+
const children = /* @__PURE__ */ new Map();
|
|
969
|
+
for (const id of Object.keys(mapping)) {
|
|
970
|
+
const parent = mapping[id]?.parent;
|
|
971
|
+
if (parent != null && mapping[parent]) {
|
|
972
|
+
const list = children.get(parent) ?? [];
|
|
973
|
+
list.push(id);
|
|
974
|
+
children.set(parent, list);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
for (const list of children.values()) list.sort();
|
|
978
|
+
return children;
|
|
979
|
+
}
|
|
980
|
+
function pathToRoot(mapping, leaf, root) {
|
|
981
|
+
const path7 = [];
|
|
982
|
+
const seen = /* @__PURE__ */ new Set();
|
|
983
|
+
let cur = leaf;
|
|
984
|
+
while (cur != null) {
|
|
985
|
+
if (seen.has(cur)) return null;
|
|
986
|
+
seen.add(cur);
|
|
987
|
+
path7.push(cur);
|
|
988
|
+
if (cur === root) return path7.reverse();
|
|
989
|
+
cur = mapping[cur]?.parent ?? null;
|
|
990
|
+
}
|
|
991
|
+
return null;
|
|
992
|
+
}
|
|
993
|
+
function findRoot(mapping) {
|
|
994
|
+
const roots = [];
|
|
995
|
+
for (const id of Object.keys(mapping)) {
|
|
996
|
+
const parent = mapping[id]?.parent;
|
|
997
|
+
if (parent == null || !mapping[parent]) roots.push(id);
|
|
998
|
+
}
|
|
999
|
+
if (roots.length === 0) return null;
|
|
1000
|
+
roots.sort();
|
|
1001
|
+
return roots[0];
|
|
1002
|
+
}
|
|
1003
|
+
function parseConversation(conv) {
|
|
1004
|
+
const mapping = conv.mapping || {};
|
|
1005
|
+
const conversationId = conversationIdOf(conv, mapping);
|
|
1006
|
+
const title = normalizeTitle(conv.title || "Untitled") || "Untitled";
|
|
1007
|
+
const createTime = toMs(conv.create_time, 0);
|
|
1008
|
+
const updateTime = toMs(conv.update_time, createTime);
|
|
1009
|
+
const childAdj = buildChildAdjacency(mapping);
|
|
1010
|
+
const childCount = (id) => childAdj.get(id)?.length ?? 0;
|
|
1011
|
+
const emptyHash = conversationContentHash({
|
|
1012
|
+
conversationId,
|
|
1013
|
+
canonicalPolicy: "empty",
|
|
1014
|
+
canonicalLeaf: null,
|
|
1015
|
+
records: []
|
|
1016
|
+
});
|
|
1017
|
+
const empty = {
|
|
1018
|
+
conversationId,
|
|
1019
|
+
title,
|
|
1020
|
+
createTime,
|
|
1021
|
+
updateTime,
|
|
1022
|
+
canonicalPolicy: "empty",
|
|
1023
|
+
canonicalLeaf: null,
|
|
1024
|
+
contentHash: emptyHash,
|
|
1025
|
+
records: [],
|
|
1026
|
+
skipped: [],
|
|
1027
|
+
noncanonicalMessages: 0,
|
|
1028
|
+
unsupportedParts: 0,
|
|
1029
|
+
branchPoints: 0
|
|
1030
|
+
};
|
|
1031
|
+
const root = findRoot(mapping);
|
|
1032
|
+
if (!root) return empty;
|
|
1033
|
+
let branchPoints = 0;
|
|
1034
|
+
for (const id of Object.keys(mapping)) {
|
|
1035
|
+
if (childCount(id) > 1) branchPoints++;
|
|
1036
|
+
}
|
|
1037
|
+
let canonicalLeaf = null;
|
|
1038
|
+
let policy = "fallback_latest_leaf";
|
|
1039
|
+
const current = conv.current_node;
|
|
1040
|
+
if (current && mapping[current] && pathToRoot(mapping, current, root)) {
|
|
1041
|
+
canonicalLeaf = current;
|
|
1042
|
+
policy = "current_node";
|
|
1043
|
+
} else {
|
|
1044
|
+
const leaves = Object.keys(mapping).filter((id) => childCount(id) === 0);
|
|
1045
|
+
let best = null;
|
|
1046
|
+
for (const leaf of leaves) {
|
|
1047
|
+
const p = pathToRoot(mapping, leaf, root);
|
|
1048
|
+
if (!p) continue;
|
|
1049
|
+
let pathLatest = 0;
|
|
1050
|
+
for (const nid of p) {
|
|
1051
|
+
pathLatest = Math.max(pathLatest, toMs(mapping[nid]?.message?.create_time, 0));
|
|
1052
|
+
}
|
|
1053
|
+
const leafTime = toMs(mapping[leaf]?.message?.create_time, 0);
|
|
1054
|
+
if (!best || pathLatest > best.pathLatest || pathLatest === best.pathLatest && leafTime > best.leafTime || pathLatest === best.pathLatest && leafTime === best.leafTime && leaf > best.leaf) {
|
|
1055
|
+
best = { leaf, pathLatest, leafTime };
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
canonicalLeaf = best?.leaf ?? null;
|
|
1059
|
+
}
|
|
1060
|
+
if (!canonicalLeaf) return empty;
|
|
1061
|
+
const canonicalPath = pathToRoot(mapping, canonicalLeaf, root);
|
|
1062
|
+
if (!canonicalPath) return empty;
|
|
1063
|
+
const canonicalSet = new Set(canonicalPath);
|
|
1064
|
+
const records = [];
|
|
1065
|
+
const skipped = [];
|
|
1066
|
+
let unsupportedParts = 0;
|
|
1067
|
+
for (const nodeId of canonicalPath) {
|
|
1068
|
+
const node = mapping[nodeId];
|
|
1069
|
+
const msg = node?.message;
|
|
1070
|
+
const messageId = msg?.id || nodeId;
|
|
1071
|
+
if (!msg) {
|
|
1072
|
+
skipped.push({ conversationId, messageId, reason: "empty_node" });
|
|
1073
|
+
continue;
|
|
1074
|
+
}
|
|
1075
|
+
if (msg.metadata?.is_visually_hidden_from_conversation === true) {
|
|
1076
|
+
skipped.push({ conversationId, messageId, reason: "hidden" });
|
|
1077
|
+
continue;
|
|
1078
|
+
}
|
|
1079
|
+
if (msg.metadata?.deleted === true) {
|
|
1080
|
+
skipped.push({ conversationId, messageId, reason: "deleted" });
|
|
1081
|
+
continue;
|
|
1082
|
+
}
|
|
1083
|
+
const role = msg.author?.role;
|
|
1084
|
+
if (role === "system") {
|
|
1085
|
+
skipped.push({ conversationId, messageId, reason: "system_role" });
|
|
1086
|
+
continue;
|
|
1087
|
+
}
|
|
1088
|
+
if (role === "tool") {
|
|
1089
|
+
skipped.push({ conversationId, messageId, reason: "tool_role" });
|
|
1090
|
+
continue;
|
|
1091
|
+
}
|
|
1092
|
+
if (role !== "user" && role !== "assistant") {
|
|
1093
|
+
skipped.push({ conversationId, messageId, reason: `unsupported_role:${role ?? "none"}` });
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
const extracted = extractText2(msg.content);
|
|
1097
|
+
unsupportedParts += extracted.unsupportedParts;
|
|
1098
|
+
if (!extracted.text) {
|
|
1099
|
+
skipped.push({ conversationId, messageId, reason: extracted.reason || "empty" });
|
|
1100
|
+
continue;
|
|
1101
|
+
}
|
|
1102
|
+
const text = extracted.text;
|
|
1103
|
+
const timestamp = toMs(msg.create_time, createTime);
|
|
1104
|
+
records.push({
|
|
1105
|
+
externalId: externalId(conversationId, messageId),
|
|
1106
|
+
conversationId,
|
|
1107
|
+
conversationTitle: title,
|
|
1108
|
+
messageId,
|
|
1109
|
+
role,
|
|
1110
|
+
text,
|
|
1111
|
+
timestamp,
|
|
1112
|
+
recordHash: recordHash({ conversationId, messageId, role, text, timestamp }),
|
|
1113
|
+
charCount: text.length
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
let noncanonical = 0;
|
|
1117
|
+
for (const id of Object.keys(mapping)) {
|
|
1118
|
+
if (canonicalSet.has(id)) continue;
|
|
1119
|
+
const msg = mapping[id]?.message;
|
|
1120
|
+
const role = msg?.author?.role;
|
|
1121
|
+
if (role !== "user" && role !== "assistant") continue;
|
|
1122
|
+
if (extractText2(msg?.content).text) noncanonical++;
|
|
1123
|
+
}
|
|
1124
|
+
const contentHash = conversationContentHash({
|
|
1125
|
+
conversationId,
|
|
1126
|
+
canonicalPolicy: policy,
|
|
1127
|
+
canonicalLeaf,
|
|
1128
|
+
records: records.map((r) => ({
|
|
1129
|
+
externalId: r.externalId,
|
|
1130
|
+
recordHash: r.recordHash,
|
|
1131
|
+
role: r.role,
|
|
1132
|
+
timestamp: r.timestamp
|
|
1133
|
+
}))
|
|
1134
|
+
});
|
|
1135
|
+
return {
|
|
1136
|
+
conversationId,
|
|
1137
|
+
title,
|
|
1138
|
+
createTime,
|
|
1139
|
+
updateTime,
|
|
1140
|
+
canonicalPolicy: policy,
|
|
1141
|
+
canonicalLeaf,
|
|
1142
|
+
contentHash,
|
|
1143
|
+
records,
|
|
1144
|
+
skipped,
|
|
1145
|
+
noncanonicalMessages: noncanonical,
|
|
1146
|
+
unsupportedParts,
|
|
1147
|
+
branchPoints
|
|
1148
|
+
};
|
|
1149
|
+
}
|
|
1150
|
+
var ArchiveBuilder = class {
|
|
1151
|
+
// conversationId → all parsed variants seen (usually 1).
|
|
1152
|
+
byId = /* @__PURE__ */ new Map();
|
|
1153
|
+
addRaw(conv) {
|
|
1154
|
+
this.addParsed(parseConversation(conv));
|
|
1155
|
+
}
|
|
1156
|
+
addParsed(parsed) {
|
|
1157
|
+
const list = this.byId.get(parsed.conversationId);
|
|
1158
|
+
if (list) list.push(parsed);
|
|
1159
|
+
else this.byId.set(parsed.conversationId, [parsed]);
|
|
1160
|
+
}
|
|
1161
|
+
finish() {
|
|
1162
|
+
const conversations = [];
|
|
1163
|
+
const duplicateConversationIds = [];
|
|
1164
|
+
const divergentDuplicateConversationIds = [];
|
|
1165
|
+
let duplicateShardMessages = 0;
|
|
1166
|
+
for (const [conversationId, variants] of this.byId) {
|
|
1167
|
+
const distinct = /* @__PURE__ */ new Map();
|
|
1168
|
+
for (const v of variants) {
|
|
1169
|
+
if (!distinct.has(v.contentHash)) distinct.set(v.contentHash, v);
|
|
1170
|
+
}
|
|
1171
|
+
const exactDuplicates = variants.length - distinct.size;
|
|
1172
|
+
if (exactDuplicates > 0) {
|
|
1173
|
+
duplicateConversationIds.push(conversationId);
|
|
1174
|
+
const anyVariant = distinct.values().next().value;
|
|
1175
|
+
duplicateShardMessages += exactDuplicates * (anyVariant?.records.length ?? 0);
|
|
1176
|
+
}
|
|
1177
|
+
if (distinct.size > 1) {
|
|
1178
|
+
divergentDuplicateConversationIds.push(conversationId);
|
|
1179
|
+
}
|
|
1180
|
+
const winnerHash = [...distinct.keys()].sort()[0];
|
|
1181
|
+
conversations.push(distinct.get(winnerHash));
|
|
1182
|
+
}
|
|
1183
|
+
conversations.sort(
|
|
1184
|
+
(a, b) => a.createTime - b.createTime || a.conversationId.localeCompare(b.conversationId)
|
|
1185
|
+
);
|
|
1186
|
+
const records = [];
|
|
1187
|
+
const skipped = [];
|
|
1188
|
+
let userMessages = 0;
|
|
1189
|
+
let assistantMessages = 0;
|
|
1190
|
+
let noncanonicalMessages = 0;
|
|
1191
|
+
let unsupportedParts = 0;
|
|
1192
|
+
let earliest = Number.POSITIVE_INFINITY;
|
|
1193
|
+
let latest = 0;
|
|
1194
|
+
for (const conv of conversations) {
|
|
1195
|
+
noncanonicalMessages += conv.noncanonicalMessages;
|
|
1196
|
+
unsupportedParts += conv.unsupportedParts;
|
|
1197
|
+
for (const s of conv.skipped) skipped.push(s);
|
|
1198
|
+
for (const r of conv.records) {
|
|
1199
|
+
records.push(r);
|
|
1200
|
+
if (r.role === "user") userMessages++;
|
|
1201
|
+
else assistantMessages++;
|
|
1202
|
+
if (r.timestamp > 0) {
|
|
1203
|
+
earliest = Math.min(earliest, r.timestamp);
|
|
1204
|
+
latest = Math.max(latest, r.timestamp);
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
return {
|
|
1209
|
+
archiveContentId: archiveContentId(conversations.map((c) => c.contentHash)),
|
|
1210
|
+
conversations,
|
|
1211
|
+
records,
|
|
1212
|
+
skipped,
|
|
1213
|
+
duplicateConversationIds: duplicateConversationIds.sort(),
|
|
1214
|
+
divergentDuplicateConversationIds: divergentDuplicateConversationIds.sort(),
|
|
1215
|
+
duplicateShardMessages,
|
|
1216
|
+
dateRange: records.length && isFinite(earliest) ? { earliestMs: earliest, latestMs: latest } : null,
|
|
1217
|
+
counts: {
|
|
1218
|
+
conversations: conversations.length,
|
|
1219
|
+
canonicalMessages: records.length,
|
|
1220
|
+
userMessages,
|
|
1221
|
+
assistantMessages,
|
|
1222
|
+
skipped: skipped.length,
|
|
1223
|
+
noncanonicalMessages,
|
|
1224
|
+
unsupportedParts
|
|
1225
|
+
}
|
|
1226
|
+
};
|
|
1227
|
+
}
|
|
1228
|
+
};
|
|
1229
|
+
|
|
1230
|
+
// src/chatgpt/load.ts
|
|
1231
|
+
var MAX_SHARD_BYTES = 512 * 1024 * 1024;
|
|
1232
|
+
function readShard(p) {
|
|
1233
|
+
const stat = fs5.statSync(p);
|
|
1234
|
+
if (stat.size > MAX_SHARD_BYTES) {
|
|
1235
|
+
throw new Error(`Conversation shard too large (${stat.size} bytes): ${p}`);
|
|
1236
|
+
}
|
|
1237
|
+
let parsed;
|
|
1238
|
+
try {
|
|
1239
|
+
parsed = JSON.parse(fs5.readFileSync(p, "utf8"));
|
|
1240
|
+
} catch (err) {
|
|
1241
|
+
throw new Error(`Malformed JSON in ${p}: ${err.message}`);
|
|
1242
|
+
}
|
|
1243
|
+
if (Array.isArray(parsed)) {
|
|
1244
|
+
return parsed;
|
|
1245
|
+
}
|
|
1246
|
+
if (parsed && typeof parsed === "object" && Array.isArray(parsed.conversations)) {
|
|
1247
|
+
return parsed.conversations;
|
|
1248
|
+
}
|
|
1249
|
+
if (parsed && typeof parsed === "object" && parsed.mapping) {
|
|
1250
|
+
return [parsed];
|
|
1251
|
+
}
|
|
1252
|
+
throw new Error(`Unrecognized conversation shard structure in ${p} (expected an array of conversations)`);
|
|
1253
|
+
}
|
|
1254
|
+
function buildArchiveFromShards(paths) {
|
|
1255
|
+
const builder = new ArchiveBuilder();
|
|
1256
|
+
for (const p of paths) {
|
|
1257
|
+
let shard = readShard(p);
|
|
1258
|
+
for (const conv of shard) builder.addRaw(conv);
|
|
1259
|
+
shard = null;
|
|
1260
|
+
}
|
|
1261
|
+
return builder.finish();
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
// src/chatgpt/source.ts
|
|
1265
|
+
function sha256File(filePath) {
|
|
1266
|
+
return new Promise((resolve, reject) => {
|
|
1267
|
+
const hash = crypto.createHash("sha256");
|
|
1268
|
+
const stream = fs6.createReadStream(filePath);
|
|
1269
|
+
stream.on("data", (c) => hash.update(c));
|
|
1270
|
+
stream.on("error", reject);
|
|
1271
|
+
stream.on("end", () => resolve(hash.digest("hex")));
|
|
1272
|
+
});
|
|
1273
|
+
}
|
|
1274
|
+
async function openArchive(archivePath) {
|
|
1275
|
+
const stat = fs6.statSync(archivePath);
|
|
1276
|
+
const isZip = stat.isFile() && archivePath.toLowerCase().endsWith(".zip");
|
|
1277
|
+
let discoverRoot = archivePath;
|
|
1278
|
+
let cleanup = () => {
|
|
1279
|
+
};
|
|
1280
|
+
let archiveSha256 = null;
|
|
1281
|
+
if (isZip) {
|
|
1282
|
+
const tmp = fs6.mkdtempSync(path5.join(os2.tmpdir(), "mr-chatgpt-"));
|
|
1283
|
+
cleanup = () => {
|
|
1284
|
+
try {
|
|
1285
|
+
fs6.rmSync(tmp, { recursive: true, force: true });
|
|
1286
|
+
} catch {
|
|
1287
|
+
}
|
|
1288
|
+
};
|
|
1289
|
+
await safeExtract(archivePath, tmp, (name) => isConversationShard(name) || isMemoryFile(name));
|
|
1290
|
+
archiveSha256 = await sha256File(archivePath);
|
|
1291
|
+
discoverRoot = tmp;
|
|
1292
|
+
}
|
|
1293
|
+
try {
|
|
1294
|
+
const discovery = discoverArchive(discoverRoot);
|
|
1295
|
+
const archive = buildArchiveFromShards(discovery.conversationShards);
|
|
1296
|
+
return {
|
|
1297
|
+
archive,
|
|
1298
|
+
memoryFilesDetected: discovery.memoryFiles.length,
|
|
1299
|
+
ignoredFilesDetected: discovery.ignoredFiles.length,
|
|
1300
|
+
conversationShards: discovery.conversationShards.length,
|
|
1301
|
+
symlinksSkipped: discovery.symlinksSkipped,
|
|
1302
|
+
archiveSha256,
|
|
1303
|
+
cleanup
|
|
1304
|
+
};
|
|
1305
|
+
} catch (err) {
|
|
1306
|
+
cleanup();
|
|
1307
|
+
throw err;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
// src/chatgpt/preview.ts
|
|
1312
|
+
var CHARS_PER_TOKEN = 4;
|
|
1313
|
+
var CHUNK_CHARS = 8e3;
|
|
1314
|
+
var SENSITIVE_PATTERNS = [
|
|
1315
|
+
{ category: "email", re: /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/i },
|
|
1316
|
+
{ category: "phone", re: /(?:\+?\d[\d\s().-]{7,}\d)/ },
|
|
1317
|
+
{ category: "credit_card", re: /\b(?:\d[ -]?){13,16}\b/ },
|
|
1318
|
+
{ category: "ssn", re: /\b\d{3}-\d{2}-\d{4}\b/ },
|
|
1319
|
+
{ category: "api_key", re: /\b(sk-[A-Za-z0-9]{16,}|AKIA[0-9A-Z]{12,}|ghp_[A-Za-z0-9]{20,}|mk_[a-f0-9]{12,})\b/ },
|
|
1320
|
+
{ category: "private_key", re: /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/ },
|
|
1321
|
+
{ category: "password_mention", re: /\b(password|passwd|secret|credential)\b/i }
|
|
1322
|
+
];
|
|
1323
|
+
function applySelection(records, selection) {
|
|
1324
|
+
const exclude = new Set(selection.excludeConversations);
|
|
1325
|
+
return records.filter((r) => {
|
|
1326
|
+
if (exclude.has(r.conversationId)) return false;
|
|
1327
|
+
if (selection.fromMs !== null && r.timestamp > 0 && r.timestamp < selection.fromMs) return false;
|
|
1328
|
+
if (selection.toMs !== null && r.timestamp > 0 && r.timestamp > selection.toMs) return false;
|
|
1329
|
+
return true;
|
|
1330
|
+
});
|
|
1331
|
+
}
|
|
1332
|
+
function detectSensitiveCategories(records) {
|
|
1333
|
+
const found = /* @__PURE__ */ new Set();
|
|
1334
|
+
for (const r of records) {
|
|
1335
|
+
for (const { category, re } of SENSITIVE_PATTERNS) {
|
|
1336
|
+
if (!found.has(category) && re.test(r.text)) found.add(category);
|
|
1337
|
+
}
|
|
1338
|
+
if (found.size === SENSITIVE_PATTERNS.length) break;
|
|
1339
|
+
}
|
|
1340
|
+
return [...found].sort();
|
|
1341
|
+
}
|
|
1342
|
+
function estimateTokens(records) {
|
|
1343
|
+
let total = 0;
|
|
1344
|
+
for (const r of records) total += Math.ceil(r.charCount / CHARS_PER_TOKEN);
|
|
1345
|
+
return total;
|
|
1346
|
+
}
|
|
1347
|
+
function estimateChunks(records) {
|
|
1348
|
+
let total = 0;
|
|
1349
|
+
for (const r of records) total += Math.max(1, Math.ceil(r.charCount / CHUNK_CHARS));
|
|
1350
|
+
return total;
|
|
1351
|
+
}
|
|
1352
|
+
function buildPreview(archive, selected, selection) {
|
|
1353
|
+
let earliest = Number.POSITIVE_INFINITY;
|
|
1354
|
+
let latest = 0;
|
|
1355
|
+
let user = 0;
|
|
1356
|
+
let assistant = 0;
|
|
1357
|
+
const convIds = /* @__PURE__ */ new Set();
|
|
1358
|
+
for (const r of selected) {
|
|
1359
|
+
convIds.add(r.conversationId);
|
|
1360
|
+
if (r.role === "user") user++;
|
|
1361
|
+
else assistant++;
|
|
1362
|
+
if (r.timestamp > 0) {
|
|
1363
|
+
earliest = Math.min(earliest, r.timestamp);
|
|
1364
|
+
latest = Math.max(latest, r.timestamp);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
return {
|
|
1368
|
+
conversations: convIds.size,
|
|
1369
|
+
canonicalMessages: selected.length,
|
|
1370
|
+
userMessages: user,
|
|
1371
|
+
assistantMessages: assistant,
|
|
1372
|
+
skipped: archive.counts.skipped,
|
|
1373
|
+
noncanonicalMessages: archive.counts.noncanonicalMessages,
|
|
1374
|
+
duplicateConversations: archive.duplicateConversationIds.length,
|
|
1375
|
+
dateRange: selected.length && isFinite(earliest) ? { earliestMs: earliest, latestMs: latest } : null,
|
|
1376
|
+
sensitiveCategories: detectSensitiveCategories(selected),
|
|
1377
|
+
estimatedTokens: estimateTokens(selected),
|
|
1378
|
+
expectedRecords: selected.length,
|
|
1379
|
+
expectedChunks: estimateChunks(selected)
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
// src/chatgpt/manifest.ts
|
|
1384
|
+
import fs7 from "fs";
|
|
1385
|
+
import path6 from "path";
|
|
1386
|
+
var MANIFEST_VERSION = 1;
|
|
1387
|
+
function manifestPath(dir) {
|
|
1388
|
+
return path6.join(dir, "manifest.json");
|
|
1389
|
+
}
|
|
1390
|
+
function ledgerPath(dir) {
|
|
1391
|
+
return path6.join(dir, "ledger.jsonl");
|
|
1392
|
+
}
|
|
1393
|
+
function receiptPath(dir) {
|
|
1394
|
+
return path6.join(dir, "receipt.json");
|
|
1395
|
+
}
|
|
1396
|
+
function writeManifest(dir, manifest) {
|
|
1397
|
+
fs7.mkdirSync(dir, { recursive: true });
|
|
1398
|
+
const tmp = manifestPath(dir) + ".tmp";
|
|
1399
|
+
fs7.writeFileSync(tmp, JSON.stringify(manifest, null, 2) + "\n");
|
|
1400
|
+
fs7.renameSync(tmp, manifestPath(dir));
|
|
1401
|
+
}
|
|
1402
|
+
function readManifest(dir) {
|
|
1403
|
+
const raw = fs7.readFileSync(manifestPath(dir), "utf8");
|
|
1404
|
+
return JSON.parse(raw);
|
|
1405
|
+
}
|
|
1406
|
+
function manifestExists(dir) {
|
|
1407
|
+
return fs7.existsSync(manifestPath(dir));
|
|
1408
|
+
}
|
|
1409
|
+
function appendLedger(dir, entry) {
|
|
1410
|
+
fs7.appendFileSync(ledgerPath(dir), JSON.stringify(entry) + "\n");
|
|
1411
|
+
}
|
|
1412
|
+
function readLedger(dir) {
|
|
1413
|
+
if (!fs7.existsSync(ledgerPath(dir))) return [];
|
|
1414
|
+
const raw = fs7.readFileSync(ledgerPath(dir), "utf8");
|
|
1415
|
+
const out = [];
|
|
1416
|
+
for (const line of raw.split("\n")) {
|
|
1417
|
+
const t = line.trim();
|
|
1418
|
+
if (!t) continue;
|
|
1419
|
+
try {
|
|
1420
|
+
out.push(JSON.parse(t));
|
|
1421
|
+
} catch {
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
return out;
|
|
1425
|
+
}
|
|
1426
|
+
function committedBatchIndices(dir) {
|
|
1427
|
+
const set = /* @__PURE__ */ new Set();
|
|
1428
|
+
for (const e of readLedger(dir)) if (e.type === "batch") set.add(e.batchIndex);
|
|
1429
|
+
return set;
|
|
1430
|
+
}
|
|
1431
|
+
function writeReceipt(dir, receipt) {
|
|
1432
|
+
fs7.writeFileSync(receiptPath(dir), JSON.stringify(receipt, null, 2) + "\n");
|
|
1433
|
+
}
|
|
1434
|
+
function receiptFilePath(dir) {
|
|
1435
|
+
return receiptPath(dir);
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// src/chatgpt/client.ts
|
|
1439
|
+
var MAX_RETRIES2 = 5;
|
|
1440
|
+
var INITIAL_BACKOFF_MS2 = 2e3;
|
|
1441
|
+
var MAX_BACKOFF_MS2 = 3e4;
|
|
1442
|
+
function sleep3(ms) {
|
|
1443
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
1444
|
+
}
|
|
1445
|
+
var ImportClient = class {
|
|
1446
|
+
constructor(baseUrl, key) {
|
|
1447
|
+
this.baseUrl = baseUrl;
|
|
1448
|
+
this.key = key;
|
|
1449
|
+
}
|
|
1450
|
+
async request(method, pathname, opts = {}) {
|
|
1451
|
+
const url = `${this.baseUrl}${pathname}`;
|
|
1452
|
+
let backoff = INITIAL_BACKOFF_MS2;
|
|
1453
|
+
let lastErr = null;
|
|
1454
|
+
for (let attempt = 1; attempt <= MAX_RETRIES2; attempt++) {
|
|
1455
|
+
try {
|
|
1456
|
+
const res = await fetch(url, {
|
|
1457
|
+
method,
|
|
1458
|
+
headers: { Authorization: `Bearer ${this.key}`, ...opts.headers ?? {} },
|
|
1459
|
+
body: opts.body
|
|
1460
|
+
});
|
|
1461
|
+
if (res.status === 429 || res.status >= 500) {
|
|
1462
|
+
if (attempt < MAX_RETRIES2) {
|
|
1463
|
+
const retryAfter = res.headers.get("Retry-After");
|
|
1464
|
+
const wait = Math.min(retryAfter ? parseInt(retryAfter, 10) * 1e3 : backoff, MAX_BACKOFF_MS2);
|
|
1465
|
+
await sleep3(wait);
|
|
1466
|
+
backoff = Math.min(backoff * 2, MAX_BACKOFF_MS2);
|
|
1467
|
+
continue;
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
const text = await res.text();
|
|
1471
|
+
let body;
|
|
1472
|
+
try {
|
|
1473
|
+
body = text ? JSON.parse(text) : {};
|
|
1474
|
+
} catch {
|
|
1475
|
+
body = { error: "invalid_json_response", raw: text.slice(0, 500) };
|
|
1476
|
+
}
|
|
1477
|
+
return { status: res.status, ok: res.ok, body };
|
|
1478
|
+
} catch (err) {
|
|
1479
|
+
lastErr = err instanceof Error ? err : new Error(String(err));
|
|
1480
|
+
if (attempt < MAX_RETRIES2) {
|
|
1481
|
+
await sleep3(backoff);
|
|
1482
|
+
backoff = Math.min(backoff * 2, MAX_BACKOFF_MS2);
|
|
1483
|
+
continue;
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
throw lastErr ?? new Error("request failed");
|
|
1488
|
+
}
|
|
1489
|
+
createImport(body) {
|
|
1490
|
+
return this.request("POST", "/v1/memory/imports", { body: JSON.stringify(body), headers: { "Content-Type": "application/json" } });
|
|
1491
|
+
}
|
|
1492
|
+
approve(importId, approvalDigest) {
|
|
1493
|
+
return this.request("POST", `/v1/memory/imports/${encodeURIComponent(importId)}/approve`, {
|
|
1494
|
+
body: JSON.stringify({ approval_digest: approvalDigest }),
|
|
1495
|
+
headers: { "Content-Type": "application/json" }
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
uploadBatch(importId, batchIndex, jsonl, idempotencyKey) {
|
|
1499
|
+
return this.request("POST", `/v1/memory/imports/${encodeURIComponent(importId)}/batches/${batchIndex}`, {
|
|
1500
|
+
body: jsonl,
|
|
1501
|
+
headers: { "Content-Type": "application/x-ndjson", "Idempotency-Key": idempotencyKey }
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
status(importId) {
|
|
1505
|
+
return this.request("GET", `/v1/memory/imports/${encodeURIComponent(importId)}`);
|
|
1506
|
+
}
|
|
1507
|
+
cancel(importId) {
|
|
1508
|
+
return this.request("POST", `/v1/memory/imports/${encodeURIComponent(importId)}/cancel`);
|
|
1509
|
+
}
|
|
1510
|
+
receipt(importId) {
|
|
1511
|
+
return this.request("GET", `/v1/memory/imports/${encodeURIComponent(importId)}/receipt`);
|
|
1512
|
+
}
|
|
1513
|
+
};
|
|
1514
|
+
|
|
1515
|
+
// src/chatgpt/run.ts
|
|
1516
|
+
var BATCH_SIZE = 200;
|
|
1517
|
+
function nowIso() {
|
|
1518
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
1519
|
+
}
|
|
1520
|
+
function fmtDate(ms) {
|
|
1521
|
+
if (ms == null) return "\u2014";
|
|
1522
|
+
return new Date(ms).toISOString().slice(0, 10);
|
|
1523
|
+
}
|
|
1524
|
+
function fmtTokens(n) {
|
|
1525
|
+
if (n >= 1e6) return `${(n / 1e6).toFixed(1)}M`;
|
|
1526
|
+
if (n >= 1e3) return `${(n / 1e3).toFixed(1)}K`;
|
|
1527
|
+
return String(n);
|
|
1528
|
+
}
|
|
1529
|
+
function parseDateOpt(s, label) {
|
|
1530
|
+
if (!s) return null;
|
|
1531
|
+
const ms = Date.parse(s);
|
|
1532
|
+
if (Number.isNaN(ms)) throw new Error(`Invalid --${label} date: ${s} (use YYYY-MM-DD)`);
|
|
1533
|
+
return ms;
|
|
1534
|
+
}
|
|
1535
|
+
function chunk(arr, size) {
|
|
1536
|
+
const out = [];
|
|
1537
|
+
for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size));
|
|
1538
|
+
return out;
|
|
1539
|
+
}
|
|
1540
|
+
function toWireRecord(r) {
|
|
1541
|
+
return JSON.stringify({
|
|
1542
|
+
external_id: r.externalId,
|
|
1543
|
+
record_sha256: r.recordHash,
|
|
1544
|
+
content: r.text,
|
|
1545
|
+
role: r.role,
|
|
1546
|
+
timestamp: r.timestamp,
|
|
1547
|
+
source_platform: SOURCE_PLATFORM,
|
|
1548
|
+
parser_version: PARSER_VERSION,
|
|
1549
|
+
chunk_version: CHUNK_VERSION
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
async function cmdInspect(archivePath) {
|
|
1553
|
+
const src = await openArchive(archivePath);
|
|
1554
|
+
try {
|
|
1555
|
+
const a = src.archive;
|
|
1556
|
+
console.log("ChatGPT export inspection");
|
|
1557
|
+
console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
|
|
1558
|
+
console.log(`Conversation shards: ${src.conversationShards}`);
|
|
1559
|
+
console.log(`Optional memory files: ${src.memoryFilesDetected} (detected, not imported)`);
|
|
1560
|
+
console.log(`Ignored JSON files: ${src.ignoredFilesDetected}`);
|
|
1561
|
+
console.log(`Archive content id: ${a.archiveContentId}`);
|
|
1562
|
+
console.log("");
|
|
1563
|
+
console.log(`Conversations: ${a.counts.conversations}`);
|
|
1564
|
+
console.log(`Canonical messages: ${a.counts.canonicalMessages} (user ${a.counts.userMessages}, assistant ${a.counts.assistantMessages})`);
|
|
1565
|
+
console.log(`Off-branch messages: ${a.counts.noncanonicalMessages} (reported, not imported)`);
|
|
1566
|
+
console.log(`Skipped nodes: ${a.counts.skipped}`);
|
|
1567
|
+
console.log(`Duplicate shards: ${a.duplicateConversationIds.length} conversation(s)`);
|
|
1568
|
+
if (a.dateRange) console.log(`Date range: ${fmtDate(a.dateRange.earliestMs)} \u2192 ${fmtDate(a.dateRange.latestMs)}`);
|
|
1569
|
+
} finally {
|
|
1570
|
+
src.cleanup();
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
async function cmdPrepare(archivePath, opts) {
|
|
1574
|
+
const config = requireConfig();
|
|
1575
|
+
const endpoint = getEndpoint(config);
|
|
1576
|
+
const src = await openArchive(archivePath);
|
|
1577
|
+
try {
|
|
1578
|
+
const selection = {
|
|
1579
|
+
fromMs: parseDateOpt(opts.from, "from"),
|
|
1580
|
+
toMs: parseDateOpt(opts.to, "to"),
|
|
1581
|
+
excludeConversations: (opts.excludeConversation ?? []).slice().sort()
|
|
1582
|
+
};
|
|
1583
|
+
const selected = applySelection(src.archive.records, selection);
|
|
1584
|
+
if (selected.length === 0) {
|
|
1585
|
+
console.error("\u274C Nothing to import after applying selection filters.");
|
|
1586
|
+
process.exit(1);
|
|
1587
|
+
}
|
|
1588
|
+
const preview = buildPreview(src.archive, selected, selection);
|
|
1589
|
+
const fingerprint = vaultFingerprint(config.key);
|
|
1590
|
+
const importId = deriveImportId(src.archive.archiveContentId, fingerprint);
|
|
1591
|
+
const clientPreviewDigest = previewDigest({
|
|
1592
|
+
importId,
|
|
1593
|
+
archiveId: src.archive.archiveContentId,
|
|
1594
|
+
fingerprint,
|
|
1595
|
+
parserVersion: PARSER_VERSION,
|
|
1596
|
+
chunkVersion: CHUNK_VERSION,
|
|
1597
|
+
expectedRecords: preview.expectedRecords,
|
|
1598
|
+
expectedChunks: preview.expectedChunks,
|
|
1599
|
+
estimatedTokens: preview.estimatedTokens,
|
|
1600
|
+
selection,
|
|
1601
|
+
categories: preview.sensitiveCategories
|
|
1602
|
+
});
|
|
1603
|
+
const client = new ImportClient(endpoint, config.key);
|
|
1604
|
+
const res = await client.createImport({
|
|
1605
|
+
import_id: importId,
|
|
1606
|
+
archive_content_id: src.archive.archiveContentId,
|
|
1607
|
+
archive_sha256: src.archiveSha256,
|
|
1608
|
+
parser_version: PARSER_VERSION,
|
|
1609
|
+
chunk_version: CHUNK_VERSION,
|
|
1610
|
+
vault_fingerprint: fingerprint,
|
|
1611
|
+
preview_digest: clientPreviewDigest,
|
|
1612
|
+
expected_records: preview.expectedRecords,
|
|
1613
|
+
expected_chunks: preview.expectedChunks,
|
|
1614
|
+
estimated_tokens: preview.estimatedTokens,
|
|
1615
|
+
selection,
|
|
1616
|
+
categories: preview.sensitiveCategories
|
|
1617
|
+
});
|
|
1618
|
+
if (!res.ok) {
|
|
1619
|
+
console.error(`\u274C Preflight failed (${res.status}): ${describeError(res.body)}`);
|
|
1620
|
+
process.exit(1);
|
|
1621
|
+
}
|
|
1622
|
+
const body = res.body;
|
|
1623
|
+
if (body.preview_digest !== clientPreviewDigest) {
|
|
1624
|
+
console.error("\u274C Preview digest mismatch between client and server. Refusing to proceed (fail closed).");
|
|
1625
|
+
process.exit(1);
|
|
1626
|
+
}
|
|
1627
|
+
const manifest = {
|
|
1628
|
+
version: MANIFEST_VERSION,
|
|
1629
|
+
importId,
|
|
1630
|
+
archiveContentId: src.archive.archiveContentId,
|
|
1631
|
+
archiveSha256: src.archiveSha256,
|
|
1632
|
+
archivePath,
|
|
1633
|
+
vaultFingerprint: fingerprint,
|
|
1634
|
+
endpoint,
|
|
1635
|
+
parserVersion: PARSER_VERSION,
|
|
1636
|
+
chunkVersion: CHUNK_VERSION,
|
|
1637
|
+
sourcePlatform: SOURCE_PLATFORM,
|
|
1638
|
+
selection,
|
|
1639
|
+
preview,
|
|
1640
|
+
previewDigest: clientPreviewDigest,
|
|
1641
|
+
approvalDigest: body.approval_digest,
|
|
1642
|
+
costQuote: {
|
|
1643
|
+
available: body.cost_quote.available,
|
|
1644
|
+
reason: body.cost_quote.reason,
|
|
1645
|
+
estimatedTokens: body.cost_quote.estimated_tokens,
|
|
1646
|
+
ratePerMillionUsd: body.cost_quote.rate_per_million_usd,
|
|
1647
|
+
freeTokensRemaining: body.cost_quote.free_tokens_remaining,
|
|
1648
|
+
paidTokens: body.cost_quote.paid_tokens,
|
|
1649
|
+
estimatedCostCents: body.cost_quote.estimated_cost_cents,
|
|
1650
|
+
costVersion: body.cost_quote.cost_version,
|
|
1651
|
+
currency: body.cost_quote.currency
|
|
1652
|
+
},
|
|
1653
|
+
status: "prepared",
|
|
1654
|
+
createdAt: nowIso(),
|
|
1655
|
+
updatedAt: nowIso()
|
|
1656
|
+
};
|
|
1657
|
+
writeManifest(opts.out, manifest);
|
|
1658
|
+
printPreview(preview, body.cost_quote, fingerprint);
|
|
1659
|
+
console.log("");
|
|
1660
|
+
console.log(`Workspace: ${opts.out}`);
|
|
1661
|
+
console.log(`Import id: ${importId}`);
|
|
1662
|
+
console.log(`Approval digest: ${body.approval_digest}`);
|
|
1663
|
+
console.log("");
|
|
1664
|
+
if (!body.cost_quote.available) {
|
|
1665
|
+
console.log("\u26A0\uFE0F Current cost is unavailable \u2014 the server will refuse to approve (fail closed).");
|
|
1666
|
+
console.log(" Ensure your account billing is provisioned, then re-run prepare.");
|
|
1667
|
+
} else {
|
|
1668
|
+
console.log("Review the preview above. To authorize writes for THIS exact digest, run:");
|
|
1669
|
+
console.log(` memoryrouter chatgpt-import approve ${opts.out}`);
|
|
1670
|
+
}
|
|
1671
|
+
} finally {
|
|
1672
|
+
src.cleanup();
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
function printPreview(preview, quote, fingerprint) {
|
|
1676
|
+
console.log("Import preview");
|
|
1677
|
+
console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
|
|
1678
|
+
console.log(`Destination vault: ${fingerprint} (opaque fingerprint)`);
|
|
1679
|
+
console.log(`Conversations: ${preview.conversations}`);
|
|
1680
|
+
console.log(`Messages to import: ${preview.expectedRecords} (user ${preview.userMessages}, assistant ${preview.assistantMessages})`);
|
|
1681
|
+
console.log(`Expected chunks: ~${preview.expectedChunks}`);
|
|
1682
|
+
console.log(`Skipped nodes: ${preview.skipped}`);
|
|
1683
|
+
console.log(`Off-branch (excl.): ${preview.noncanonicalMessages}`);
|
|
1684
|
+
if (preview.dateRange) console.log(`Date range: ${fmtDate(preview.dateRange.earliestMs)} \u2192 ${fmtDate(preview.dateRange.latestMs)}`);
|
|
1685
|
+
console.log(`Sensitive flags: ${preview.sensitiveCategories.length ? preview.sensitiveCategories.join(", ") : "none detected"}`);
|
|
1686
|
+
console.log("");
|
|
1687
|
+
console.log("Cost estimate (current billing source of truth)");
|
|
1688
|
+
console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
|
|
1689
|
+
if (quote.available) {
|
|
1690
|
+
console.log(`Estimated tokens: ${fmtTokens(quote.estimated_tokens)}`);
|
|
1691
|
+
console.log(`Rate: $${quote.rate_per_million_usd}/1M paid tokens`);
|
|
1692
|
+
console.log(`Free remaining: ${fmtTokens(quote.free_tokens_remaining)}`);
|
|
1693
|
+
console.log(`Paid tokens: ${fmtTokens(quote.paid_tokens)}`);
|
|
1694
|
+
console.log(`Estimated cost: $${(quote.estimated_cost_cents / 100).toFixed(2)} (labeled estimate; receipt reconciles actuals)`);
|
|
1695
|
+
} else {
|
|
1696
|
+
console.log(`Unavailable: ${quote.reason ?? "unknown"} \u2014 cannot compute a safe cost (approval will be refused).`);
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
async function cmdApprove(dir) {
|
|
1700
|
+
requireDir(dir);
|
|
1701
|
+
const manifest = readManifest(dir);
|
|
1702
|
+
const config = requireConfig();
|
|
1703
|
+
const client = new ImportClient(manifest.endpoint || getEndpoint(config), config.key);
|
|
1704
|
+
const res = await client.approve(manifest.importId, manifest.approvalDigest);
|
|
1705
|
+
if (!res.ok) {
|
|
1706
|
+
console.error(`\u274C Approval refused (${res.status}): ${describeError(res.body)}`);
|
|
1707
|
+
process.exit(1);
|
|
1708
|
+
}
|
|
1709
|
+
manifest.status = "approved";
|
|
1710
|
+
manifest.updatedAt = nowIso();
|
|
1711
|
+
writeManifest(dir, manifest);
|
|
1712
|
+
console.log("\u2705 Approved. Writes are now authorized for this exact digest.");
|
|
1713
|
+
console.log(` Run the import with: memoryrouter chatgpt-import run ${dir}`);
|
|
1714
|
+
}
|
|
1715
|
+
async function cmdRun(dir) {
|
|
1716
|
+
requireDir(dir);
|
|
1717
|
+
const manifest = readManifest(dir);
|
|
1718
|
+
if (manifest.status === "cancelled") {
|
|
1719
|
+
console.error("\u274C This import was cancelled. Prepare a new import to continue.");
|
|
1720
|
+
process.exit(1);
|
|
1721
|
+
}
|
|
1722
|
+
if (manifest.status === "prepared") {
|
|
1723
|
+
console.error("\u274C Not approved yet. Run `chatgpt-import approve` first.");
|
|
1724
|
+
process.exit(1);
|
|
1725
|
+
}
|
|
1726
|
+
const config = requireConfig();
|
|
1727
|
+
const client = new ImportClient(manifest.endpoint || getEndpoint(config), config.key);
|
|
1728
|
+
const src = await openArchive(manifest.archivePath);
|
|
1729
|
+
try {
|
|
1730
|
+
if (src.archive.archiveContentId !== manifest.archiveContentId) {
|
|
1731
|
+
console.error("\u274C The archive changed since prepare (content id mismatch). Re-run prepare.");
|
|
1732
|
+
process.exit(1);
|
|
1733
|
+
}
|
|
1734
|
+
const selected = applySelection(src.archive.records, manifest.selection);
|
|
1735
|
+
const batches = chunk(selected, BATCH_SIZE);
|
|
1736
|
+
const alreadyCommitted = committedBatchIndices(dir);
|
|
1737
|
+
manifest.status = "running";
|
|
1738
|
+
manifest.updatedAt = nowIso();
|
|
1739
|
+
writeManifest(dir, manifest);
|
|
1740
|
+
let sentBatches = 0;
|
|
1741
|
+
const totals = { stored: 0, duplicate: 0, skipped: 0, failed: 0, conflict: 0 };
|
|
1742
|
+
console.log(`Uploading ${selected.length} records in ${batches.length} batch(es) of up to ${BATCH_SIZE}\u2026`);
|
|
1743
|
+
for (let i = 0; i < batches.length; i++) {
|
|
1744
|
+
if (alreadyCommitted.has(i)) continue;
|
|
1745
|
+
const jsonl = batches[i].map(toWireRecord).join("\n");
|
|
1746
|
+
const idem = `${manifest.importId}:b${i}`;
|
|
1747
|
+
const res = await client.uploadBatch(manifest.importId, i, jsonl, idem);
|
|
1748
|
+
if (res.status === 402) {
|
|
1749
|
+
console.error("\n\u{1F4B3} Payment required \u2014 out of tokens/credits. Add credits, then re-run to resume.");
|
|
1750
|
+
console.error(` ${describeError(res.body)}`);
|
|
1751
|
+
process.exit(2);
|
|
1752
|
+
}
|
|
1753
|
+
if (res.status === 409) {
|
|
1754
|
+
const reason = res.body.error;
|
|
1755
|
+
if (reason === "import_cancelled") {
|
|
1756
|
+
console.error("\n\u{1F6D1} Import was cancelled server-side. Stopping.");
|
|
1757
|
+
manifest.status = "cancelled";
|
|
1758
|
+
writeManifest(dir, manifest);
|
|
1759
|
+
process.exit(2);
|
|
1760
|
+
}
|
|
1761
|
+
console.error(`
|
|
1762
|
+
\u274C Conflict on batch ${i}: ${describeError(res.body)}`);
|
|
1763
|
+
process.exit(1);
|
|
1764
|
+
}
|
|
1765
|
+
if (!res.ok) {
|
|
1766
|
+
console.error(`
|
|
1767
|
+
\u274C Batch ${i} failed (${res.status}): ${describeError(res.body)}. Re-run to resume.`);
|
|
1768
|
+
process.exit(1);
|
|
1769
|
+
}
|
|
1770
|
+
const body = res.body;
|
|
1771
|
+
for (const ack of body.acks ?? []) {
|
|
1772
|
+
appendLedger(dir, {
|
|
1773
|
+
type: "record",
|
|
1774
|
+
externalId: ack.externalId,
|
|
1775
|
+
status: ack.status,
|
|
1776
|
+
chunksStored: ack.chunksStored,
|
|
1777
|
+
billableTokens: ack.billableTokens,
|
|
1778
|
+
serverRecordId: ack.serverRecordId,
|
|
1779
|
+
batchIndex: i,
|
|
1780
|
+
ts: nowIso()
|
|
1781
|
+
});
|
|
1782
|
+
}
|
|
1783
|
+
const s = body.summary;
|
|
1784
|
+
appendLedger(dir, {
|
|
1785
|
+
type: "batch",
|
|
1786
|
+
batchIndex: i,
|
|
1787
|
+
stored: s.stored,
|
|
1788
|
+
duplicate: s.duplicate,
|
|
1789
|
+
skipped: s.skipped,
|
|
1790
|
+
failed: s.failed,
|
|
1791
|
+
conflict: s.conflict,
|
|
1792
|
+
billableTokens: s.billableTokens,
|
|
1793
|
+
ts: nowIso()
|
|
1794
|
+
});
|
|
1795
|
+
totals.stored += s.stored;
|
|
1796
|
+
totals.duplicate += s.duplicate;
|
|
1797
|
+
totals.skipped += s.skipped;
|
|
1798
|
+
totals.failed += s.failed;
|
|
1799
|
+
totals.conflict += s.conflict;
|
|
1800
|
+
sentBatches++;
|
|
1801
|
+
process.stdout.write(`\r batch ${i + 1}/${batches.length} \u2014 stored ${totals.stored}, dup ${totals.duplicate}, failed ${totals.failed} `);
|
|
1802
|
+
}
|
|
1803
|
+
console.log("");
|
|
1804
|
+
const st = await client.status(manifest.importId);
|
|
1805
|
+
if (st.ok && st.body.complete) {
|
|
1806
|
+
manifest.status = "completed";
|
|
1807
|
+
manifest.updatedAt = nowIso();
|
|
1808
|
+
writeManifest(dir, manifest);
|
|
1809
|
+
}
|
|
1810
|
+
console.log(`
|
|
1811
|
+
\u2705 Done. Sent ${sentBatches} new batch(es). stored=${totals.stored} duplicate=${totals.duplicate} skipped=${totals.skipped} failed=${totals.failed} conflict=${totals.conflict}`);
|
|
1812
|
+
console.log(` Receipt: memoryrouter chatgpt-import receipt ${dir}`);
|
|
1813
|
+
} finally {
|
|
1814
|
+
src.cleanup();
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
async function cmdStatus(dir) {
|
|
1818
|
+
requireDir(dir);
|
|
1819
|
+
const manifest = readManifest(dir);
|
|
1820
|
+
const config = requireConfig();
|
|
1821
|
+
const client = new ImportClient(manifest.endpoint || getEndpoint(config), config.key);
|
|
1822
|
+
const committed = committedBatchIndices(dir);
|
|
1823
|
+
console.log(`Local status: ${manifest.status}`);
|
|
1824
|
+
console.log(`Import id: ${manifest.importId}`);
|
|
1825
|
+
console.log(`Batches sent: ${committed.size}`);
|
|
1826
|
+
const res = await client.status(manifest.importId);
|
|
1827
|
+
if (!res.ok) {
|
|
1828
|
+
console.log(`Server status: unavailable (${res.status}: ${describeError(res.body)})`);
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1831
|
+
const body = res.body;
|
|
1832
|
+
console.log(`Server status: ${body.import.status} (complete=${body.complete})`);
|
|
1833
|
+
console.log(`Server counts: stored=${body.counts.stored} duplicate=${body.counts.duplicate} skipped=${body.counts.skipped} failed=${body.counts.failed} reserved=${body.counts.reserved}`);
|
|
1834
|
+
console.log(`Billable tokens:${body.counts.billableTokens}`);
|
|
1835
|
+
}
|
|
1836
|
+
async function cmdCancel(dir) {
|
|
1837
|
+
requireDir(dir);
|
|
1838
|
+
const manifest = readManifest(dir);
|
|
1839
|
+
const config = requireConfig();
|
|
1840
|
+
const client = new ImportClient(manifest.endpoint || getEndpoint(config), config.key);
|
|
1841
|
+
const res = await client.cancel(manifest.importId);
|
|
1842
|
+
if (!res.ok) {
|
|
1843
|
+
console.error(`\u274C Cancel failed (${res.status}): ${describeError(res.body)}`);
|
|
1844
|
+
process.exit(1);
|
|
1845
|
+
}
|
|
1846
|
+
manifest.status = "cancelled";
|
|
1847
|
+
manifest.updatedAt = nowIso();
|
|
1848
|
+
writeManifest(dir, manifest);
|
|
1849
|
+
console.log("\u{1F6D1} Import cancelled. No further batches will be sent. Already-stored records remain.");
|
|
1850
|
+
}
|
|
1851
|
+
async function cmdReceipt(dir) {
|
|
1852
|
+
requireDir(dir);
|
|
1853
|
+
const manifest = readManifest(dir);
|
|
1854
|
+
const config = requireConfig();
|
|
1855
|
+
const client = new ImportClient(manifest.endpoint || getEndpoint(config), config.key);
|
|
1856
|
+
const res = await client.receipt(manifest.importId);
|
|
1857
|
+
if (!res.ok) {
|
|
1858
|
+
console.error(`\u274C Receipt unavailable (${res.status}): ${describeError(res.body)}`);
|
|
1859
|
+
process.exit(1);
|
|
1860
|
+
}
|
|
1861
|
+
const receipt = res.body.receipt;
|
|
1862
|
+
writeReceipt(dir, receipt);
|
|
1863
|
+
console.log(`Immutable receipt written to ${receiptFilePath(dir)}`);
|
|
1864
|
+
console.log(JSON.stringify(receipt, null, 2));
|
|
1865
|
+
}
|
|
1866
|
+
function requireDir(dir) {
|
|
1867
|
+
if (!manifestExists(dir)) {
|
|
1868
|
+
console.error(`\u274C No import workspace at ${dir}. Run \`chatgpt-import prepare\` first.`);
|
|
1869
|
+
process.exit(1);
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
function describeError(body) {
|
|
1873
|
+
if (body && typeof body === "object") {
|
|
1874
|
+
const b = body;
|
|
1875
|
+
const parts = [b.error, b.message].filter(Boolean);
|
|
1876
|
+
if (parts.length) return parts.join(": ");
|
|
1877
|
+
}
|
|
1878
|
+
return JSON.stringify(body).slice(0, 200);
|
|
1879
|
+
}
|
|
1880
|
+
|
|
383
1881
|
// src/index.ts
|
|
384
1882
|
var program = new Command();
|
|
385
|
-
program.name("memoryrouter").description("
|
|
1883
|
+
program.name("memoryrouter").description("Persistent AI memory and safe ChatGPT history import").version("0.1.2");
|
|
386
1884
|
program.command("auth <key>").description("Authenticate with your MemoryRouter memory key").option("--endpoint <url>", "Custom API endpoint").action(async (key, opts) => {
|
|
387
1885
|
if (!/^mk[_-]/.test(key)) {
|
|
388
1886
|
console.error("\u274C Memory key must start with mk_ or mk-");
|
|
@@ -457,6 +1955,31 @@ program.command("delete").description("Clear all memories from vault").option("-
|
|
|
457
1955
|
process.exit(1);
|
|
458
1956
|
}
|
|
459
1957
|
});
|
|
1958
|
+
var chatgpt = program.command("chatgpt-import").description("Import an official ChatGPT data export (deterministic, previewed, resumable, idempotent)");
|
|
1959
|
+
chatgpt.command("inspect <archive>").description("Safely inspect a ChatGPT export (.zip or extracted folder) \u2014 no network, no writes").action(async (archive) => {
|
|
1960
|
+
await cmdInspect(archive);
|
|
1961
|
+
});
|
|
1962
|
+
chatgpt.command("prepare <archive>").description("Parse + preview + server preflight; write an approval-bound manifest (no writes yet)").requiredOption("-o, --out <dir>", "Import workspace directory").option("--from <YYYY-MM-DD>", "Only include messages on/after this date").option("--to <YYYY-MM-DD>", "Only include messages on/before this date").option("--exclude-conversation <id>", "Exclude a conversation id (repeatable)", collect, []).action(async (archive, opts) => {
|
|
1963
|
+
await cmdPrepare(archive, { out: opts.out, from: opts.from, to: opts.to, excludeConversation: opts.excludeConversation });
|
|
1964
|
+
});
|
|
1965
|
+
chatgpt.command("approve <dir>").description("Explicitly authorize writes for the exact prepared preview digest").action(async (dir) => {
|
|
1966
|
+
await cmdApprove(dir);
|
|
1967
|
+
});
|
|
1968
|
+
chatgpt.command("run <dir>").description("Run the approved import (resumable, idempotent)").action(async (dir) => {
|
|
1969
|
+
await cmdRun(dir);
|
|
1970
|
+
});
|
|
1971
|
+
chatgpt.command("resume <dir>").description("Resume an interrupted import \u2014 sends only not-yet-acknowledged batches").action(async (dir) => {
|
|
1972
|
+
await cmdRun(dir);
|
|
1973
|
+
});
|
|
1974
|
+
chatgpt.command("status <dir>").description("Show local + server-reconciled import status").action(async (dir) => {
|
|
1975
|
+
await cmdStatus(dir);
|
|
1976
|
+
});
|
|
1977
|
+
chatgpt.command("cancel <dir>").description("Cancel the import \u2014 prevents future batches; keeps stored records").action(async (dir) => {
|
|
1978
|
+
await cmdCancel(dir);
|
|
1979
|
+
});
|
|
1980
|
+
chatgpt.command("receipt <dir>").description("Fetch + save the immutable final receipt (reconciles stored/duplicate/skipped/failed + billing)").action(async (dir) => {
|
|
1981
|
+
await cmdReceipt(dir);
|
|
1982
|
+
});
|
|
460
1983
|
program.command("whoami").description("Show current authentication").action(() => {
|
|
461
1984
|
const config = loadConfig();
|
|
462
1985
|
if (!config?.key) {
|
|
@@ -466,6 +1989,9 @@ program.command("whoami").description("Show current authentication").action(() =
|
|
|
466
1989
|
console.log(`Key: ${maskKey(config.key)}`);
|
|
467
1990
|
console.log(`Endpoint: ${getEndpoint(config)}`);
|
|
468
1991
|
});
|
|
1992
|
+
function collect(value, previous) {
|
|
1993
|
+
return previous.concat([value]);
|
|
1994
|
+
}
|
|
469
1995
|
function formatTokens2(tokens) {
|
|
470
1996
|
if (tokens >= 1e6) return `${(tokens / 1e6).toFixed(1)}M`;
|
|
471
1997
|
if (tokens >= 1e3) return `${(tokens / 1e3).toFixed(1)}K`;
|