@codelia/storage 0.1.82 → 0.1.84
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2026 -308
- package/dist/index.d.cts +185 -13
- package/dist/index.d.ts +185 -13
- package/dist/index.js +2042 -303
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,7 +1,221 @@
|
|
|
1
|
+
// src/attachments.ts
|
|
2
|
+
import { createHash as createHash2, randomUUID } from "crypto";
|
|
3
|
+
import { constants as constants2 } from "fs";
|
|
4
|
+
import { lstat, mkdir, open as open2, rename, rm, writeFile } from "fs/promises";
|
|
5
|
+
import path from "path";
|
|
6
|
+
|
|
7
|
+
// src/image-files.ts
|
|
8
|
+
import { createHash } from "crypto";
|
|
9
|
+
import { constants } from "fs";
|
|
10
|
+
import { open } from "fs/promises";
|
|
11
|
+
var imageHash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
12
|
+
async function readImageFileBounded(file, limit) {
|
|
13
|
+
const handle = await open(
|
|
14
|
+
file,
|
|
15
|
+
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
|
|
16
|
+
);
|
|
17
|
+
try {
|
|
18
|
+
const stat = await handle.stat();
|
|
19
|
+
if (!stat.isFile() || stat.size > limit)
|
|
20
|
+
throw new Error("Invalid artifact file");
|
|
21
|
+
const bytes = Buffer.alloc(stat.size + 1);
|
|
22
|
+
let offset = 0;
|
|
23
|
+
while (offset < bytes.length) {
|
|
24
|
+
const read = await handle.read(
|
|
25
|
+
bytes,
|
|
26
|
+
offset,
|
|
27
|
+
bytes.length - offset,
|
|
28
|
+
offset
|
|
29
|
+
);
|
|
30
|
+
if (!read.bytesRead) break;
|
|
31
|
+
offset += read.bytesRead;
|
|
32
|
+
}
|
|
33
|
+
if (offset !== stat.size) throw new Error("Artifact changed during read");
|
|
34
|
+
return bytes.subarray(0, offset);
|
|
35
|
+
} finally {
|
|
36
|
+
await handle.close();
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/attachments.ts
|
|
41
|
+
var ID = /^codelia-attachment-[0-9a-f-]{36}$/;
|
|
42
|
+
var UUID = /^[0-9a-f-]{36}$/;
|
|
43
|
+
var SHA256 = /^[0-9a-f]{64}$/;
|
|
44
|
+
var MAX_BYTES = 32 * 1024 * 1024;
|
|
45
|
+
var BLOCK_BYTES = 64 * 1024;
|
|
46
|
+
var digest = (bytes) => createHash2("sha256").update(bytes).digest("hex");
|
|
47
|
+
var createAttachmentId = () => `codelia-attachment-${randomUUID()}`;
|
|
48
|
+
var isAttachmentId = (id2) => ID.test(id2);
|
|
49
|
+
var FileAttachmentStore = class {
|
|
50
|
+
constructor(root, images) {
|
|
51
|
+
this.root = root;
|
|
52
|
+
this.images = images;
|
|
53
|
+
}
|
|
54
|
+
root;
|
|
55
|
+
images;
|
|
56
|
+
resolveImage = (ref) => this.images.resolve(ref);
|
|
57
|
+
async commit(sessionId, entries2) {
|
|
58
|
+
if (!entries2.length) return;
|
|
59
|
+
const batch = randomUUID();
|
|
60
|
+
const marker = path.join(this.root, "committed", batch);
|
|
61
|
+
await mkdir(path.join(this.root, "committed"), {
|
|
62
|
+
recursive: true,
|
|
63
|
+
mode: 448
|
|
64
|
+
});
|
|
65
|
+
const created = [];
|
|
66
|
+
const createdImages = [];
|
|
67
|
+
try {
|
|
68
|
+
for (const { record: record2, bytes } of entries2) {
|
|
69
|
+
const { ref, imageRef } = record2;
|
|
70
|
+
if (!isAttachmentId(ref.attachment_id) || bytes.length !== ref.byte_size || bytes.length > MAX_BYTES || digest(bytes) !== ref.sha256) {
|
|
71
|
+
throw new Error("Invalid attachment original");
|
|
72
|
+
}
|
|
73
|
+
const dir = path.join(this.root, ref.attachment_id);
|
|
74
|
+
await mkdir(dir, { mode: 448 });
|
|
75
|
+
created.push(dir);
|
|
76
|
+
const metadata = { ...record2, sessionId, batch };
|
|
77
|
+
if (imageRef) {
|
|
78
|
+
await this.images.saveAttachment(bytes, imageRef.media_type, {
|
|
79
|
+
artifactId: imageRef.artifact_id,
|
|
80
|
+
ownerSessionId: sessionId
|
|
81
|
+
});
|
|
82
|
+
createdImages.push(imageRef);
|
|
83
|
+
} else {
|
|
84
|
+
metadata.blocks = [];
|
|
85
|
+
for (let offset = 0; offset < bytes.length; offset += BLOCK_BYTES) {
|
|
86
|
+
metadata.blocks.push(
|
|
87
|
+
digest(bytes.subarray(offset, offset + BLOCK_BYTES))
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
await writeFile(path.join(dir, "original"), bytes, {
|
|
91
|
+
flag: "wx",
|
|
92
|
+
mode: 384
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
await writeFile(
|
|
96
|
+
path.join(dir, "metadata.json"),
|
|
97
|
+
JSON.stringify(metadata),
|
|
98
|
+
{ flag: "wx", mode: 384 }
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
await writeFile(`${marker}.pending`, "", { flag: "wx", mode: 384 });
|
|
102
|
+
await rename(`${marker}.pending`, marker);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
await Promise.allSettled([
|
|
105
|
+
...created.map((dir) => rm(dir, { force: true, recursive: true })),
|
|
106
|
+
...createdImages.map(
|
|
107
|
+
(ref) => this.images.discardUnpublishedAttachment(ref, sessionId)
|
|
108
|
+
),
|
|
109
|
+
rm(`${marker}.pending`, { force: true })
|
|
110
|
+
]);
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async lookup(attachmentId, sessionId) {
|
|
115
|
+
const metadata = await this.metadata(attachmentId, sessionId);
|
|
116
|
+
if (!metadata) return null;
|
|
117
|
+
const { ref, imageRef } = metadata;
|
|
118
|
+
if (imageRef) {
|
|
119
|
+
await this.readImage(metadata);
|
|
120
|
+
} else {
|
|
121
|
+
const bytes = await readImageFileBounded(
|
|
122
|
+
path.join(this.root, attachmentId, "original"),
|
|
123
|
+
ref.byte_size
|
|
124
|
+
);
|
|
125
|
+
if (bytes.length !== ref.byte_size || digest(bytes) !== ref.sha256)
|
|
126
|
+
throw new Error("Attachment original is corrupt");
|
|
127
|
+
}
|
|
128
|
+
return { ref, ...imageRef ? { imageRef } : {} };
|
|
129
|
+
}
|
|
130
|
+
async read(attachmentId, sessionId, offset, length) {
|
|
131
|
+
const metadata = await this.metadata(attachmentId, sessionId);
|
|
132
|
+
if (!metadata) throw new Error("Attachment unavailable in this session");
|
|
133
|
+
if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || length > 256 * 1024)
|
|
134
|
+
throw new Error("Invalid attachment byte range");
|
|
135
|
+
const end = Math.min(offset + length, metadata.ref.byte_size);
|
|
136
|
+
if (metadata.imageRef)
|
|
137
|
+
return (await this.readImage(metadata)).subarray(offset, end);
|
|
138
|
+
const file = await open2(
|
|
139
|
+
path.join(this.root, attachmentId, "original"),
|
|
140
|
+
constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0) | (constants2.O_NONBLOCK ?? 0)
|
|
141
|
+
);
|
|
142
|
+
try {
|
|
143
|
+
const stat = await file.stat();
|
|
144
|
+
if (!stat.isFile() || stat.size !== metadata.ref.byte_size)
|
|
145
|
+
throw new Error("Attachment original is corrupt");
|
|
146
|
+
if (offset >= end) return Buffer.alloc(0);
|
|
147
|
+
const firstBlock = Math.floor(offset / BLOCK_BYTES);
|
|
148
|
+
const lastBlock = Math.ceil(end / BLOCK_BYTES);
|
|
149
|
+
const start = firstBlock * BLOCK_BYTES;
|
|
150
|
+
const bytes = Buffer.alloc(
|
|
151
|
+
Math.min(lastBlock * BLOCK_BYTES, stat.size) - start
|
|
152
|
+
);
|
|
153
|
+
let count = 0;
|
|
154
|
+
while (count < bytes.length) {
|
|
155
|
+
const result = await file.read(
|
|
156
|
+
bytes,
|
|
157
|
+
count,
|
|
158
|
+
bytes.length - count,
|
|
159
|
+
start + count
|
|
160
|
+
);
|
|
161
|
+
if (!result.bytesRead)
|
|
162
|
+
throw new Error("Attachment original is corrupt");
|
|
163
|
+
count += result.bytesRead;
|
|
164
|
+
}
|
|
165
|
+
for (let block = firstBlock; block < lastBlock; block++) {
|
|
166
|
+
const beg = (block - firstBlock) * BLOCK_BYTES;
|
|
167
|
+
if (metadata.blocks?.[block] !== digest(bytes.subarray(beg, beg + BLOCK_BYTES))) {
|
|
168
|
+
throw new Error("Attachment original is corrupt");
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return bytes.subarray(offset - start, end - start);
|
|
172
|
+
} finally {
|
|
173
|
+
await file.close();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async metadata(attachmentId, sessionId) {
|
|
177
|
+
if (!isAttachmentId(attachmentId)) return null;
|
|
178
|
+
const dir = path.join(this.root, attachmentId);
|
|
179
|
+
try {
|
|
180
|
+
if (!(await lstat(dir)).isDirectory()) return null;
|
|
181
|
+
const metadata = JSON.parse(
|
|
182
|
+
(await readImageFileBounded(path.join(dir, "metadata.json"), 64 * 1024)).toString()
|
|
183
|
+
);
|
|
184
|
+
const { ref, imageRef, blocks } = metadata;
|
|
185
|
+
if (metadata.sessionId !== sessionId || !UUID.test(metadata.batch) || ref?.attachment_id !== attachmentId)
|
|
186
|
+
return null;
|
|
187
|
+
if (!Number.isSafeInteger(ref.byte_size) || ref.byte_size < 0 || ref.byte_size > MAX_BYTES || !SHA256.test(ref.sha256) || typeof ref.media_type !== "string" || typeof ref.display_name !== "string")
|
|
188
|
+
throw new Error("Invalid attachment metadata");
|
|
189
|
+
if (!imageRef && (!Array.isArray(blocks) || blocks.length !== Math.ceil(ref.byte_size / BLOCK_BYTES)))
|
|
190
|
+
throw new Error("Invalid attachment block index");
|
|
191
|
+
const marker = path.join(this.root, "committed", metadata.batch);
|
|
192
|
+
return (await lstat(marker)).isFile() ? metadata : null;
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (error.code === "ENOENT") return null;
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
async readImage({
|
|
199
|
+
ref,
|
|
200
|
+
imageRef,
|
|
201
|
+
sessionId
|
|
202
|
+
}) {
|
|
203
|
+
if (!imageRef || imageRef.sha256 !== ref.sha256 || imageRef.byte_size !== ref.byte_size || imageRef.media_type !== ref.media_type || imageRef.width !== ref.width || imageRef.height !== ref.height)
|
|
204
|
+
throw new Error("Invalid image attachment reference");
|
|
205
|
+
const { metadata, bytes } = await this.images.read(
|
|
206
|
+
imageRef.artifact_id,
|
|
207
|
+
sessionId
|
|
208
|
+
);
|
|
209
|
+
if (metadata.kind !== "attachment" || metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size || metadata.media_type !== ref.media_type || metadata.width !== ref.width || metadata.height !== ref.height)
|
|
210
|
+
throw new Error("Image attachment original is corrupt");
|
|
211
|
+
return bytes;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
|
|
1
215
|
// src/image-artifacts.ts
|
|
2
|
-
import { randomUUID as
|
|
3
|
-
import { lstat as
|
|
4
|
-
import
|
|
216
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
217
|
+
import { lstat as lstat3, mkdir as mkdir3, rename as rename3, rm as rm3, writeFile as writeFile3 } from "fs/promises";
|
|
218
|
+
import path3 from "path";
|
|
5
219
|
|
|
6
220
|
// src/image-attachment.ts
|
|
7
221
|
import { imageSize } from "image-size";
|
|
@@ -9,7 +223,9 @@ import { imageSize } from "image-size";
|
|
|
9
223
|
// src/image-png.ts
|
|
10
224
|
import { promisify } from "util";
|
|
11
225
|
import { inflate } from "zlib";
|
|
12
|
-
var IMAGE_MAX_BYTES =
|
|
226
|
+
var IMAGE_MAX_BYTES = 32 * 1024 * 1024;
|
|
227
|
+
var IMAGE_MAX_SIDE = 12288;
|
|
228
|
+
var IMAGE_MAX_PIXELS = 2e7;
|
|
13
229
|
var inflateAsync = promisify(inflate);
|
|
14
230
|
var crcTable = Uint32Array.from({ length: 256 }, (_, n) => {
|
|
15
231
|
let c = n;
|
|
@@ -23,7 +239,7 @@ var crc32 = (data) => {
|
|
|
23
239
|
};
|
|
24
240
|
var invalid = () => {
|
|
25
241
|
throw new Error(
|
|
26
|
-
"Invalid or unsupported image: require a complete non-interlaced 8-bit PNG
|
|
242
|
+
"Invalid or unsupported image: require a complete non-interlaced 8-bit PNG within 32 MiB, 12288 px per side and 20 MP."
|
|
27
243
|
);
|
|
28
244
|
};
|
|
29
245
|
async function validateImagePng(bytes) {
|
|
@@ -52,7 +268,7 @@ async function validateImagePng(bytes) {
|
|
|
52
268
|
height = payload.readUInt32BE(4);
|
|
53
269
|
color = payload[9] ?? -1;
|
|
54
270
|
channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[color] ?? 0;
|
|
55
|
-
if (!width || !height || width >
|
|
271
|
+
if (!width || !height || width > IMAGE_MAX_SIDE || height > IMAGE_MAX_SIDE || width * height > IMAGE_MAX_PIXELS || !channels || payload[8] !== 8 || payload[10] !== 0 || payload[11] !== 0 || payload[12] !== 0)
|
|
56
272
|
invalid();
|
|
57
273
|
} else if (type === "IDAT") {
|
|
58
274
|
if (dataEnded || color === 3 && !palette) invalid();
|
|
@@ -88,61 +304,35 @@ async function validateImagePng(bytes) {
|
|
|
88
304
|
}
|
|
89
305
|
|
|
90
306
|
// src/image-attachment.ts
|
|
307
|
+
var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
308
|
+
function detectImageAttachmentType(bytes) {
|
|
309
|
+
if (bytes.subarray(0, 8).equals(PNG_SIGNATURE)) return "image/png";
|
|
310
|
+
if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255)
|
|
311
|
+
return "image/jpeg";
|
|
312
|
+
if (bytes.toString("latin1", 0, 4) === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP")
|
|
313
|
+
return "image/webp";
|
|
314
|
+
if (["GIF87a", "GIF89a"].includes(bytes.toString("latin1", 0, 6)))
|
|
315
|
+
return "image/gif";
|
|
316
|
+
return void 0;
|
|
317
|
+
}
|
|
91
318
|
function validateImageAttachment(bytes, mediaType) {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
"image/gif": ["GIF87a", "GIF89a"].includes(bytes.toString("ascii", 0, 6))
|
|
97
|
-
};
|
|
98
|
-
if (!bytes.length || bytes.length > IMAGE_MAX_BYTES || !signatures[mediaType])
|
|
99
|
-
throw new Error("Invalid image attachment: MIME mismatch or exceeds 8 MiB");
|
|
319
|
+
if (!bytes.length || bytes.length > IMAGE_MAX_BYTES || detectImageAttachmentType(bytes) !== mediaType)
|
|
320
|
+
throw new Error(
|
|
321
|
+
"Invalid image attachment: MIME mismatch or exceeds 32 MiB"
|
|
322
|
+
);
|
|
100
323
|
try {
|
|
101
324
|
const { width, height } = imageSize(bytes);
|
|
102
|
-
if (!width || !height || width >
|
|
325
|
+
if (!width || !height || width > IMAGE_MAX_SIDE || height > IMAGE_MAX_SIDE || width * height > IMAGE_MAX_PIXELS)
|
|
103
326
|
throw new Error("dimensions");
|
|
104
327
|
return { width, height };
|
|
105
328
|
} catch {
|
|
106
329
|
throw new Error(
|
|
107
|
-
"Invalid image attachment: unreadable header or exceeds
|
|
330
|
+
"Invalid image attachment: unreadable header or exceeds 12288px/20 MP"
|
|
108
331
|
);
|
|
109
332
|
}
|
|
110
333
|
}
|
|
111
334
|
var imageOriginalFilename = (mediaType) => `original.${{ "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif" }[mediaType]}`;
|
|
112
335
|
|
|
113
|
-
// src/image-files.ts
|
|
114
|
-
import { createHash } from "crypto";
|
|
115
|
-
import { constants } from "fs";
|
|
116
|
-
import { open } from "fs/promises";
|
|
117
|
-
var imageHash = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
118
|
-
async function readImageFileBounded(file, limit) {
|
|
119
|
-
const handle = await open(
|
|
120
|
-
file,
|
|
121
|
-
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
|
|
122
|
-
);
|
|
123
|
-
try {
|
|
124
|
-
const stat = await handle.stat();
|
|
125
|
-
if (!stat.isFile() || stat.size > limit)
|
|
126
|
-
throw new Error("Invalid artifact file");
|
|
127
|
-
const bytes = Buffer.alloc(stat.size + 1);
|
|
128
|
-
let offset = 0;
|
|
129
|
-
while (offset < bytes.length) {
|
|
130
|
-
const read = await handle.read(
|
|
131
|
-
bytes,
|
|
132
|
-
offset,
|
|
133
|
-
bytes.length - offset,
|
|
134
|
-
offset
|
|
135
|
-
);
|
|
136
|
-
if (!read.bytesRead) break;
|
|
137
|
-
offset += read.bytesRead;
|
|
138
|
-
}
|
|
139
|
-
if (offset !== stat.size) throw new Error("Artifact changed during read");
|
|
140
|
-
return bytes.subarray(0, offset);
|
|
141
|
-
} finally {
|
|
142
|
-
await handle.close();
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
|
|
146
336
|
// src/image-metadata.ts
|
|
147
337
|
import {
|
|
148
338
|
IMAGE_REFERENCE_MAX_COUNT
|
|
@@ -176,7 +366,7 @@ function parseImageMetadata(value) {
|
|
|
176
366
|
created_at: value.created_at
|
|
177
367
|
};
|
|
178
368
|
}
|
|
179
|
-
if (value.kind !== void 0 && value.kind !== "generated" || value.media_type !== "image/png" || !label(value.provider, 160) || !label(value.requested_model, 160) || !label(value.endpoint, 256) || value.effective_model !== void 0 && !label(value.effective_model, 160) || !Array.isArray(value.parent_artifact_ids) || value.parent_artifact_ids.length > IMAGE_REFERENCE_MAX_COUNT || !value.parent_artifact_ids.every(id))
|
|
369
|
+
if (value.kind !== void 0 && value.kind !== "generated" || value.media_type !== "image/png" && value.media_type !== "image/jpeg" || !label(value.provider, 160) || !label(value.requested_model, 160) || !label(value.endpoint, 256) || value.effective_model !== void 0 && !label(value.effective_model, 160) || !Array.isArray(value.parent_artifact_ids) || value.parent_artifact_ids.length > IMAGE_REFERENCE_MAX_COUNT || !value.parent_artifact_ids.every(id))
|
|
180
370
|
throw new Error("Invalid image artifact metadata");
|
|
181
371
|
let usage;
|
|
182
372
|
if (value.usage !== void 0) {
|
|
@@ -208,24 +398,24 @@ function parseImageMetadata(value) {
|
|
|
208
398
|
}
|
|
209
399
|
|
|
210
400
|
// src/image-model-view.ts
|
|
211
|
-
import { randomUUID } from "crypto";
|
|
212
|
-
import { lstat, mkdir, rename, rm, writeFile } from "fs/promises";
|
|
213
|
-
import
|
|
401
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
402
|
+
import { lstat as lstat2, mkdir as mkdir2, rename as rename2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
|
|
403
|
+
import path2 from "path";
|
|
214
404
|
import {
|
|
215
405
|
isImageModelView
|
|
216
406
|
} from "@codelia/shared-types";
|
|
217
407
|
import { imageSize as imageSize2 } from "image-size";
|
|
218
408
|
var VERSION = "jpeg-q90-444-v1";
|
|
219
|
-
var directory = (root) =>
|
|
409
|
+
var directory = (root) => path2.join(root, VERSION);
|
|
220
410
|
var errorCode = (error) => error && typeof error === "object" && "code" in error ? error.code : void 0;
|
|
221
411
|
async function readModelView(root, original, expected) {
|
|
222
412
|
if (expected !== void 0 && !isImageModelView(expected))
|
|
223
413
|
throw new Error("Invalid image model view");
|
|
224
414
|
const dir = directory(root);
|
|
225
|
-
if (!(await
|
|
415
|
+
if (!(await lstat2(dir)).isDirectory())
|
|
226
416
|
throw new Error("Invalid model view directory");
|
|
227
417
|
const record2 = JSON.parse(
|
|
228
|
-
(await readImageFileBounded(
|
|
418
|
+
(await readImageFileBounded(path2.join(dir, "metadata.json"), 4096)).toString()
|
|
229
419
|
);
|
|
230
420
|
if (!record2 || record2.original_sha256 !== original.sha256 || !isImageModelView(record2.view))
|
|
231
421
|
throw new Error("Invalid model view metadata");
|
|
@@ -233,8 +423,8 @@ async function readModelView(root, original, expected) {
|
|
|
233
423
|
if (expected && (view.sha256 !== expected.sha256 || view.byte_size !== expected.byte_size))
|
|
234
424
|
throw new Error("Image model view reference mismatch");
|
|
235
425
|
const bytes = await readImageFileBounded(
|
|
236
|
-
|
|
237
|
-
|
|
426
|
+
path2.join(dir, "view.jpg"),
|
|
427
|
+
32 * 1024 * 1024
|
|
238
428
|
);
|
|
239
429
|
const dims = imageSize2(bytes);
|
|
240
430
|
if (bytes[0] !== 255 || bytes[1] !== 216 || dims.type !== "jpg" || dims.width !== original.width || dims.height !== original.height || bytes.length !== view.byte_size || imageHash(bytes) !== view.sha256)
|
|
@@ -246,21 +436,21 @@ async function prepareModelView(root, original, bytes) {
|
|
|
246
436
|
return void 0;
|
|
247
437
|
let exists = true;
|
|
248
438
|
try {
|
|
249
|
-
await
|
|
439
|
+
await lstat2(directory(root));
|
|
250
440
|
} catch (error) {
|
|
251
441
|
if (errorCode(error) !== "ENOENT") throw error;
|
|
252
442
|
exists = false;
|
|
253
443
|
}
|
|
254
444
|
if (exists) return (await readModelView(root, original)).view;
|
|
255
445
|
const { default: sharp } = await import("sharp");
|
|
256
|
-
const
|
|
257
|
-
limitInputPixels:
|
|
446
|
+
const pipeline2 = sharp(bytes, {
|
|
447
|
+
limitInputPixels: 2e7,
|
|
258
448
|
failOn: "warning"
|
|
259
449
|
}).timeout({ seconds: 15 });
|
|
260
|
-
const metadata = await
|
|
261
|
-
if ((metadata.pages ?? 1) > 1 || metadata.hasAlpha && !(await
|
|
450
|
+
const metadata = await pipeline2.metadata();
|
|
451
|
+
if ((metadata.pages ?? 1) > 1 || metadata.hasAlpha && !(await pipeline2.clone().stats()).isOpaque)
|
|
262
452
|
return void 0;
|
|
263
|
-
const jpeg = await
|
|
453
|
+
const jpeg = await pipeline2.jpeg({ quality: 90, chromaSubsampling: "4:4:4" }).toBuffer();
|
|
264
454
|
if (jpeg.length >= bytes.length) return void 0;
|
|
265
455
|
const view = {
|
|
266
456
|
version: VERSION,
|
|
@@ -268,46 +458,50 @@ async function prepareModelView(root, original, bytes) {
|
|
|
268
458
|
sha256: imageHash(jpeg),
|
|
269
459
|
byte_size: jpeg.length
|
|
270
460
|
};
|
|
271
|
-
const temporary =
|
|
272
|
-
await
|
|
461
|
+
const temporary = path2.join(root, `.model-view-${randomUUID2()}`);
|
|
462
|
+
await mkdir2(temporary, { mode: 448 });
|
|
273
463
|
try {
|
|
274
|
-
await
|
|
464
|
+
await writeFile2(path2.join(temporary, "view.jpg"), jpeg, {
|
|
275
465
|
flag: "wx",
|
|
276
466
|
mode: 384
|
|
277
467
|
});
|
|
278
|
-
await
|
|
279
|
-
|
|
468
|
+
await writeFile2(
|
|
469
|
+
path2.join(temporary, "metadata.json"),
|
|
280
470
|
JSON.stringify({ original_sha256: original.sha256, view }),
|
|
281
471
|
{ flag: "wx", mode: 384 }
|
|
282
472
|
);
|
|
283
473
|
try {
|
|
284
|
-
await
|
|
474
|
+
await rename2(temporary, directory(root));
|
|
285
475
|
} catch (error) {
|
|
286
476
|
if (!["EEXIST", "ENOTEMPTY"].includes(String(errorCode(error))))
|
|
287
477
|
throw error;
|
|
288
478
|
}
|
|
289
479
|
return (await readModelView(root, original)).view;
|
|
290
480
|
} finally {
|
|
291
|
-
await
|
|
481
|
+
await rm2(temporary, { recursive: true, force: true });
|
|
292
482
|
}
|
|
293
483
|
}
|
|
294
484
|
|
|
295
485
|
// src/image-artifacts.ts
|
|
296
|
-
var
|
|
486
|
+
var ID2 = /^codelia-image-[0-9a-f-]{36}$/;
|
|
297
487
|
var ImageArtifactStore = class {
|
|
298
|
-
constructor(root) {
|
|
488
|
+
constructor(root, getSessionId) {
|
|
299
489
|
this.root = root;
|
|
490
|
+
this.getSessionId = getSessionId;
|
|
300
491
|
}
|
|
301
492
|
root;
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
const
|
|
493
|
+
getSessionId;
|
|
494
|
+
async save(bytes, provenance, mediaType = "image/png") {
|
|
495
|
+
const dimensions = mediaType === "image/png" ? await validateImagePng(bytes) : validateImageAttachment(bytes, "image/jpeg");
|
|
496
|
+
if (mediaType === "image/jpeg" && (bytes.at(-2) !== 255 || bytes.at(-1) !== 217))
|
|
497
|
+
throw new Error("Invalid generated JPEG: missing end marker");
|
|
498
|
+
const artifact_id = `codelia-image-${randomUUID3()}`;
|
|
305
499
|
const metadata = parseImageMetadata({
|
|
306
500
|
...provenance,
|
|
307
501
|
...dimensions,
|
|
308
502
|
artifact_id,
|
|
309
503
|
sha256: imageHash(bytes),
|
|
310
|
-
media_type:
|
|
504
|
+
media_type: mediaType,
|
|
311
505
|
byte_size: bytes.length,
|
|
312
506
|
created_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
313
507
|
});
|
|
@@ -316,60 +510,90 @@ var ImageArtifactStore = class {
|
|
|
316
510
|
await this.persist(bytes, metadata);
|
|
317
511
|
return metadata;
|
|
318
512
|
}
|
|
319
|
-
async saveAttachment(bytes, mediaType
|
|
513
|
+
async saveAttachment(bytes, mediaType, {
|
|
514
|
+
artifactId = `codelia-image-${randomUUID3()}`,
|
|
515
|
+
ownerSessionId
|
|
516
|
+
} = {}) {
|
|
517
|
+
if (!ID2.test(artifactId)) throw new Error("Invalid image artifact id");
|
|
320
518
|
const dimensions = validateImageAttachment(bytes, mediaType);
|
|
321
519
|
const metadata = {
|
|
322
520
|
kind: "attachment",
|
|
323
|
-
artifact_id:
|
|
521
|
+
artifact_id: artifactId,
|
|
324
522
|
sha256: imageHash(bytes),
|
|
325
523
|
media_type: mediaType,
|
|
326
524
|
byte_size: bytes.length,
|
|
327
525
|
...dimensions,
|
|
328
526
|
created_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
329
527
|
};
|
|
330
|
-
|
|
331
|
-
|
|
528
|
+
try {
|
|
529
|
+
await this.persist(bytes, metadata, ownerSessionId);
|
|
530
|
+
return metadata;
|
|
531
|
+
} catch (error) {
|
|
532
|
+
const code = error.code;
|
|
533
|
+
if (code !== "EEXIST" && code !== "ENOTEMPTY") throw error;
|
|
534
|
+
const { metadata: existing } = await this.read(
|
|
535
|
+
artifactId,
|
|
536
|
+
ownerSessionId ?? null
|
|
537
|
+
);
|
|
538
|
+
if (existing.kind !== "attachment" || existing.media_type !== mediaType || existing.sha256 !== metadata.sha256)
|
|
539
|
+
throw error;
|
|
540
|
+
return existing;
|
|
541
|
+
}
|
|
332
542
|
}
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
const
|
|
336
|
-
|
|
543
|
+
/** Roll back a newly uploaded attachment before its ownership batch is published. */
|
|
544
|
+
async discardUnpublishedAttachment(ref, sessionId) {
|
|
545
|
+
const { metadata } = await this.read(ref.artifact_id, sessionId);
|
|
546
|
+
if (metadata.kind !== "attachment" || metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size)
|
|
547
|
+
throw new Error("Image attachment rollback reference mismatch");
|
|
548
|
+
await rm3(path3.join(this.root, ref.artifact_id), { recursive: true });
|
|
549
|
+
}
|
|
550
|
+
async persist(bytes, metadata, ownerSessionId) {
|
|
551
|
+
await mkdir3(this.root, { recursive: true, mode: 448 });
|
|
552
|
+
const temporary = path3.join(this.root, `.pending-${randomUUID3()}`);
|
|
553
|
+
await mkdir3(temporary, { mode: 448 });
|
|
337
554
|
try {
|
|
338
|
-
await
|
|
339
|
-
|
|
555
|
+
await writeFile3(
|
|
556
|
+
path3.join(temporary, imageOriginalFilename(metadata.media_type)),
|
|
340
557
|
bytes,
|
|
341
558
|
{
|
|
342
559
|
flag: "wx",
|
|
343
560
|
mode: 384
|
|
344
561
|
}
|
|
345
562
|
);
|
|
346
|
-
await
|
|
347
|
-
|
|
348
|
-
JSON.stringify(
|
|
563
|
+
await writeFile3(
|
|
564
|
+
path3.join(temporary, "metadata.json"),
|
|
565
|
+
JSON.stringify({
|
|
566
|
+
...metadata,
|
|
567
|
+
...ownerSessionId !== void 0 ? { owner_session_id: ownerSessionId } : {}
|
|
568
|
+
}),
|
|
349
569
|
{ flag: "wx", mode: 384 }
|
|
350
570
|
);
|
|
351
|
-
await
|
|
571
|
+
await rename3(temporary, path3.join(this.root, metadata.artifact_id));
|
|
352
572
|
} catch (error) {
|
|
353
|
-
await
|
|
573
|
+
await rm3(temporary, { recursive: true, force: true });
|
|
354
574
|
throw error;
|
|
355
575
|
}
|
|
356
576
|
}
|
|
357
|
-
async read(artifactId) {
|
|
358
|
-
if (!
|
|
577
|
+
async read(artifactId, sessionId = this.getSessionId?.() ?? null) {
|
|
578
|
+
if (!ID2.test(artifactId)) throw new Error("Invalid image artifact id");
|
|
359
579
|
try {
|
|
360
|
-
const dir =
|
|
361
|
-
if (!(await
|
|
580
|
+
const dir = path3.join(this.root, artifactId);
|
|
581
|
+
if (!(await lstat3(dir)).isDirectory())
|
|
362
582
|
throw new Error("Invalid artifact directory");
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
(await readImageFileBounded(path2.join(dir, "metadata.json"), 16384)).toString()
|
|
366
|
-
)
|
|
583
|
+
const rawMetadata = JSON.parse(
|
|
584
|
+
(await readImageFileBounded(path3.join(dir, "metadata.json"), 16384)).toString()
|
|
367
585
|
);
|
|
586
|
+
const metadata = parseImageMetadata(rawMetadata);
|
|
587
|
+
const owner = rawMetadata.owner_session_id;
|
|
588
|
+
if (owner !== void 0 && (metadata.kind !== "attachment" || typeof owner !== "string" || !owner || owner !== sessionId))
|
|
589
|
+
throw new Error("Image artifact owned by another session");
|
|
368
590
|
const bytes = await readImageFileBounded(
|
|
369
|
-
|
|
591
|
+
path3.join(dir, imageOriginalFilename(metadata.media_type)),
|
|
370
592
|
IMAGE_MAX_BYTES
|
|
371
593
|
);
|
|
372
|
-
const dims = metadata.kind === "attachment" ? validateImageAttachment(bytes, metadata.media_type) : await validateImagePng(bytes);
|
|
594
|
+
const dims = metadata.kind === "attachment" ? validateImageAttachment(bytes, metadata.media_type) : metadata.media_type === "image/png" ? await validateImagePng(bytes) : validateImageAttachment(bytes, "image/jpeg");
|
|
595
|
+
if (metadata.kind !== "attachment" && metadata.media_type === "image/jpeg" && (bytes.at(-2) !== 255 || bytes.at(-1) !== 217))
|
|
596
|
+
throw new Error("Invalid generated JPEG");
|
|
373
597
|
if (metadata.artifact_id !== artifactId || metadata.byte_size !== bytes.length || metadata.sha256 !== imageHash(bytes) || metadata.width !== dims.width || metadata.height !== dims.height)
|
|
374
598
|
throw new Error("Invalid artifact metadata");
|
|
375
599
|
return { metadata, bytes };
|
|
@@ -393,7 +617,7 @@ var ImageArtifactStore = class {
|
|
|
393
617
|
};
|
|
394
618
|
if (original) return ref;
|
|
395
619
|
const model_view = await prepareModelView(
|
|
396
|
-
|
|
620
|
+
path3.join(this.root, artifactId),
|
|
397
621
|
metadata,
|
|
398
622
|
bytes
|
|
399
623
|
);
|
|
@@ -404,7 +628,7 @@ var ImageArtifactStore = class {
|
|
|
404
628
|
if (metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size || metadata.media_type !== ref.media_type || metadata.width !== ref.width || metadata.height !== ref.height)
|
|
405
629
|
throw new Error("Image artifact reference mismatch");
|
|
406
630
|
const input = ref.model_view !== void 0 ? await readModelView(
|
|
407
|
-
|
|
631
|
+
path3.join(this.root, ref.artifact_id),
|
|
408
632
|
metadata,
|
|
409
633
|
ref.model_view
|
|
410
634
|
) : { bytes, view: metadata };
|
|
@@ -422,9 +646,9 @@ var ImageArtifactStore = class {
|
|
|
422
646
|
import { promises as fs } from "fs";
|
|
423
647
|
|
|
424
648
|
// src/paths.ts
|
|
425
|
-
import { mkdir as
|
|
649
|
+
import { mkdir as mkdir4 } from "fs/promises";
|
|
426
650
|
import os from "os";
|
|
427
|
-
import
|
|
651
|
+
import path4 from "path";
|
|
428
652
|
var DEFAULT_ROOT_DIR = ".codelia";
|
|
429
653
|
var LAYOUT_ENV = "CODELIA_LAYOUT";
|
|
430
654
|
var XDG_DIR_NAME = "codelia";
|
|
@@ -449,11 +673,11 @@ function resolveStoragePaths(options = {}) {
|
|
|
449
673
|
}
|
|
450
674
|
async function ensureStorageDirs(paths) {
|
|
451
675
|
await Promise.all([
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
676
|
+
mkdir4(paths.configDir, { recursive: true }),
|
|
677
|
+
mkdir4(paths.cacheDir, { recursive: true }),
|
|
678
|
+
mkdir4(paths.toolOutputCacheDir, { recursive: true }),
|
|
679
|
+
mkdir4(paths.sessionsDir, { recursive: true }),
|
|
680
|
+
mkdir4(paths.logsDir, { recursive: true })
|
|
457
681
|
]);
|
|
458
682
|
}
|
|
459
683
|
function normalizeLayout(value) {
|
|
@@ -461,46 +685,46 @@ function normalizeLayout(value) {
|
|
|
461
685
|
return "home";
|
|
462
686
|
}
|
|
463
687
|
function defaultHomeRoot() {
|
|
464
|
-
return
|
|
688
|
+
return path4.join(os.homedir(), DEFAULT_ROOT_DIR);
|
|
465
689
|
}
|
|
466
690
|
function buildHomeLayout(root) {
|
|
467
691
|
const configDir = root;
|
|
468
692
|
return {
|
|
469
693
|
root,
|
|
470
694
|
configDir,
|
|
471
|
-
configFile:
|
|
472
|
-
authFile:
|
|
473
|
-
mcpAuthFile:
|
|
474
|
-
projectsFile:
|
|
475
|
-
cacheDir:
|
|
476
|
-
toolOutputCacheDir:
|
|
695
|
+
configFile: path4.join(configDir, CONFIG_FILENAME),
|
|
696
|
+
authFile: path4.join(configDir, AUTH_FILENAME),
|
|
697
|
+
mcpAuthFile: path4.join(configDir, MCP_AUTH_FILENAME),
|
|
698
|
+
projectsFile: path4.join(configDir, PROJECTS_FILENAME),
|
|
699
|
+
cacheDir: path4.join(root, CACHE_DIRNAME),
|
|
700
|
+
toolOutputCacheDir: path4.join(
|
|
477
701
|
root,
|
|
478
702
|
CACHE_DIRNAME,
|
|
479
703
|
TOOL_OUTPUT_CACHE_DIRNAME
|
|
480
704
|
),
|
|
481
|
-
sessionsDir:
|
|
482
|
-
logsDir:
|
|
705
|
+
sessionsDir: path4.join(root, SESSIONS_DIRNAME),
|
|
706
|
+
logsDir: path4.join(root, LOGS_DIRNAME)
|
|
483
707
|
};
|
|
484
708
|
}
|
|
485
709
|
function buildXdgLayout() {
|
|
486
710
|
const home = os.homedir();
|
|
487
|
-
const configRoot = process.env.XDG_CONFIG_HOME ??
|
|
488
|
-
const cacheRoot = process.env.XDG_CACHE_HOME ??
|
|
489
|
-
const stateRoot = process.env.XDG_STATE_HOME ??
|
|
490
|
-
const configDir =
|
|
491
|
-
const cacheDir =
|
|
492
|
-
const stateDir =
|
|
711
|
+
const configRoot = process.env.XDG_CONFIG_HOME ?? path4.join(home, ".config");
|
|
712
|
+
const cacheRoot = process.env.XDG_CACHE_HOME ?? path4.join(home, ".cache");
|
|
713
|
+
const stateRoot = process.env.XDG_STATE_HOME ?? path4.join(home, ".local", "state");
|
|
714
|
+
const configDir = path4.join(configRoot, XDG_DIR_NAME);
|
|
715
|
+
const cacheDir = path4.join(cacheRoot, XDG_DIR_NAME);
|
|
716
|
+
const stateDir = path4.join(stateRoot, XDG_DIR_NAME);
|
|
493
717
|
return {
|
|
494
718
|
root: stateDir,
|
|
495
719
|
configDir,
|
|
496
|
-
configFile:
|
|
497
|
-
authFile:
|
|
498
|
-
mcpAuthFile:
|
|
499
|
-
projectsFile:
|
|
720
|
+
configFile: path4.join(configDir, CONFIG_FILENAME),
|
|
721
|
+
authFile: path4.join(configDir, AUTH_FILENAME),
|
|
722
|
+
mcpAuthFile: path4.join(configDir, MCP_AUTH_FILENAME),
|
|
723
|
+
projectsFile: path4.join(configDir, PROJECTS_FILENAME),
|
|
500
724
|
cacheDir,
|
|
501
|
-
toolOutputCacheDir:
|
|
502
|
-
sessionsDir:
|
|
503
|
-
logsDir:
|
|
725
|
+
toolOutputCacheDir: path4.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
|
|
726
|
+
sessionsDir: path4.join(stateDir, SESSIONS_DIRNAME),
|
|
727
|
+
logsDir: path4.join(stateDir, LOGS_DIRNAME)
|
|
504
728
|
};
|
|
505
729
|
}
|
|
506
730
|
|
|
@@ -566,9 +790,41 @@ var McpAuthStore = class {
|
|
|
566
790
|
}
|
|
567
791
|
};
|
|
568
792
|
|
|
569
|
-
// src/
|
|
793
|
+
// src/process-identity.ts
|
|
794
|
+
import { execFile } from "child_process";
|
|
570
795
|
import { promises as fs2 } from "fs";
|
|
571
|
-
|
|
796
|
+
var getProcessIdentity = async (pid, options = {}) => {
|
|
797
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return null;
|
|
798
|
+
if (process.platform === "linux") {
|
|
799
|
+
try {
|
|
800
|
+
const [stat, boot] = await Promise.all([
|
|
801
|
+
fs2.readFile(`/proc/${pid}/stat`, "utf8"),
|
|
802
|
+
fs2.readFile("/proc/sys/kernel/random/boot_id", "utf8")
|
|
803
|
+
]);
|
|
804
|
+
return `${boot.trim()}:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
|
|
805
|
+
} catch {
|
|
806
|
+
return null;
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
if (process.platform === "darwin")
|
|
810
|
+
return new Promise((resolve) => {
|
|
811
|
+
execFile(
|
|
812
|
+
"/bin/ps",
|
|
813
|
+
["-p", String(pid), "-o", "lstart="],
|
|
814
|
+
{
|
|
815
|
+
timeout: 2e3,
|
|
816
|
+
// Preserve existing task recovery identities unless explicitly requested.
|
|
817
|
+
env: options.canonicalEnvironment ? { ...process.env, LC_ALL: "C", TZ: "UTC" } : process.env
|
|
818
|
+
},
|
|
819
|
+
(error, stdout) => resolve(error || !stdout.trim() ? null : `${pid}:${stdout.trim()}`)
|
|
820
|
+
);
|
|
821
|
+
}).catch(() => null);
|
|
822
|
+
return null;
|
|
823
|
+
};
|
|
824
|
+
|
|
825
|
+
// src/projects-store.ts
|
|
826
|
+
import { promises as fs3 } from "fs";
|
|
827
|
+
import path5 from "path";
|
|
572
828
|
import { parseApprovalMode } from "@codelia/shared-types";
|
|
573
829
|
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
574
830
|
var parseApprovalModeField = (fieldPath, value) => {
|
|
@@ -605,13 +861,13 @@ var normalizeProjectsPolicyFile = (value) => {
|
|
|
605
861
|
if (!isRecord2(projectsValue)) {
|
|
606
862
|
throw new Error("projects policy projects must be an object");
|
|
607
863
|
}
|
|
608
|
-
const
|
|
864
|
+
const entries2 = {};
|
|
609
865
|
for (const [key, projectValue] of Object.entries(projectsValue)) {
|
|
610
866
|
if (!isRecord2(projectValue)) {
|
|
611
867
|
throw new Error(`projects policy projects['${key}'] must be an object`);
|
|
612
868
|
}
|
|
613
869
|
if (projectValue.approval_mode !== void 0) {
|
|
614
|
-
|
|
870
|
+
entries2[key] = {
|
|
615
871
|
approval_mode: parseApprovalModeField(
|
|
616
872
|
`projects policy projects['${key}'].approval_mode`,
|
|
617
873
|
projectValue.approval_mode
|
|
@@ -619,23 +875,23 @@ var normalizeProjectsPolicyFile = (value) => {
|
|
|
619
875
|
};
|
|
620
876
|
}
|
|
621
877
|
}
|
|
622
|
-
if (Object.keys(
|
|
623
|
-
normalized.projects =
|
|
878
|
+
if (Object.keys(entries2).length > 0) {
|
|
879
|
+
normalized.projects = entries2;
|
|
624
880
|
}
|
|
625
881
|
}
|
|
626
882
|
return normalized;
|
|
627
883
|
};
|
|
628
884
|
var atomicWriteFile = async (filePath, content) => {
|
|
629
|
-
const dirPath =
|
|
630
|
-
const fileName =
|
|
631
|
-
const tempPath =
|
|
885
|
+
const dirPath = path5.dirname(filePath);
|
|
886
|
+
const fileName = path5.basename(filePath);
|
|
887
|
+
const tempPath = path5.join(
|
|
632
888
|
dirPath,
|
|
633
889
|
`.${fileName}.${process.pid}.${Date.now()}.tmp`
|
|
634
890
|
);
|
|
635
|
-
await
|
|
636
|
-
await
|
|
891
|
+
await fs3.writeFile(tempPath, content, { mode: 384 });
|
|
892
|
+
await fs3.rename(tempPath, filePath);
|
|
637
893
|
if (process.platform !== "win32") {
|
|
638
|
-
await
|
|
894
|
+
await fs3.chmod(filePath, 384);
|
|
639
895
|
}
|
|
640
896
|
};
|
|
641
897
|
var ProjectsPolicyStore = class {
|
|
@@ -648,7 +904,7 @@ var ProjectsPolicyStore = class {
|
|
|
648
904
|
}
|
|
649
905
|
async load() {
|
|
650
906
|
try {
|
|
651
|
-
const raw = await
|
|
907
|
+
const raw = await fs3.readFile(this.paths.projectsFile, "utf8");
|
|
652
908
|
const parsed = JSON.parse(raw);
|
|
653
909
|
return normalizeProjectsPolicyFile(parsed);
|
|
654
910
|
} catch (error) {
|
|
@@ -670,46 +926,359 @@ var ProjectsPolicyStore = class {
|
|
|
670
926
|
};
|
|
671
927
|
|
|
672
928
|
// src/session-store.ts
|
|
673
|
-
import { promises as
|
|
674
|
-
import
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
929
|
+
import { promises as fs6 } from "fs";
|
|
930
|
+
import path8 from "path";
|
|
931
|
+
|
|
932
|
+
// src/run-log-paths.ts
|
|
933
|
+
import { createHash as createHash3 } from "crypto";
|
|
934
|
+
import path6 from "path";
|
|
935
|
+
var runDatePath = (startedAt) => {
|
|
936
|
+
const date = new Date(startedAt);
|
|
937
|
+
if (!Number.isFinite(date.getTime()))
|
|
938
|
+
throw new Error("Invalid run start time");
|
|
939
|
+
return [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join(path6.sep);
|
|
940
|
+
};
|
|
941
|
+
var validateRunLogId = (id2) => {
|
|
942
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(id2))
|
|
943
|
+
throw new Error("Invalid run/session log id");
|
|
944
|
+
return id2;
|
|
945
|
+
};
|
|
946
|
+
var activeRunDirectory = (paths, sessionId) => path6.join(
|
|
947
|
+
paths.sessionsDir,
|
|
948
|
+
"active-runs",
|
|
949
|
+
createHash3("sha256").update(sessionId).digest("hex")
|
|
950
|
+
);
|
|
951
|
+
var usageLogPath = (paths, datePath, runId) => path6.join(paths.root, "usage", datePath, `${validateRunLogId(runId)}.jsonl`);
|
|
952
|
+
|
|
953
|
+
// src/session-run-index.ts
|
|
954
|
+
import { promises as fs5, lstatSync } from "fs";
|
|
955
|
+
import path7 from "path";
|
|
956
|
+
|
|
957
|
+
// src/run-log-reader.ts
|
|
958
|
+
import { constants as constants3, existsSync, promises as fs4 } from "fs";
|
|
959
|
+
import { createInterface } from "readline";
|
|
960
|
+
import { Readable } from "stream";
|
|
961
|
+
import { createGunzip } from "zlib";
|
|
962
|
+
var resolveRunLogPath = (file) => existsSync(file) ? file : file.endsWith(".gz") ? file : `${file}.gz`;
|
|
963
|
+
async function* readRunLogChunks(file) {
|
|
964
|
+
let resolved = resolveRunLogPath(file);
|
|
965
|
+
let handle;
|
|
966
|
+
try {
|
|
967
|
+
handle = await fs4.open(
|
|
968
|
+
resolved,
|
|
969
|
+
constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0)
|
|
970
|
+
);
|
|
971
|
+
} catch (error) {
|
|
972
|
+
if (error.code !== "ENOENT" || file.endsWith(".gz"))
|
|
973
|
+
throw error;
|
|
974
|
+
resolved = `${file}.gz`;
|
|
975
|
+
handle = await fs4.open(
|
|
976
|
+
resolved,
|
|
977
|
+
constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0)
|
|
978
|
+
);
|
|
979
|
+
}
|
|
980
|
+
const source = handle.createReadStream();
|
|
981
|
+
const input = resolved.endsWith(".gz") ? source.pipe(createGunzip()) : source;
|
|
982
|
+
const sourceError = (error) => input.destroy(error);
|
|
983
|
+
if (input !== source) source.on("error", sourceError);
|
|
984
|
+
try {
|
|
985
|
+
for await (const chunk of input)
|
|
986
|
+
yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
987
|
+
} finally {
|
|
988
|
+
input.destroy();
|
|
989
|
+
source.destroy();
|
|
990
|
+
source.off("error", sourceError);
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
async function* readRunLogLines(file) {
|
|
994
|
+
const input = Readable.from(readRunLogChunks(file));
|
|
995
|
+
const lines = createInterface({ input, crlfDelay: Infinity });
|
|
996
|
+
try {
|
|
997
|
+
for await (const line of lines) yield line;
|
|
998
|
+
} finally {
|
|
999
|
+
lines.close();
|
|
1000
|
+
input.destroy();
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
// src/session-run-index.ts
|
|
1005
|
+
var REL_PATH_PATTERN = /^\d{4}\/\d{2}\/\d{2}\/[^/\\]+\.jsonl$/;
|
|
1006
|
+
var normalizeRunStartedAt = (startedAt) => {
|
|
1007
|
+
const time = Date.parse(startedAt);
|
|
1008
|
+
return Number.isFinite(time) ? new Date(time).toISOString() : startedAt;
|
|
1009
|
+
};
|
|
1010
|
+
var isRegularFile = (file) => {
|
|
1011
|
+
try {
|
|
1012
|
+
return lstatSync(file).isFile();
|
|
1013
|
+
} catch {
|
|
1014
|
+
return false;
|
|
1015
|
+
}
|
|
1016
|
+
};
|
|
1017
|
+
var toRunLogRelPath = (sessionsDir, file) => {
|
|
1018
|
+
const relative = path7.relative(sessionsDir, file).split(path7.sep).join("/").replace(/\.gz$/, "");
|
|
1019
|
+
return REL_PATH_PATTERN.test(relative) ? relative : void 0;
|
|
1020
|
+
};
|
|
1021
|
+
var resolveIndexedRunLog = (sessionsDir, relPath) => {
|
|
1022
|
+
if (!REL_PATH_PATTERN.test(relPath)) return void 0;
|
|
1023
|
+
const plain = path7.join(sessionsDir, ...relPath.split("/"));
|
|
1024
|
+
if (isRegularFile(plain)) return plain;
|
|
1025
|
+
if (isRegularFile(`${plain}.gz`)) return `${plain}.gz`;
|
|
1026
|
+
return void 0;
|
|
1027
|
+
};
|
|
1028
|
+
var readHeader = async (file) => {
|
|
1029
|
+
for await (const line of readRunLogLines(file)) {
|
|
1030
|
+
try {
|
|
1031
|
+
const header = JSON.parse(line);
|
|
1032
|
+
if (!header || typeof header !== "object") return null;
|
|
1033
|
+
return header.type === "header" ? header : null;
|
|
1034
|
+
} catch {
|
|
1035
|
+
return null;
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
return null;
|
|
1039
|
+
};
|
|
1040
|
+
var errorCode2 = (error) => error?.code;
|
|
1041
|
+
var readDirs = async (directory2) => {
|
|
1042
|
+
try {
|
|
1043
|
+
return await fs5.readdir(directory2, {
|
|
1044
|
+
withFileTypes: true,
|
|
1045
|
+
encoding: "utf8"
|
|
1046
|
+
});
|
|
1047
|
+
} catch (error) {
|
|
1048
|
+
if (errorCode2(error) === "ENOENT" || errorCode2(error) === "ENOTDIR")
|
|
1049
|
+
return [];
|
|
1050
|
+
throw error;
|
|
1051
|
+
}
|
|
1052
|
+
};
|
|
1053
|
+
var isPermanentFileError = (error) => {
|
|
1054
|
+
const code = errorCode2(error);
|
|
1055
|
+
return code === void 0 || code === "ENOENT" || code === "ELOOP" || code === "EISDIR" || code.startsWith("Z_") || code.startsWith("ERR_");
|
|
1056
|
+
};
|
|
1057
|
+
var listRunLogFiles = async (sessionsDir) => {
|
|
1058
|
+
const files = [];
|
|
1059
|
+
for (const year of await readDirs(sessionsDir)) {
|
|
1060
|
+
if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
|
|
1061
|
+
const yearPath = path7.join(sessionsDir, year.name);
|
|
1062
|
+
for (const month of await readDirs(yearPath)) {
|
|
1063
|
+
if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
|
|
1064
|
+
const monthPath = path7.join(yearPath, month.name);
|
|
1065
|
+
for (const day of await readDirs(monthPath)) {
|
|
1066
|
+
if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
|
|
1067
|
+
const dayPath = path7.join(monthPath, day.name);
|
|
1068
|
+
const entries2 = (await readDirs(dayPath)).filter(
|
|
1069
|
+
(entry) => entry.isFile() && /\.jsonl(?:\.gz)?$/.test(entry.name)
|
|
1070
|
+
);
|
|
1071
|
+
const plain = new Set(
|
|
1072
|
+
entries2.filter((entry) => entry.name.endsWith(".jsonl")).map((entry) => entry.name)
|
|
1073
|
+
);
|
|
1074
|
+
for (const entry of entries2) {
|
|
1075
|
+
if (entry.name.endsWith(".gz") && plain.has(entry.name.slice(0, -3)))
|
|
1076
|
+
continue;
|
|
1077
|
+
files.push(path7.join(dayPath, entry.name));
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
return files;
|
|
1083
|
+
};
|
|
1084
|
+
var SCAN_CONCURRENCY = 16;
|
|
1085
|
+
var scanSessionRunLogs = async (sessionsDir) => {
|
|
1086
|
+
const files = await listRunLogFiles(sessionsDir);
|
|
1087
|
+
const entries2 = [];
|
|
1088
|
+
let next = 0;
|
|
1089
|
+
const worker = async () => {
|
|
1090
|
+
while (next < files.length) {
|
|
1091
|
+
const file = files[next++];
|
|
1092
|
+
const relPath = toRunLogRelPath(sessionsDir, file);
|
|
1093
|
+
if (!relPath) continue;
|
|
1094
|
+
try {
|
|
1095
|
+
const header = await readHeader(file);
|
|
1096
|
+
if (!header || typeof header.session_id !== "string") continue;
|
|
1097
|
+
const startedAt = typeof header.started_at === "string" ? header.started_at : new Date((await fs5.stat(file)).mtimeMs).toISOString();
|
|
1098
|
+
entries2.push({
|
|
1099
|
+
session_id: header.session_id,
|
|
1100
|
+
run_id: typeof header.run_id === "string" ? header.run_id : path7.posix.basename(relPath, ".jsonl"),
|
|
1101
|
+
rel_path: relPath,
|
|
1102
|
+
started_at: normalizeRunStartedAt(startedAt)
|
|
1103
|
+
});
|
|
1104
|
+
} catch (error) {
|
|
1105
|
+
if (isPermanentFileError(error)) continue;
|
|
1106
|
+
next = files.length;
|
|
1107
|
+
throw error;
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
};
|
|
1111
|
+
await Promise.all(
|
|
1112
|
+
Array.from({ length: Math.min(SCAN_CONCURRENCY, files.length) }, worker)
|
|
1113
|
+
);
|
|
1114
|
+
return entries2;
|
|
1115
|
+
};
|
|
1116
|
+
|
|
1117
|
+
// src/usage-log.ts
|
|
1118
|
+
var toUsageRecord = (record2, sessionId, model) => {
|
|
1119
|
+
const usage = record2.output.usage;
|
|
679
1120
|
return {
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
1121
|
+
type: "llm.usage",
|
|
1122
|
+
run_id: record2.run_id,
|
|
1123
|
+
...sessionId ? { session_id: sessionId } : {},
|
|
1124
|
+
ts: record2.ts,
|
|
1125
|
+
seq: record2.seq,
|
|
1126
|
+
model: { provider: model?.provider, name: usage?.model ?? model?.name },
|
|
1127
|
+
output: {
|
|
1128
|
+
usage: usage ? {
|
|
1129
|
+
model: usage.model,
|
|
1130
|
+
provider_model: usage.provider_model,
|
|
1131
|
+
input_tokens: usage.input_tokens,
|
|
1132
|
+
input_cached_tokens: usage.input_cached_tokens,
|
|
1133
|
+
input_cache_creation_tokens: usage.input_cache_creation_tokens,
|
|
1134
|
+
input_image_tokens: usage.input_image_tokens,
|
|
1135
|
+
output_tokens: usage.output_tokens,
|
|
1136
|
+
output_reasoning_tokens: usage.output_reasoning_tokens,
|
|
1137
|
+
total_tokens: usage.total_tokens
|
|
1138
|
+
} : null,
|
|
1139
|
+
timing: record2.output.timing ? {
|
|
1140
|
+
time_to_first_token_ms: record2.output.timing.time_to_first_token_ms,
|
|
1141
|
+
generation_duration_ms: record2.output.timing.generation_duration_ms,
|
|
1142
|
+
generation_start_ms: record2.output.timing.generation_start_ms,
|
|
1143
|
+
generation_start_source: record2.output.timing.generation_start_source
|
|
1144
|
+
} : void 0,
|
|
1145
|
+
stop_reason: record2.output.stop_reason
|
|
1146
|
+
}
|
|
683
1147
|
};
|
|
684
1148
|
};
|
|
1149
|
+
|
|
1150
|
+
// src/session-store.ts
|
|
685
1151
|
var SessionStoreWriterImpl = class {
|
|
686
1152
|
filePath;
|
|
687
|
-
|
|
1153
|
+
usageFilePath;
|
|
1154
|
+
diagnosticFilePath;
|
|
1155
|
+
paths;
|
|
1156
|
+
runId;
|
|
1157
|
+
startedAt;
|
|
1158
|
+
sessionId;
|
|
1159
|
+
model;
|
|
1160
|
+
requestModels = /* @__PURE__ */ new Map();
|
|
1161
|
+
activePath;
|
|
688
1162
|
writeChain = Promise.resolve();
|
|
1163
|
+
runIndex;
|
|
1164
|
+
onRunIndexError;
|
|
689
1165
|
constructor(options) {
|
|
690
1166
|
const paths = options.paths ?? resolveStoragePaths();
|
|
691
|
-
|
|
692
|
-
|
|
1167
|
+
this.paths = paths;
|
|
1168
|
+
this.runIndex = options.runIndex;
|
|
1169
|
+
this.onRunIndexError = options.onRunIndexError;
|
|
1170
|
+
this.runId = validateRunLogId(options.runId);
|
|
1171
|
+
this.startedAt = options.startedAt;
|
|
1172
|
+
const datePath = runDatePath(options.startedAt);
|
|
1173
|
+
this.filePath = path8.join(
|
|
693
1174
|
paths.sessionsDir,
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
parts.day
|
|
1175
|
+
datePath,
|
|
1176
|
+
`${this.runId}.jsonl`
|
|
697
1177
|
);
|
|
698
|
-
this.
|
|
699
|
-
|
|
700
|
-
|
|
1178
|
+
this.usageFilePath = usageLogPath(paths, datePath, this.runId);
|
|
1179
|
+
const dump = options.dump ?? /^(1|true)$/i.test(process.env.CODELIA_SESSION_DUMP ?? "");
|
|
1180
|
+
if (dump)
|
|
1181
|
+
this.diagnosticFilePath = path8.join(
|
|
1182
|
+
paths.sessionsDir,
|
|
1183
|
+
"diagnostics",
|
|
1184
|
+
datePath,
|
|
1185
|
+
`${this.runId}.jsonl`
|
|
1186
|
+
);
|
|
1187
|
+
}
|
|
1188
|
+
projectNormalRecord(record2) {
|
|
1189
|
+
switch (record2.type) {
|
|
1190
|
+
case "header": {
|
|
1191
|
+
this.sessionId = record2.session_id;
|
|
1192
|
+
this.model = record2.model;
|
|
1193
|
+
const { prompts: _prompts, tools: _tools, ...header } = record2;
|
|
1194
|
+
return header;
|
|
1195
|
+
}
|
|
1196
|
+
case "llm.request":
|
|
1197
|
+
this.requestModels.set(record2.seq, {
|
|
1198
|
+
provider: record2.model?.provider ?? this.model?.provider,
|
|
1199
|
+
name: record2.model?.name ?? this.model?.name
|
|
1200
|
+
});
|
|
1201
|
+
return void 0;
|
|
1202
|
+
case "llm.response": {
|
|
1203
|
+
const model = this.requestModels.get(record2.seq) ?? this.model;
|
|
1204
|
+
this.requestModels.delete(record2.seq);
|
|
1205
|
+
return toUsageRecord(record2, this.sessionId, model);
|
|
1206
|
+
}
|
|
1207
|
+
case "tool.output":
|
|
1208
|
+
return void 0;
|
|
1209
|
+
case "run.end":
|
|
1210
|
+
this.requestModels.clear();
|
|
1211
|
+
return record2;
|
|
1212
|
+
default:
|
|
1213
|
+
return record2;
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
/** Indexed before the log line exists so a written log is never unindexed. */
|
|
1217
|
+
async recordRun(sessionId, startedAt) {
|
|
1218
|
+
const relPath = toRunLogRelPath(this.paths.sessionsDir, this.filePath);
|
|
1219
|
+
if (!this.runIndex || !relPath) return;
|
|
1220
|
+
try {
|
|
1221
|
+
await this.runIndex.recordSessionRun({
|
|
1222
|
+
session_id: sessionId,
|
|
1223
|
+
run_id: this.runId,
|
|
1224
|
+
rel_path: relPath,
|
|
1225
|
+
started_at: startedAt
|
|
1226
|
+
});
|
|
1227
|
+
} catch (error) {
|
|
1228
|
+
this.onRunIndexError?.(error);
|
|
1229
|
+
}
|
|
701
1230
|
}
|
|
702
1231
|
append(record2) {
|
|
703
|
-
|
|
1232
|
+
const markerSessionId = record2.type === "header" ? record2.session_id : void 0;
|
|
1233
|
+
const startedAt = record2.type === "header" ? record2.started_at : void 0;
|
|
1234
|
+
const terminal = record2.type === "run.end";
|
|
1235
|
+
let normal;
|
|
1236
|
+
let dump;
|
|
1237
|
+
let usage;
|
|
704
1238
|
try {
|
|
705
|
-
|
|
1239
|
+
if (this.diagnosticFilePath) dump = `${JSON.stringify(record2)}
|
|
706
1240
|
`;
|
|
1241
|
+
const projected = this.projectNormalRecord(record2);
|
|
1242
|
+
if (projected) {
|
|
1243
|
+
normal = `${JSON.stringify(projected)}
|
|
1244
|
+
`;
|
|
1245
|
+
if (record2.type === "llm.response") usage = normal;
|
|
1246
|
+
}
|
|
707
1247
|
} catch (error) {
|
|
708
1248
|
return Promise.reject(error);
|
|
709
1249
|
}
|
|
1250
|
+
if (normal === void 0 && dump === void 0 && usage === void 0)
|
|
1251
|
+
return this.writeChain;
|
|
710
1252
|
const write = this.writeChain.then(async () => {
|
|
711
|
-
|
|
712
|
-
|
|
1253
|
+
if (markerSessionId) {
|
|
1254
|
+
await this.recordRun(markerSessionId, startedAt ?? this.startedAt);
|
|
1255
|
+
const directory2 = activeRunDirectory(this.paths, markerSessionId);
|
|
1256
|
+
await fs6.mkdir(directory2, { recursive: true });
|
|
1257
|
+
this.activePath = path8.join(directory2, `${this.runId}.json`);
|
|
1258
|
+
await fs6.writeFile(
|
|
1259
|
+
this.activePath,
|
|
1260
|
+
JSON.stringify({
|
|
1261
|
+
pid: process.pid,
|
|
1262
|
+
identity: await getProcessIdentity(process.pid, {
|
|
1263
|
+
canonicalEnvironment: true
|
|
1264
|
+
})
|
|
1265
|
+
}),
|
|
1266
|
+
{ flag: "wx", mode: 384 }
|
|
1267
|
+
);
|
|
1268
|
+
}
|
|
1269
|
+
for (const [file, line] of [
|
|
1270
|
+
[this.usageFilePath, usage],
|
|
1271
|
+
[this.filePath, normal],
|
|
1272
|
+
[this.diagnosticFilePath, dump]
|
|
1273
|
+
]) {
|
|
1274
|
+
if (!file || line === void 0) continue;
|
|
1275
|
+
await fs6.mkdir(path8.dirname(file), { recursive: true });
|
|
1276
|
+
await fs6.appendFile(file, line, { encoding: "utf8", mode: 384 });
|
|
1277
|
+
}
|
|
1278
|
+
if (terminal && this.activePath) {
|
|
1279
|
+
await fs6.unlink(this.activePath);
|
|
1280
|
+
this.activePath = void 0;
|
|
1281
|
+
}
|
|
713
1282
|
});
|
|
714
1283
|
this.writeChain = write.catch(() => {
|
|
715
1284
|
});
|
|
@@ -717,40 +1286,198 @@ var SessionStoreWriterImpl = class {
|
|
|
717
1286
|
}
|
|
718
1287
|
};
|
|
719
1288
|
|
|
720
|
-
// src/
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
1289
|
+
// src/session-state.ts
|
|
1290
|
+
import {
|
|
1291
|
+
closeSync as closeSync2,
|
|
1292
|
+
existsSync as existsSync2,
|
|
1293
|
+
promises as fs7,
|
|
1294
|
+
fsyncSync as fsyncSync2,
|
|
1295
|
+
lstatSync as lstatSync2,
|
|
1296
|
+
openSync as openSync2,
|
|
1297
|
+
readFileSync,
|
|
1298
|
+
renameSync,
|
|
1299
|
+
unlinkSync,
|
|
1300
|
+
writeFileSync
|
|
1301
|
+
} from "fs";
|
|
1302
|
+
import path9 from "path";
|
|
1303
|
+
import { stringifyContent as stringifyContent2 } from "@codelia/core";
|
|
729
1304
|
|
|
730
|
-
// src/
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
1305
|
+
// src/conversation-archive.ts
|
|
1306
|
+
import {
|
|
1307
|
+
closeSync,
|
|
1308
|
+
constants as constants4,
|
|
1309
|
+
createReadStream,
|
|
1310
|
+
fstatSync,
|
|
1311
|
+
fsyncSync,
|
|
1312
|
+
openSync,
|
|
1313
|
+
readSync,
|
|
1314
|
+
writeSync
|
|
1315
|
+
} from "fs";
|
|
1316
|
+
import { stringifyContent } from "@codelia/core";
|
|
1317
|
+
function appendOriginalMessages(file, messages) {
|
|
1318
|
+
const data = Buffer.from(
|
|
1319
|
+
messages.map((message) => JSON.stringify(message)).join("\n") + (messages.length ? "\n" : "")
|
|
1320
|
+
);
|
|
1321
|
+
const fd = openSync(
|
|
1322
|
+
file,
|
|
1323
|
+
constants4.O_RDWR | constants4.O_CREAT | constants4.O_APPEND | (constants4.O_NOFOLLOW ?? 0),
|
|
1324
|
+
384
|
|
1325
|
+
);
|
|
1326
|
+
try {
|
|
1327
|
+
const stat = fstatSync(fd);
|
|
1328
|
+
if (!stat.isFile()) throw new Error("Invalid conversation archive");
|
|
1329
|
+
if (stat.size) {
|
|
1330
|
+
const last = Buffer.alloc(1);
|
|
1331
|
+
readSync(fd, last, 0, 1, stat.size - 1);
|
|
1332
|
+
if (last[0] !== 10)
|
|
1333
|
+
throw new Error(
|
|
1334
|
+
"Incomplete conversation archive; original bytes retained"
|
|
1335
|
+
);
|
|
1336
|
+
}
|
|
1337
|
+
let written = 0;
|
|
1338
|
+
while (written < data.length)
|
|
1339
|
+
written += writeSync(fd, data, written, data.length - written);
|
|
1340
|
+
fsyncSync(fd);
|
|
1341
|
+
} finally {
|
|
1342
|
+
closeSync(fd);
|
|
734
1343
|
}
|
|
1344
|
+
}
|
|
1345
|
+
var parseId = (id2) => {
|
|
1346
|
+
if (!/^m(?:0|[1-9][0-9]*)$/.test(id2))
|
|
1347
|
+
throw new Error("Invalid conversation message ID");
|
|
1348
|
+
const offset = Number(id2.slice(1));
|
|
1349
|
+
if (!Number.isSafeInteger(offset))
|
|
1350
|
+
throw new Error("Invalid conversation message ID");
|
|
1351
|
+
return offset;
|
|
735
1352
|
};
|
|
1353
|
+
var textOf = (message) => {
|
|
1354
|
+
const text = [
|
|
1355
|
+
message.role === "tool" && message.display_content ? message.display_content : stringifyContent(message.content, { mode: "display" }),
|
|
1356
|
+
message.role === "assistant" ? message.refusal : void 0
|
|
1357
|
+
].filter(Boolean).join("\n");
|
|
1358
|
+
return message.role === "assistant" && message.tool_calls?.length ? `${text}
|
|
1359
|
+
${JSON.stringify(message.tool_calls.map((call) => ({ id: call.id, function: call.function })))}` : text;
|
|
1360
|
+
};
|
|
1361
|
+
async function* entries(file, start) {
|
|
1362
|
+
const fd = openSync(file, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
|
|
1363
|
+
let stream;
|
|
1364
|
+
try {
|
|
1365
|
+
const stat = fstatSync(fd);
|
|
1366
|
+
if (!stat.isFile()) throw new Error("Invalid conversation archive");
|
|
1367
|
+
if (start > stat.size)
|
|
1368
|
+
throw new Error("Conversation cursor is beyond the archive");
|
|
1369
|
+
if (start === stat.size) return;
|
|
1370
|
+
if (start > 0) {
|
|
1371
|
+
const previous = Buffer.alloc(1);
|
|
1372
|
+
readSync(fd, previous, 0, 1, start - 1);
|
|
1373
|
+
if (previous[0] !== 10)
|
|
1374
|
+
throw new Error("Conversation cursor is not a message boundary");
|
|
1375
|
+
}
|
|
1376
|
+
stream = createReadStream(file, {
|
|
1377
|
+
fd,
|
|
1378
|
+
autoClose: true,
|
|
1379
|
+
start,
|
|
1380
|
+
end: Math.max(0, stat.size - 1)
|
|
1381
|
+
});
|
|
1382
|
+
let offset = start;
|
|
1383
|
+
let parts = [];
|
|
1384
|
+
let length = 0;
|
|
1385
|
+
for await (const raw of stream) {
|
|
1386
|
+
const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
|
|
1387
|
+
let position = 0;
|
|
1388
|
+
while (position < chunk.length) {
|
|
1389
|
+
const newline = chunk.indexOf(10, position);
|
|
1390
|
+
const end = newline < 0 ? chunk.length : newline + 1;
|
|
1391
|
+
const fragment = chunk.subarray(position, end);
|
|
1392
|
+
parts.push(fragment);
|
|
1393
|
+
length += fragment.length;
|
|
1394
|
+
if (newline >= 0) {
|
|
1395
|
+
const message = JSON.parse(
|
|
1396
|
+
Buffer.concat(parts, length).toString("utf8")
|
|
1397
|
+
);
|
|
1398
|
+
if (!message || typeof message.role !== "string")
|
|
1399
|
+
throw new Error("Invalid original conversation message");
|
|
1400
|
+
yield { id: `m${offset}`, next: `m${offset + length}`, message };
|
|
1401
|
+
offset += length;
|
|
1402
|
+
parts = [];
|
|
1403
|
+
length = 0;
|
|
1404
|
+
}
|
|
1405
|
+
position = end;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
} finally {
|
|
1409
|
+
if (!stream) closeSync(fd);
|
|
1410
|
+
else if (!stream.closed) {
|
|
1411
|
+
const closed = new Promise(
|
|
1412
|
+
(resolve) => stream?.once("close", resolve)
|
|
1413
|
+
);
|
|
1414
|
+
stream.destroy();
|
|
1415
|
+
await closed;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
async function searchOriginalMessages(file, options) {
|
|
1420
|
+
const query = options.query.trim().toLowerCase();
|
|
1421
|
+
if (!query || query.length > 200)
|
|
1422
|
+
throw new Error("Expected a query of 1\u2013200 characters");
|
|
1423
|
+
const limit = Math.max(1, Math.min(20, Math.trunc(options.limit ?? 10)));
|
|
1424
|
+
const matches = [];
|
|
1425
|
+
let scanned = 0;
|
|
1426
|
+
for await (const entry of entries(
|
|
1427
|
+
file,
|
|
1428
|
+
options.cursor ? parseId(options.cursor) : 0
|
|
1429
|
+
)) {
|
|
1430
|
+
const text = textOf(entry.message);
|
|
1431
|
+
const index = text.toLowerCase().indexOf(query);
|
|
1432
|
+
if (index >= 0) {
|
|
1433
|
+
const start = Math.max(0, index - 80);
|
|
1434
|
+
matches.push({
|
|
1435
|
+
id: entry.id,
|
|
1436
|
+
role: entry.message.role,
|
|
1437
|
+
text: text.slice(start, start + 240),
|
|
1438
|
+
truncated: start > 0 || text.length > start + 240
|
|
1439
|
+
});
|
|
1440
|
+
}
|
|
1441
|
+
if (++scanned >= 1e3 || matches.length >= limit)
|
|
1442
|
+
return { matches, next_cursor: entry.next };
|
|
1443
|
+
}
|
|
1444
|
+
return { matches };
|
|
1445
|
+
}
|
|
1446
|
+
async function readOriginalMessage(file, options) {
|
|
1447
|
+
for await (const entry of entries(file, parseId(options.id))) {
|
|
1448
|
+
const text = textOf(entry.message);
|
|
1449
|
+
const offset = Math.max(0, Math.trunc(options.offset ?? 0));
|
|
1450
|
+
const limit = Math.max(
|
|
1451
|
+
1,
|
|
1452
|
+
Math.min(8e3, Math.trunc(options.limit ?? 4e3))
|
|
1453
|
+
);
|
|
1454
|
+
const next = offset + limit;
|
|
1455
|
+
return {
|
|
1456
|
+
id: entry.id,
|
|
1457
|
+
role: entry.message.role,
|
|
1458
|
+
text: text.slice(offset, next),
|
|
1459
|
+
truncated: next < text.length,
|
|
1460
|
+
...next < text.length ? { next_offset: next } : {}
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
return null;
|
|
1464
|
+
}
|
|
736
1465
|
|
|
737
|
-
// src/session-state.ts
|
|
738
|
-
import { promises as fs4 } from "fs";
|
|
739
|
-
import path6 from "path";
|
|
740
|
-
import { stringifyContent } from "@codelia/core";
|
|
1466
|
+
// src/session-state.ts
|
|
741
1467
|
var LEGACY_STATE_DIRNAME = "state";
|
|
742
1468
|
var MESSAGES_DIRNAME = "messages";
|
|
743
1469
|
var STATE_DB_FILENAME = "state.db";
|
|
744
1470
|
var SESSION_WORKSPACE_ROOT_META_KEY = "codelia_workspace_root";
|
|
745
|
-
var
|
|
746
|
-
var
|
|
747
|
-
var
|
|
1471
|
+
var RUN_INDEX_BACKFILL_KEY = "session_runs_backfilled_at";
|
|
1472
|
+
var resolveLegacyStateDir = (paths) => path9.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
|
|
1473
|
+
var resolveMessagesDir = (paths) => path9.join(paths.sessionsDir, MESSAGES_DIRNAME);
|
|
1474
|
+
var resolveStateDbPath = (paths) => path9.join(paths.sessionsDir, STATE_DB_FILENAME);
|
|
748
1475
|
var extractLastUserMessage = (messages) => {
|
|
749
1476
|
for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
|
|
750
1477
|
const message = messages[idx];
|
|
751
1478
|
if (!message || typeof message !== "object") continue;
|
|
752
1479
|
if ("role" in message && message.role === "user" && "content" in message) {
|
|
753
|
-
return
|
|
1480
|
+
return stringifyContent2(message.content, {
|
|
754
1481
|
mode: "display"
|
|
755
1482
|
});
|
|
756
1483
|
}
|
|
@@ -777,13 +1504,10 @@ var fromSummaryRow = (row) => ({
|
|
|
777
1504
|
run_id: row.run_id ?? void 0,
|
|
778
1505
|
message_count: row.message_count ?? void 0,
|
|
779
1506
|
last_user_message: row.last_user_message ?? void 0,
|
|
780
|
-
workspace_root: row.workspace_root ?? void 0
|
|
1507
|
+
workspace_root: row.workspace_root ?? void 0,
|
|
1508
|
+
...row.pinned === 1 ? { pinned: true } : {},
|
|
1509
|
+
...row.archived_at ? { archived_at: row.archived_at } : {}
|
|
781
1510
|
});
|
|
782
|
-
var serializeMessages = (messages) => {
|
|
783
|
-
if (messages.length === 0) return "";
|
|
784
|
-
return `${messages.map((message) => JSON.stringify(message)).join("\n")}
|
|
785
|
-
`;
|
|
786
|
-
};
|
|
787
1511
|
var deserializeMessages = (payload) => {
|
|
788
1512
|
if (!payload.trim()) return [];
|
|
789
1513
|
const messages = [];
|
|
@@ -799,44 +1523,31 @@ var deserializeMessages = (payload) => {
|
|
|
799
1523
|
}
|
|
800
1524
|
return messages;
|
|
801
1525
|
};
|
|
802
|
-
var atomicWriteFile2 = async (filePath, payload) => {
|
|
803
|
-
const dirname = path6.dirname(filePath);
|
|
804
|
-
const basename = path6.basename(filePath);
|
|
805
|
-
const tempFile = path6.join(
|
|
806
|
-
dirname,
|
|
807
|
-
`${basename}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
|
|
808
|
-
);
|
|
809
|
-
let wroteTemp = false;
|
|
810
|
-
try {
|
|
811
|
-
await fs4.writeFile(tempFile, payload, "utf8");
|
|
812
|
-
wroteTemp = true;
|
|
813
|
-
await fs4.rename(tempFile, filePath);
|
|
814
|
-
} catch (error) {
|
|
815
|
-
if (wroteTemp) {
|
|
816
|
-
await fs4.rm(tempFile, { force: true }).catch(() => {
|
|
817
|
-
});
|
|
818
|
-
}
|
|
819
|
-
throw error;
|
|
820
|
-
}
|
|
821
|
-
};
|
|
822
1526
|
var SessionStateStoreImpl = class {
|
|
1527
|
+
/** Root that `session_runs.rel_path` values are relative to. */
|
|
1528
|
+
sessionsDir;
|
|
823
1529
|
legacyStateDir;
|
|
824
1530
|
messagesDir;
|
|
1531
|
+
contextsDir;
|
|
825
1532
|
stateDbPath;
|
|
826
1533
|
ensureDirs;
|
|
827
1534
|
db;
|
|
828
1535
|
schemaInit;
|
|
829
1536
|
onError;
|
|
830
1537
|
lastDbUnavailableError;
|
|
1538
|
+
runIndexBackfill = null;
|
|
831
1539
|
constructor(options = {}) {
|
|
832
1540
|
const paths = options.paths ?? resolveStoragePaths();
|
|
1541
|
+
this.sessionsDir = paths.sessionsDir;
|
|
833
1542
|
this.legacyStateDir = resolveLegacyStateDir(paths);
|
|
834
1543
|
this.messagesDir = resolveMessagesDir(paths);
|
|
1544
|
+
this.contextsDir = path9.join(paths.sessionsDir, "contexts");
|
|
835
1545
|
this.stateDbPath = resolveStateDbPath(paths);
|
|
836
1546
|
this.ensureDirs = Promise.all([
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
1547
|
+
fs7.mkdir(paths.sessionsDir, { recursive: true }),
|
|
1548
|
+
fs7.mkdir(this.legacyStateDir, { recursive: true }),
|
|
1549
|
+
fs7.mkdir(this.messagesDir, { recursive: true }),
|
|
1550
|
+
fs7.mkdir(this.contextsDir, { recursive: true })
|
|
840
1551
|
]).then(() => {
|
|
841
1552
|
});
|
|
842
1553
|
this.onError = options.onError;
|
|
@@ -851,10 +1562,58 @@ var SessionStateStoreImpl = class {
|
|
|
851
1562
|
return this.db;
|
|
852
1563
|
}
|
|
853
1564
|
resolveLegacyPath(sessionId) {
|
|
854
|
-
return
|
|
1565
|
+
return path9.join(this.legacyStateDir, `${sessionId}.json`);
|
|
855
1566
|
}
|
|
856
1567
|
resolveMessagePath(sessionId) {
|
|
857
|
-
return
|
|
1568
|
+
return path9.join(this.messagesDir, `${validateRunLogId(sessionId)}.jsonl`);
|
|
1569
|
+
}
|
|
1570
|
+
contextPath(sessionId) {
|
|
1571
|
+
return path9.join(this.contextsDir, `${validateRunLogId(sessionId)}.json`);
|
|
1572
|
+
}
|
|
1573
|
+
writeContext(sessionId, messages) {
|
|
1574
|
+
const target = this.contextPath(sessionId);
|
|
1575
|
+
const temporary = `${target}.${crypto.randomUUID()}.tmp`;
|
|
1576
|
+
const archiveBytes = lstatSync2(this.resolveMessagePath(sessionId)).size;
|
|
1577
|
+
try {
|
|
1578
|
+
const fd = openSync2(temporary, "wx", 384);
|
|
1579
|
+
try {
|
|
1580
|
+
writeFileSync(
|
|
1581
|
+
fd,
|
|
1582
|
+
JSON.stringify({ version: 1, archive_bytes: archiveBytes, messages })
|
|
1583
|
+
);
|
|
1584
|
+
fsyncSync2(fd);
|
|
1585
|
+
} finally {
|
|
1586
|
+
closeSync2(fd);
|
|
1587
|
+
}
|
|
1588
|
+
renameSync(temporary, target);
|
|
1589
|
+
} finally {
|
|
1590
|
+
if (existsSync2(temporary)) unlinkSync(temporary);
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
ensureArchive(sessionId, db) {
|
|
1594
|
+
const row = db.get(
|
|
1595
|
+
"SELECT archive_version FROM session_state WHERE session_id = ?",
|
|
1596
|
+
[sessionId]
|
|
1597
|
+
);
|
|
1598
|
+
if (row?.archive_version === 1) {
|
|
1599
|
+
if (!lstatSync2(this.resolveMessagePath(sessionId)).isFile())
|
|
1600
|
+
throw new Error("Invalid original conversation archive");
|
|
1601
|
+
return false;
|
|
1602
|
+
}
|
|
1603
|
+
const file = this.resolveMessagePath(sessionId);
|
|
1604
|
+
let messages = [];
|
|
1605
|
+
if (existsSync2(file)) {
|
|
1606
|
+
if (!lstatSync2(file).isFile())
|
|
1607
|
+
throw new Error("Invalid legacy conversation file");
|
|
1608
|
+
messages = deserializeMessages(readFileSync(file, "utf8"));
|
|
1609
|
+
} else appendOriginalMessages(file, []);
|
|
1610
|
+
this.writeContext(sessionId, messages);
|
|
1611
|
+
db.run(
|
|
1612
|
+
`INSERT INTO session_state (session_id, updated_at, schema_version, archive_version) VALUES (?, ?, 1, 1)
|
|
1613
|
+
ON CONFLICT(session_id) DO UPDATE SET archive_version = 1`,
|
|
1614
|
+
[sessionId, (/* @__PURE__ */ new Date()).toISOString()]
|
|
1615
|
+
);
|
|
1616
|
+
return messages.length === 0;
|
|
858
1617
|
}
|
|
859
1618
|
async openDatabase() {
|
|
860
1619
|
await this.ensureDirs;
|
|
@@ -895,33 +1654,82 @@ var SessionStateStoreImpl = class {
|
|
|
895
1654
|
};
|
|
896
1655
|
}
|
|
897
1656
|
initDatabaseSchema(db) {
|
|
1657
|
+
db.exec("PRAGMA busy_timeout = 5000;");
|
|
898
1658
|
db.exec("PRAGMA journal_mode = WAL;");
|
|
899
|
-
db.exec(
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
1659
|
+
db.exec("BEGIN IMMEDIATE");
|
|
1660
|
+
try {
|
|
1661
|
+
db.exec(`
|
|
1662
|
+
CREATE TABLE IF NOT EXISTS session_state (
|
|
1663
|
+
session_id TEXT PRIMARY KEY,
|
|
1664
|
+
updated_at TEXT NOT NULL,
|
|
1665
|
+
run_id TEXT,
|
|
1666
|
+
invoke_seq INTEGER,
|
|
1667
|
+
schema_version INTEGER NOT NULL,
|
|
1668
|
+
meta_json TEXT,
|
|
1669
|
+
message_count INTEGER,
|
|
1670
|
+
last_user_message TEXT,
|
|
1671
|
+
workspace_root TEXT
|
|
1672
|
+
);
|
|
1673
|
+
`);
|
|
1674
|
+
const columns = db.all(
|
|
1675
|
+
"PRAGMA table_info(session_state)"
|
|
1676
|
+
);
|
|
1677
|
+
const columnNames = new Set(
|
|
1678
|
+
columns.map((column) => column.name).filter((name) => typeof name === "string")
|
|
1679
|
+
);
|
|
1680
|
+
if (!columnNames.has("workspace_root")) {
|
|
1681
|
+
db.exec("ALTER TABLE session_state ADD COLUMN workspace_root TEXT;");
|
|
1682
|
+
}
|
|
1683
|
+
if (!columnNames.has("pinned"))
|
|
1684
|
+
db.exec(
|
|
1685
|
+
"ALTER TABLE session_state ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0;"
|
|
1686
|
+
);
|
|
1687
|
+
if (!columnNames.has("archived_at"))
|
|
1688
|
+
db.exec("ALTER TABLE session_state ADD COLUMN archived_at TEXT;");
|
|
1689
|
+
if (!columnNames.has("archive_version"))
|
|
1690
|
+
db.exec(
|
|
1691
|
+
"ALTER TABLE session_state ADD COLUMN archive_version INTEGER NOT NULL DEFAULT 0;"
|
|
1692
|
+
);
|
|
1693
|
+
db.exec(`
|
|
1694
|
+
CREATE INDEX IF NOT EXISTS idx_session_state_updated_at
|
|
1695
|
+
ON session_state(updated_at DESC);
|
|
1696
|
+
`);
|
|
1697
|
+
db.exec(`
|
|
1698
|
+
CREATE TABLE IF NOT EXISTS session_runs (
|
|
1699
|
+
rel_path TEXT PRIMARY KEY,
|
|
1700
|
+
session_id TEXT NOT NULL,
|
|
1701
|
+
run_id TEXT NOT NULL,
|
|
1702
|
+
started_at TEXT NOT NULL
|
|
1703
|
+
);
|
|
1704
|
+
`);
|
|
1705
|
+
db.exec(`
|
|
1706
|
+
CREATE INDEX IF NOT EXISTS idx_session_runs_session
|
|
1707
|
+
ON session_runs(session_id, started_at DESC);
|
|
1708
|
+
`);
|
|
1709
|
+
db.exec(`
|
|
1710
|
+
CREATE TABLE IF NOT EXISTS session_run_checks (
|
|
1711
|
+
session_id TEXT PRIMARY KEY,
|
|
1712
|
+
run_id TEXT NOT NULL,
|
|
1713
|
+
checked_at TEXT NOT NULL
|
|
1714
|
+
);
|
|
1715
|
+
`);
|
|
1716
|
+
db.exec(`
|
|
1717
|
+
CREATE TABLE IF NOT EXISTS session_run_rescans (
|
|
1718
|
+
session_id TEXT PRIMARY KEY,
|
|
1719
|
+
flagged_at TEXT NOT NULL
|
|
1720
|
+
);
|
|
1721
|
+
`);
|
|
1722
|
+
db.exec(`
|
|
1723
|
+
CREATE TABLE IF NOT EXISTS storage_meta (
|
|
1724
|
+
key TEXT PRIMARY KEY,
|
|
1725
|
+
value TEXT NOT NULL
|
|
1726
|
+
);
|
|
1727
|
+
`);
|
|
1728
|
+
db.exec("COMMIT");
|
|
1729
|
+
} catch (error) {
|
|
1730
|
+
db.exec("ROLLBACK");
|
|
1731
|
+
throw error;
|
|
920
1732
|
}
|
|
921
|
-
db.exec(`
|
|
922
|
-
CREATE INDEX IF NOT EXISTS idx_session_state_updated_at
|
|
923
|
-
ON session_state(updated_at DESC);
|
|
924
|
-
`);
|
|
925
1733
|
}
|
|
926
1734
|
async tryGetDb(action, detail) {
|
|
927
1735
|
try {
|
|
@@ -952,7 +1760,7 @@ var SessionStateStoreImpl = class {
|
|
|
952
1760
|
}
|
|
953
1761
|
async loadLegacy(sessionId) {
|
|
954
1762
|
try {
|
|
955
|
-
const file = await
|
|
1763
|
+
const file = await fs7.readFile(this.resolveLegacyPath(sessionId), "utf8");
|
|
956
1764
|
const parsed = JSON.parse(file);
|
|
957
1765
|
if (!parsed || typeof parsed !== "object") return null;
|
|
958
1766
|
if (!parsed.session_id || !parsed.updated_at) return null;
|
|
@@ -978,7 +1786,7 @@ var SessionStateStoreImpl = class {
|
|
|
978
1786
|
let row;
|
|
979
1787
|
try {
|
|
980
1788
|
row = db.get(
|
|
981
|
-
`SELECT session_id, updated_at, run_id, invoke_seq, schema_version, meta_json
|
|
1789
|
+
`SELECT session_id, updated_at, run_id, invoke_seq, schema_version, meta_json, archive_version
|
|
982
1790
|
FROM session_state
|
|
983
1791
|
WHERE session_id = ?`,
|
|
984
1792
|
[sessionId]
|
|
@@ -990,13 +1798,19 @@ var SessionStateStoreImpl = class {
|
|
|
990
1798
|
if (!row) return null;
|
|
991
1799
|
let messages;
|
|
992
1800
|
try {
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
1801
|
+
if (row.archive_version === 1) {
|
|
1802
|
+
const checkpoint = JSON.parse(
|
|
1803
|
+
await fs7.readFile(this.contextPath(sessionId), "utf8")
|
|
1804
|
+
);
|
|
1805
|
+
if (checkpoint.version !== 1 || !Array.isArray(checkpoint.messages))
|
|
1806
|
+
throw new Error("Invalid active conversation checkpoint");
|
|
1807
|
+
messages = checkpoint.messages;
|
|
1808
|
+
} else
|
|
1809
|
+
messages = deserializeMessages(
|
|
1810
|
+
await fs7.readFile(this.resolveMessagePath(sessionId), "utf8")
|
|
1811
|
+
);
|
|
998
1812
|
} catch (error) {
|
|
999
|
-
if (error.code === "ENOENT") {
|
|
1813
|
+
if (error.code === "ENOENT" && row.archive_version !== 1) {
|
|
1000
1814
|
messages = [];
|
|
1001
1815
|
} else {
|
|
1002
1816
|
this.onError?.(error, { action: "messages.load", detail: sessionId });
|
|
@@ -1028,16 +1842,17 @@ var SessionStateStoreImpl = class {
|
|
|
1028
1842
|
};
|
|
1029
1843
|
}
|
|
1030
1844
|
async saveToIndex(state, db) {
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1845
|
+
await this.withRetentionGuard(state.session_id, () => {
|
|
1846
|
+
const seed = this.ensureArchive(state.session_id, db);
|
|
1847
|
+
if (seed)
|
|
1848
|
+
appendOriginalMessages(
|
|
1849
|
+
this.resolveMessagePath(state.session_id),
|
|
1850
|
+
state.messages
|
|
1851
|
+
);
|
|
1852
|
+
this.writeContext(state.session_id, state.messages);
|
|
1853
|
+
const summary = toSummary(state);
|
|
1854
|
+
db.run(
|
|
1855
|
+
`INSERT INTO session_state (
|
|
1041
1856
|
session_id,
|
|
1042
1857
|
updated_at,
|
|
1043
1858
|
run_id,
|
|
@@ -1058,18 +1873,35 @@ var SessionStateStoreImpl = class {
|
|
|
1058
1873
|
message_count = excluded.message_count,
|
|
1059
1874
|
last_user_message = excluded.last_user_message,
|
|
1060
1875
|
workspace_root = excluded.workspace_root`,
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1876
|
+
[
|
|
1877
|
+
state.session_id,
|
|
1878
|
+
state.updated_at,
|
|
1879
|
+
state.run_id ?? null,
|
|
1880
|
+
state.invoke_seq ?? null,
|
|
1881
|
+
state.schema_version ?? 1,
|
|
1882
|
+
state.meta ? JSON.stringify(state.meta) : null,
|
|
1883
|
+
summary.message_count ?? null,
|
|
1884
|
+
summary.last_user_message ?? null,
|
|
1885
|
+
summary.workspace_root ?? null
|
|
1886
|
+
]
|
|
1887
|
+
);
|
|
1888
|
+
});
|
|
1889
|
+
}
|
|
1890
|
+
async appendMessages(sessionId, messages) {
|
|
1891
|
+
const db = await this.requireDb("archive.append", sessionId);
|
|
1892
|
+
if (!await this.getSummary(sessionId)) await this.load(sessionId);
|
|
1893
|
+
await this.withRetentionGuard(sessionId, () => {
|
|
1894
|
+
this.ensureArchive(sessionId, db);
|
|
1895
|
+
appendOriginalMessages(this.resolveMessagePath(sessionId), messages);
|
|
1896
|
+
});
|
|
1897
|
+
}
|
|
1898
|
+
async searchMessages(sessionId, options) {
|
|
1899
|
+
if (!await this.getSummary(sessionId)) await this.load(sessionId);
|
|
1900
|
+
return searchOriginalMessages(this.resolveMessagePath(sessionId), options);
|
|
1901
|
+
}
|
|
1902
|
+
async readMessage(sessionId, options) {
|
|
1903
|
+
if (!await this.getSummary(sessionId)) await this.load(sessionId);
|
|
1904
|
+
return readOriginalMessage(this.resolveMessagePath(sessionId), options);
|
|
1073
1905
|
}
|
|
1074
1906
|
async load(sessionId) {
|
|
1075
1907
|
const db = await this.requireDb("load", sessionId);
|
|
@@ -1090,6 +1922,7 @@ var SessionStateStoreImpl = class {
|
|
|
1090
1922
|
action: "load.migrate_legacy",
|
|
1091
1923
|
detail: sessionId
|
|
1092
1924
|
});
|
|
1925
|
+
throw error;
|
|
1093
1926
|
}
|
|
1094
1927
|
}
|
|
1095
1928
|
return legacy;
|
|
@@ -1104,10 +1937,192 @@ var SessionStateStoreImpl = class {
|
|
|
1104
1937
|
throw error;
|
|
1105
1938
|
}
|
|
1106
1939
|
}
|
|
1940
|
+
async getSummary(sessionId) {
|
|
1941
|
+
const db = await this.requireDb("summary", sessionId);
|
|
1942
|
+
const row = db.get(
|
|
1943
|
+
"SELECT session_id, updated_at, run_id, message_count, last_user_message, workspace_root, pinned, archived_at FROM session_state WHERE session_id = ?",
|
|
1944
|
+
[sessionId]
|
|
1945
|
+
);
|
|
1946
|
+
return row ? fromSummaryRow(row) : null;
|
|
1947
|
+
}
|
|
1948
|
+
/** Serializes pin changes with the final, synchronous unlink decision. */
|
|
1949
|
+
async withRetentionGuard(sessionId, action) {
|
|
1950
|
+
const db = await this.requireDb("retention", sessionId);
|
|
1951
|
+
db.exec("BEGIN IMMEDIATE");
|
|
1952
|
+
try {
|
|
1953
|
+
const row = db.get(
|
|
1954
|
+
"SELECT session_id, updated_at, run_id, message_count, last_user_message, workspace_root, pinned, archived_at FROM session_state WHERE session_id = ?",
|
|
1955
|
+
[sessionId]
|
|
1956
|
+
);
|
|
1957
|
+
const result = action(row ? fromSummaryRow(row) : null);
|
|
1958
|
+
db.exec("COMMIT");
|
|
1959
|
+
return result;
|
|
1960
|
+
} catch (error) {
|
|
1961
|
+
db.exec("ROLLBACK");
|
|
1962
|
+
throw error;
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
async updateMetadata(sessionId, patch) {
|
|
1966
|
+
if (!await this.getSummary(sessionId)) await this.load(sessionId);
|
|
1967
|
+
const db = await this.requireDb("updateMetadata", sessionId);
|
|
1968
|
+
return this.withRetentionGuard(sessionId, (summary) => {
|
|
1969
|
+
if (!summary) throw new Error("Session not found");
|
|
1970
|
+
if (patch.pinned !== void 0)
|
|
1971
|
+
db.run("UPDATE session_state SET pinned = ? WHERE session_id = ?", [
|
|
1972
|
+
patch.pinned ? 1 : 0,
|
|
1973
|
+
sessionId
|
|
1974
|
+
]);
|
|
1975
|
+
const archivedAt = patch.archived === void 0 ? summary.archived_at : patch.archived ? summary.archived_at ?? (/* @__PURE__ */ new Date()).toISOString() : void 0;
|
|
1976
|
+
if (patch.archived !== void 0)
|
|
1977
|
+
db.run(
|
|
1978
|
+
"UPDATE session_state SET archived_at = ? WHERE session_id = ?",
|
|
1979
|
+
[archivedAt ?? null, sessionId]
|
|
1980
|
+
);
|
|
1981
|
+
return {
|
|
1982
|
+
...summary,
|
|
1983
|
+
pinned: patch.pinned ?? summary.pinned,
|
|
1984
|
+
archived_at: archivedAt
|
|
1985
|
+
};
|
|
1986
|
+
});
|
|
1987
|
+
}
|
|
1988
|
+
/** Records a run log; idempotent, safe across concurrent runtimes. */
|
|
1989
|
+
async recordSessionRun(entry) {
|
|
1990
|
+
const db = await this.requireDb("runs.record", entry.session_id);
|
|
1991
|
+
db.exec("BEGIN IMMEDIATE");
|
|
1992
|
+
try {
|
|
1993
|
+
const previous = db.get(
|
|
1994
|
+
"SELECT run_id FROM session_state WHERE session_id = ?",
|
|
1995
|
+
[entry.session_id]
|
|
1996
|
+
)?.run_id;
|
|
1997
|
+
if (previous && previous !== entry.run_id && !this.isRunKnown(db, entry.session_id, previous))
|
|
1998
|
+
db.run(
|
|
1999
|
+
`INSERT INTO session_run_rescans (session_id, flagged_at) VALUES (?, ?)
|
|
2000
|
+
ON CONFLICT(session_id) DO UPDATE SET flagged_at = excluded.flagged_at`,
|
|
2001
|
+
[entry.session_id, (/* @__PURE__ */ new Date()).toISOString()]
|
|
2002
|
+
);
|
|
2003
|
+
db.run(
|
|
2004
|
+
`INSERT INTO session_runs (rel_path, session_id, run_id, started_at)
|
|
2005
|
+
VALUES (?, ?, ?, ?)
|
|
2006
|
+
ON CONFLICT(rel_path) DO NOTHING`,
|
|
2007
|
+
[
|
|
2008
|
+
entry.rel_path,
|
|
2009
|
+
entry.session_id,
|
|
2010
|
+
entry.run_id,
|
|
2011
|
+
normalizeRunStartedAt(entry.started_at)
|
|
2012
|
+
]
|
|
2013
|
+
);
|
|
2014
|
+
db.exec("COMMIT");
|
|
2015
|
+
} catch (error) {
|
|
2016
|
+
db.exec("ROLLBACK");
|
|
2017
|
+
throw error;
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
/** True when run_id is indexed for the session or was already rescanned. */
|
|
2021
|
+
isRunKnown(db, sessionId, runId) {
|
|
2022
|
+
return Boolean(
|
|
2023
|
+
db.get(
|
|
2024
|
+
"SELECT 1 AS ok FROM session_runs WHERE session_id = ? AND run_id = ? LIMIT 1",
|
|
2025
|
+
[sessionId, runId]
|
|
2026
|
+
) ?? db.get(
|
|
2027
|
+
"SELECT 1 AS ok FROM session_run_checks WHERE session_id = ? AND run_id = ?",
|
|
2028
|
+
[sessionId, runId]
|
|
2029
|
+
)
|
|
2030
|
+
);
|
|
2031
|
+
}
|
|
2032
|
+
/**
|
|
2033
|
+
* The index answers for a session once a store-wide backfill finished and
|
|
2034
|
+
* the session's latest run_id is either indexed or was already rescanned.
|
|
2035
|
+
* The run_id check catches logs written by runtimes that predate the index.
|
|
2036
|
+
*/
|
|
2037
|
+
isSessionRunIndexComplete(db, sessionId) {
|
|
2038
|
+
if (!db.get("SELECT 1 AS ok FROM storage_meta WHERE key = ?", [
|
|
2039
|
+
RUN_INDEX_BACKFILL_KEY
|
|
2040
|
+
]))
|
|
2041
|
+
return false;
|
|
2042
|
+
if (db.get("SELECT 1 AS ok FROM session_run_rescans WHERE session_id = ?", [
|
|
2043
|
+
sessionId
|
|
2044
|
+
]))
|
|
2045
|
+
return false;
|
|
2046
|
+
const latest = db.get(
|
|
2047
|
+
"SELECT run_id FROM session_state WHERE session_id = ?",
|
|
2048
|
+
[sessionId]
|
|
2049
|
+
)?.run_id;
|
|
2050
|
+
return !latest || this.isRunKnown(db, sessionId, latest);
|
|
2051
|
+
}
|
|
2052
|
+
/** One store-wide header scan per process at a time; rows are idempotent. */
|
|
2053
|
+
backfillSessionRuns(db) {
|
|
2054
|
+
if (!this.runIndexBackfill) {
|
|
2055
|
+
this.runIndexBackfill = (async () => {
|
|
2056
|
+
const scanStartedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2057
|
+
const entries2 = await scanSessionRunLogs(this.sessionsDir);
|
|
2058
|
+
db.exec("BEGIN IMMEDIATE");
|
|
2059
|
+
try {
|
|
2060
|
+
for (const entry of entries2)
|
|
2061
|
+
db.run(
|
|
2062
|
+
`INSERT INTO session_runs (rel_path, session_id, run_id, started_at)
|
|
2063
|
+
VALUES (?, ?, ?, ?)
|
|
2064
|
+
ON CONFLICT(rel_path) DO NOTHING`,
|
|
2065
|
+
[
|
|
2066
|
+
entry.rel_path,
|
|
2067
|
+
entry.session_id,
|
|
2068
|
+
entry.run_id,
|
|
2069
|
+
entry.started_at
|
|
2070
|
+
]
|
|
2071
|
+
);
|
|
2072
|
+
db.run(
|
|
2073
|
+
`INSERT INTO storage_meta (key, value) VALUES (?, ?)
|
|
2074
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
|
|
2075
|
+
[RUN_INDEX_BACKFILL_KEY, (/* @__PURE__ */ new Date()).toISOString()]
|
|
2076
|
+
);
|
|
2077
|
+
db.run("DELETE FROM session_run_rescans WHERE flagged_at <= ?", [
|
|
2078
|
+
scanStartedAt
|
|
2079
|
+
]);
|
|
2080
|
+
db.exec("COMMIT");
|
|
2081
|
+
} catch (error) {
|
|
2082
|
+
db.exec("ROLLBACK");
|
|
2083
|
+
throw error;
|
|
2084
|
+
}
|
|
2085
|
+
})().finally(() => {
|
|
2086
|
+
this.runIndexBackfill = null;
|
|
2087
|
+
});
|
|
2088
|
+
}
|
|
2089
|
+
return this.runIndexBackfill;
|
|
2090
|
+
}
|
|
2091
|
+
/**
|
|
2092
|
+
* Returns the session's run logs, newest first. Falls back to one
|
|
2093
|
+
* store-wide header scan (which indexes every session) only while the
|
|
2094
|
+
* index cannot answer for this session.
|
|
2095
|
+
*/
|
|
2096
|
+
async listSessionRuns(sessionId) {
|
|
2097
|
+
const db = await this.requireDb("runs.list", sessionId);
|
|
2098
|
+
if (!this.isSessionRunIndexComplete(db, sessionId)) {
|
|
2099
|
+
const latest = db.get(
|
|
2100
|
+
"SELECT run_id FROM session_state WHERE session_id = ?",
|
|
2101
|
+
[sessionId]
|
|
2102
|
+
)?.run_id;
|
|
2103
|
+
await this.backfillSessionRuns(db);
|
|
2104
|
+
if (latest)
|
|
2105
|
+
db.run(
|
|
2106
|
+
`INSERT INTO session_run_checks (session_id, run_id, checked_at)
|
|
2107
|
+
VALUES (?, ?, ?)
|
|
2108
|
+
ON CONFLICT(session_id) DO UPDATE SET
|
|
2109
|
+
run_id = excluded.run_id,
|
|
2110
|
+
checked_at = excluded.checked_at`,
|
|
2111
|
+
[sessionId, latest, (/* @__PURE__ */ new Date()).toISOString()]
|
|
2112
|
+
);
|
|
2113
|
+
}
|
|
2114
|
+
return db.all(
|
|
2115
|
+
`SELECT session_id, run_id, rel_path, started_at
|
|
2116
|
+
FROM session_runs
|
|
2117
|
+
WHERE session_id = ?
|
|
2118
|
+
ORDER BY started_at DESC, rel_path DESC`,
|
|
2119
|
+
[sessionId]
|
|
2120
|
+
);
|
|
2121
|
+
}
|
|
1107
2122
|
async listLegacySummaries() {
|
|
1108
|
-
let
|
|
2123
|
+
let entries2;
|
|
1109
2124
|
try {
|
|
1110
|
-
|
|
2125
|
+
entries2 = await fs7.readdir(this.legacyStateDir, {
|
|
1111
2126
|
withFileTypes: true,
|
|
1112
2127
|
encoding: "utf8"
|
|
1113
2128
|
});
|
|
@@ -1116,12 +2131,12 @@ var SessionStateStoreImpl = class {
|
|
|
1116
2131
|
throw error;
|
|
1117
2132
|
}
|
|
1118
2133
|
const summaries = [];
|
|
1119
|
-
for (const entry of
|
|
2134
|
+
for (const entry of entries2) {
|
|
1120
2135
|
if (!entry.isFile()) continue;
|
|
1121
2136
|
if (!entry.name.endsWith(".json")) continue;
|
|
1122
|
-
const filePath =
|
|
2137
|
+
const filePath = path9.join(this.legacyStateDir, entry.name);
|
|
1123
2138
|
try {
|
|
1124
|
-
const contents = await
|
|
2139
|
+
const contents = await fs7.readFile(filePath, "utf8");
|
|
1125
2140
|
const parsed = JSON.parse(contents);
|
|
1126
2141
|
if (!parsed || typeof parsed !== "object") continue;
|
|
1127
2142
|
if (!parsed.session_id || !parsed.updated_at) continue;
|
|
@@ -1144,7 +2159,7 @@ var SessionStateStoreImpl = class {
|
|
|
1144
2159
|
const db = await this.requireDb("list");
|
|
1145
2160
|
try {
|
|
1146
2161
|
const rows = db.all(
|
|
1147
|
-
`SELECT session_id, updated_at, run_id, message_count, last_user_message, workspace_root
|
|
2162
|
+
`SELECT session_id, updated_at, run_id, message_count, last_user_message, workspace_root, pinned, archived_at
|
|
1148
2163
|
FROM session_state
|
|
1149
2164
|
ORDER BY updated_at DESC`
|
|
1150
2165
|
);
|
|
@@ -1165,9 +2180,721 @@ var SessionStateStoreImpl = class {
|
|
|
1165
2180
|
}
|
|
1166
2181
|
};
|
|
1167
2182
|
|
|
2183
|
+
// src/run-event-store.ts
|
|
2184
|
+
var RunEventStoreFactoryImpl = class {
|
|
2185
|
+
runIndex;
|
|
2186
|
+
onRunIndexError;
|
|
2187
|
+
/**
|
|
2188
|
+
* `runIndex` records each run in state.db (`session_runs`). When omitted, a
|
|
2189
|
+
* default-path SessionStateStoreImpl is created on the first run so every
|
|
2190
|
+
* normal run log stays indexed.
|
|
2191
|
+
*/
|
|
2192
|
+
constructor(options = {}) {
|
|
2193
|
+
this.runIndex = options.runIndex;
|
|
2194
|
+
this.onRunIndexError = options.onRunIndexError;
|
|
2195
|
+
}
|
|
2196
|
+
create(init) {
|
|
2197
|
+
this.runIndex ??= new SessionStateStoreImpl();
|
|
2198
|
+
return new SessionStoreWriterImpl({
|
|
2199
|
+
runId: init.runId,
|
|
2200
|
+
startedAt: init.startedAt,
|
|
2201
|
+
runIndex: this.runIndex,
|
|
2202
|
+
onRunIndexError: this.onRunIndexError
|
|
2203
|
+
});
|
|
2204
|
+
}
|
|
2205
|
+
};
|
|
2206
|
+
|
|
2207
|
+
// src/run-log-retention.ts
|
|
2208
|
+
import {
|
|
2209
|
+
promises as fs11,
|
|
2210
|
+
linkSync,
|
|
2211
|
+
lstatSync as lstatSync4,
|
|
2212
|
+
renameSync as renameSync2,
|
|
2213
|
+
unlinkSync as unlinkSync3,
|
|
2214
|
+
utimesSync
|
|
2215
|
+
} from "fs";
|
|
2216
|
+
import path12 from "path";
|
|
2217
|
+
|
|
2218
|
+
// src/run-log-compression.ts
|
|
2219
|
+
import { createHash as createHash4 } from "crypto";
|
|
2220
|
+
import { createReadStream as createReadStream2, createWriteStream, promises as fs8 } from "fs";
|
|
2221
|
+
import { Readable as Readable2, Transform } from "stream";
|
|
2222
|
+
import { pipeline } from "stream/promises";
|
|
2223
|
+
import { createGunzip as createGunzip2, createGzip } from "zlib";
|
|
2224
|
+
|
|
2225
|
+
// src/run-log-records.ts
|
|
2226
|
+
var MAX_RECORD_PREFIX_BYTES = 256;
|
|
2227
|
+
var RECORD_TYPE = /^\s*\{\s*"type"\s*:\s*"([^"\\]+)"/;
|
|
2228
|
+
async function* readRunLogRecordParts(file) {
|
|
2229
|
+
let prefix = Buffer.alloc(0);
|
|
2230
|
+
let type;
|
|
2231
|
+
for await (const chunk of readRunLogChunks(file)) {
|
|
2232
|
+
let offset = 0;
|
|
2233
|
+
while (offset < chunk.length) {
|
|
2234
|
+
const newline = chunk.indexOf(10, offset);
|
|
2235
|
+
const next = newline < 0 ? chunk.length : newline + 1;
|
|
2236
|
+
const data = chunk.subarray(offset, next);
|
|
2237
|
+
const end = newline >= 0;
|
|
2238
|
+
if (type === void 0) {
|
|
2239
|
+
const consumed = Math.min(
|
|
2240
|
+
MAX_RECORD_PREFIX_BYTES - prefix.length,
|
|
2241
|
+
data.length
|
|
2242
|
+
);
|
|
2243
|
+
prefix = Buffer.concat([prefix, data.subarray(0, consumed)]);
|
|
2244
|
+
const match = RECORD_TYPE.exec(prefix.toString("utf8"));
|
|
2245
|
+
if (!match) {
|
|
2246
|
+
if (end || prefix.length === MAX_RECORD_PREFIX_BYTES)
|
|
2247
|
+
throw new Error("Invalid run log record prefix");
|
|
2248
|
+
} else {
|
|
2249
|
+
type = match[1];
|
|
2250
|
+
yield {
|
|
2251
|
+
type,
|
|
2252
|
+
data: prefix,
|
|
2253
|
+
start: true,
|
|
2254
|
+
end: end && consumed === data.length
|
|
2255
|
+
};
|
|
2256
|
+
prefix = Buffer.alloc(0);
|
|
2257
|
+
if (consumed < data.length)
|
|
2258
|
+
yield { type, data: data.subarray(consumed), start: false, end };
|
|
2259
|
+
}
|
|
2260
|
+
} else yield { type, data, start: false, end };
|
|
2261
|
+
if (end) type = void 0;
|
|
2262
|
+
offset = next;
|
|
2263
|
+
}
|
|
2264
|
+
}
|
|
2265
|
+
if (type !== void 0 || prefix.length)
|
|
2266
|
+
throw new Error("Incomplete run log record");
|
|
2267
|
+
}
|
|
2268
|
+
|
|
2269
|
+
// src/run-log-archive.ts
|
|
2270
|
+
var RUN_LOG_ARCHIVE_VERSION = 1;
|
|
2271
|
+
var MAX_RUN_LOG_HEADER_BYTES = 256 * 1024;
|
|
2272
|
+
var DIAGNOSTIC_RECORDS = /* @__PURE__ */ new Set([
|
|
2273
|
+
"llm.request",
|
|
2274
|
+
"llm.response",
|
|
2275
|
+
"tool.output"
|
|
2276
|
+
]);
|
|
2277
|
+
async function* projectArchivedRunLog(file, usage) {
|
|
2278
|
+
let headerSeen = false;
|
|
2279
|
+
let headerParts = [];
|
|
2280
|
+
let headerBytes = 0;
|
|
2281
|
+
for await (const part of readRunLogRecordParts(file)) {
|
|
2282
|
+
if (!headerSeen && part.type !== "header")
|
|
2283
|
+
throw new Error("Run log must start with its header");
|
|
2284
|
+
if (part.type === "header") {
|
|
2285
|
+
if (headerSeen) throw new Error("Duplicate run log header");
|
|
2286
|
+
headerBytes += part.data.length;
|
|
2287
|
+
if (headerBytes > MAX_RUN_LOG_HEADER_BYTES)
|
|
2288
|
+
throw new Error("Run log header is too large");
|
|
2289
|
+
headerParts.push(part.data);
|
|
2290
|
+
if (part.end) {
|
|
2291
|
+
const header = JSON.parse(
|
|
2292
|
+
Buffer.concat(headerParts, headerBytes).toString("utf8")
|
|
2293
|
+
);
|
|
2294
|
+
const { prompts: _prompts, tools: _tools, ...retained } = header;
|
|
2295
|
+
yield Buffer.from(
|
|
2296
|
+
`${JSON.stringify({
|
|
2297
|
+
...retained,
|
|
2298
|
+
meta: {
|
|
2299
|
+
...retained.meta,
|
|
2300
|
+
codelia_log_archive_version: RUN_LOG_ARCHIVE_VERSION
|
|
2301
|
+
}
|
|
2302
|
+
})}
|
|
2303
|
+
`
|
|
2304
|
+
);
|
|
2305
|
+
headerSeen = true;
|
|
2306
|
+
headerParts = [];
|
|
2307
|
+
}
|
|
2308
|
+
} else if (part.type !== "llm.usage" && !DIAGNOSTIC_RECORDS.has(part.type)) {
|
|
2309
|
+
yield part.data;
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
if (!headerSeen) throw new Error("Missing run log header");
|
|
2313
|
+
for (const record2 of usage) yield Buffer.from(`${JSON.stringify(record2)}
|
|
2314
|
+
`);
|
|
2315
|
+
}
|
|
2316
|
+
|
|
2317
|
+
// src/run-log-compression.ts
|
|
2318
|
+
async function prepareCompressedLog(file, usage) {
|
|
2319
|
+
const temporary = `${file}.${crypto.randomUUID()}.gz.tmp`;
|
|
2320
|
+
const hash = createHash4("sha256");
|
|
2321
|
+
let bytes = 0;
|
|
2322
|
+
try {
|
|
2323
|
+
await pipeline(
|
|
2324
|
+
Readable2.from(projectArchivedRunLog(file, usage)),
|
|
2325
|
+
new Transform({
|
|
2326
|
+
transform(chunk, _encoding, callback) {
|
|
2327
|
+
bytes += chunk.length;
|
|
2328
|
+
hash.update(chunk);
|
|
2329
|
+
callback(null, chunk);
|
|
2330
|
+
}
|
|
2331
|
+
}),
|
|
2332
|
+
createGzip(),
|
|
2333
|
+
createWriteStream(temporary, { flags: "wx", mode: 384 })
|
|
2334
|
+
);
|
|
2335
|
+
const expected = hash.digest("hex");
|
|
2336
|
+
const verification = createHash4("sha256");
|
|
2337
|
+
let decoded = 0;
|
|
2338
|
+
await pipeline(
|
|
2339
|
+
createReadStream2(temporary),
|
|
2340
|
+
createGunzip2(),
|
|
2341
|
+
new Transform({
|
|
2342
|
+
transform(chunk, _encoding, callback) {
|
|
2343
|
+
decoded += chunk.length;
|
|
2344
|
+
verification.update(chunk);
|
|
2345
|
+
callback();
|
|
2346
|
+
}
|
|
2347
|
+
})
|
|
2348
|
+
);
|
|
2349
|
+
if (decoded !== bytes || verification.digest("hex") !== expected)
|
|
2350
|
+
throw new Error("Compressed run log verification failed");
|
|
2351
|
+
const persisted = await fs8.open(temporary, "r+");
|
|
2352
|
+
try {
|
|
2353
|
+
await persisted.sync();
|
|
2354
|
+
} finally {
|
|
2355
|
+
await persisted.close();
|
|
2356
|
+
}
|
|
2357
|
+
return { temporary, size: (await fs8.stat(temporary)).size };
|
|
2358
|
+
} catch (error) {
|
|
2359
|
+
await fs8.rm(temporary, { force: true });
|
|
2360
|
+
throw error;
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
|
|
2364
|
+
// src/run-log-files.ts
|
|
2365
|
+
import {
|
|
2366
|
+
promises as fs9,
|
|
2367
|
+
lstatSync as lstatSync3,
|
|
2368
|
+
readdirSync,
|
|
2369
|
+
readFileSync as readFileSync2,
|
|
2370
|
+
unlinkSync as unlinkSync2
|
|
2371
|
+
} from "fs";
|
|
2372
|
+
import path10 from "path";
|
|
2373
|
+
var MAX_ACTIVE_RUN_MARKER_BYTES = 256;
|
|
2374
|
+
var isRegularDirectory = async (directory2) => {
|
|
2375
|
+
try {
|
|
2376
|
+
return (await fs9.lstat(directory2)).isDirectory();
|
|
2377
|
+
} catch {
|
|
2378
|
+
return false;
|
|
2379
|
+
}
|
|
2380
|
+
};
|
|
2381
|
+
async function readHeader2(file) {
|
|
2382
|
+
const parts = [];
|
|
2383
|
+
let length = 0;
|
|
2384
|
+
for await (const chunk of readRunLogChunks(file)) {
|
|
2385
|
+
const newline = chunk.indexOf(10);
|
|
2386
|
+
const part = newline < 0 ? chunk : chunk.subarray(0, newline + 1);
|
|
2387
|
+
length += part.length;
|
|
2388
|
+
if (length > MAX_RUN_LOG_HEADER_BYTES) return null;
|
|
2389
|
+
parts.push(part);
|
|
2390
|
+
if (newline < 0) continue;
|
|
2391
|
+
const record2 = JSON.parse(Buffer.concat(parts, length).toString("utf8"));
|
|
2392
|
+
if (record2.type !== "header" || typeof record2.run_id !== "string" || typeof record2.session_id !== "string")
|
|
2393
|
+
return null;
|
|
2394
|
+
validateRunLogId(record2.run_id);
|
|
2395
|
+
validateRunLogId(record2.session_id);
|
|
2396
|
+
return record2;
|
|
2397
|
+
}
|
|
2398
|
+
return null;
|
|
2399
|
+
}
|
|
2400
|
+
async function inspectCandidate(root, datePath, name, diagnostic) {
|
|
2401
|
+
const compressed = name.endsWith(".jsonl.gz");
|
|
2402
|
+
const file = path10.join(root, datePath, name);
|
|
2403
|
+
try {
|
|
2404
|
+
const stat = await fs9.lstat(file);
|
|
2405
|
+
if (!stat.isFile()) return void 0;
|
|
2406
|
+
const header = await readHeader2(file);
|
|
2407
|
+
if (!header || name !== `${header.run_id}.jsonl${compressed ? ".gz" : ""}` || compressed && header.meta?.codelia_log_archive_version === RUN_LOG_ARCHIVE_VERSION)
|
|
2408
|
+
return void 0;
|
|
2409
|
+
return {
|
|
2410
|
+
file,
|
|
2411
|
+
runId: header.run_id,
|
|
2412
|
+
sessionId: header.session_id,
|
|
2413
|
+
datePath,
|
|
2414
|
+
mtimeMs: stat.mtimeMs,
|
|
2415
|
+
size: stat.size,
|
|
2416
|
+
ino: stat.ino,
|
|
2417
|
+
dev: stat.dev,
|
|
2418
|
+
diagnostic,
|
|
2419
|
+
compressed,
|
|
2420
|
+
model: header.model ? { provider: header.model.provider, name: header.model.name } : void 0
|
|
2421
|
+
};
|
|
2422
|
+
} catch {
|
|
2423
|
+
return void 0;
|
|
2424
|
+
}
|
|
2425
|
+
}
|
|
2426
|
+
async function collectRunLogCandidates(root, diagnostic = false) {
|
|
2427
|
+
if (!await isRegularDirectory(root)) return [];
|
|
2428
|
+
const candidates = [];
|
|
2429
|
+
for (const year of await fs9.readdir(root, { withFileTypes: true })) {
|
|
2430
|
+
if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
|
|
2431
|
+
for (const month of await fs9.readdir(path10.join(root, year.name), {
|
|
2432
|
+
withFileTypes: true
|
|
2433
|
+
})) {
|
|
2434
|
+
if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
|
|
2435
|
+
for (const day of await fs9.readdir(
|
|
2436
|
+
path10.join(root, year.name, month.name),
|
|
2437
|
+
{ withFileTypes: true }
|
|
2438
|
+
)) {
|
|
2439
|
+
if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
|
|
2440
|
+
const datePath = path10.join(year.name, month.name, day.name);
|
|
2441
|
+
const entries2 = await fs9.readdir(path10.join(root, datePath), {
|
|
2442
|
+
withFileTypes: true
|
|
2443
|
+
});
|
|
2444
|
+
const plain = new Set(
|
|
2445
|
+
entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl")).map((entry) => entry.name)
|
|
2446
|
+
);
|
|
2447
|
+
for (const entry of entries2) {
|
|
2448
|
+
const compressed = entry.name.endsWith(".jsonl.gz");
|
|
2449
|
+
if (!entry.isFile() || !entry.name.endsWith(".jsonl") && (diagnostic || !compressed))
|
|
2450
|
+
continue;
|
|
2451
|
+
if (compressed && plain.has(entry.name.slice(0, -3))) continue;
|
|
2452
|
+
const candidate = await inspectCandidate(
|
|
2453
|
+
root,
|
|
2454
|
+
datePath,
|
|
2455
|
+
entry.name,
|
|
2456
|
+
diagnostic
|
|
2457
|
+
);
|
|
2458
|
+
if (candidate) candidates.push(candidate);
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
return candidates;
|
|
2464
|
+
}
|
|
2465
|
+
async function collectRunLogCandidatesAt(root, relPaths, diagnostic = false) {
|
|
2466
|
+
if (!await isRegularDirectory(root)) return [];
|
|
2467
|
+
const candidates = [];
|
|
2468
|
+
for (const relPath of relPaths) {
|
|
2469
|
+
const parts = relPath.split("/");
|
|
2470
|
+
const name = parts.pop();
|
|
2471
|
+
if (!name?.endsWith(".jsonl") || parts.length !== 3 || !/^\d{4}$/.test(parts[0] ?? "") || !/^\d{2}$/.test(parts[1] ?? "") || !/^\d{2}$/.test(parts[2] ?? "") || name.includes("\\"))
|
|
2472
|
+
continue;
|
|
2473
|
+
const datePath = path10.join(...parts);
|
|
2474
|
+
let selected = name;
|
|
2475
|
+
try {
|
|
2476
|
+
await fs9.lstat(path10.join(root, datePath, name));
|
|
2477
|
+
} catch {
|
|
2478
|
+
if (diagnostic) continue;
|
|
2479
|
+
selected = `${name}.gz`;
|
|
2480
|
+
}
|
|
2481
|
+
const candidate = await inspectCandidate(
|
|
2482
|
+
root,
|
|
2483
|
+
datePath,
|
|
2484
|
+
selected,
|
|
2485
|
+
diagnostic
|
|
2486
|
+
);
|
|
2487
|
+
if (candidate) candidates.push(candidate);
|
|
2488
|
+
}
|
|
2489
|
+
return candidates;
|
|
2490
|
+
}
|
|
2491
|
+
async function removeReusedProcessMarkers(paths, sessionId, identify = (pid) => getProcessIdentity(pid, { canonicalEnvironment: true })) {
|
|
2492
|
+
const directory2 = activeRunDirectory(paths, sessionId);
|
|
2493
|
+
let entries2;
|
|
2494
|
+
try {
|
|
2495
|
+
entries2 = readdirSync(directory2);
|
|
2496
|
+
} catch {
|
|
2497
|
+
return;
|
|
2498
|
+
}
|
|
2499
|
+
for (const entry of entries2) {
|
|
2500
|
+
const file = path10.join(directory2, entry);
|
|
2501
|
+
try {
|
|
2502
|
+
const before = lstatSync3(file);
|
|
2503
|
+
if (!before.isFile() || before.size > MAX_ACTIVE_RUN_MARKER_BYTES)
|
|
2504
|
+
continue;
|
|
2505
|
+
const contents = readFileSync2(file, "utf8");
|
|
2506
|
+
const { pid, identity } = JSON.parse(contents);
|
|
2507
|
+
if (!Number.isSafeInteger(pid) || pid < 1 || typeof identity !== "string" || !identity)
|
|
2508
|
+
continue;
|
|
2509
|
+
const current = await identify(pid);
|
|
2510
|
+
if (!current || current === identity) continue;
|
|
2511
|
+
const after = lstatSync3(file);
|
|
2512
|
+
if (after.isFile() && after.ino === before.ino && after.dev === before.dev && after.size === before.size && after.mtimeMs === before.mtimeMs && readFileSync2(file, "utf8") === contents)
|
|
2513
|
+
unlinkSync2(file);
|
|
2514
|
+
} catch {
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
}
|
|
2518
|
+
function hasActiveRunWriter(paths, sessionId) {
|
|
2519
|
+
try {
|
|
2520
|
+
const directory2 = activeRunDirectory(paths, sessionId);
|
|
2521
|
+
for (const entry of readdirSync(directory2, { withFileTypes: true })) {
|
|
2522
|
+
if (!entry.isFile()) return true;
|
|
2523
|
+
try {
|
|
2524
|
+
const file = path10.join(directory2, entry.name);
|
|
2525
|
+
if (lstatSync3(file).size > MAX_ACTIVE_RUN_MARKER_BYTES) return true;
|
|
2526
|
+
const { pid } = JSON.parse(readFileSync2(file, "utf8"));
|
|
2527
|
+
if (!Number.isSafeInteger(pid) || pid < 1) return true;
|
|
2528
|
+
try {
|
|
2529
|
+
process.kill(pid, 0);
|
|
2530
|
+
return true;
|
|
2531
|
+
} catch (error) {
|
|
2532
|
+
if (error.code !== "ESRCH") return true;
|
|
2533
|
+
}
|
|
2534
|
+
} catch {
|
|
2535
|
+
return true;
|
|
2536
|
+
}
|
|
2537
|
+
}
|
|
2538
|
+
return false;
|
|
2539
|
+
} catch (error) {
|
|
2540
|
+
return error.code !== "ENOENT";
|
|
2541
|
+
}
|
|
2542
|
+
}
|
|
2543
|
+
|
|
2544
|
+
// src/run-log-usage.ts
|
|
2545
|
+
import { promises as fs10 } from "fs";
|
|
2546
|
+
import path11 from "path";
|
|
2547
|
+
|
|
2548
|
+
// src/run-log-request-model.ts
|
|
2549
|
+
var TOKENS = /["\\{}[\]:,]/g;
|
|
2550
|
+
var MAX_KEY_BYTES = 256;
|
|
2551
|
+
var MAX_MODEL_BYTES = 64 * 1024;
|
|
2552
|
+
var RunLogRequestModel = class {
|
|
2553
|
+
depth = 0;
|
|
2554
|
+
inString = false;
|
|
2555
|
+
escapeAt = -2;
|
|
2556
|
+
offset = 0;
|
|
2557
|
+
complete = false;
|
|
2558
|
+
key;
|
|
2559
|
+
inValue = false;
|
|
2560
|
+
capture;
|
|
2561
|
+
parts = [];
|
|
2562
|
+
bytes = 0;
|
|
2563
|
+
fields = {};
|
|
2564
|
+
push(data) {
|
|
2565
|
+
if (this.complete) {
|
|
2566
|
+
if (data.toString("utf8").trim())
|
|
2567
|
+
throw new Error("Extra request record data");
|
|
2568
|
+
return;
|
|
2569
|
+
}
|
|
2570
|
+
let captureStart = this.capture ? 0 : void 0;
|
|
2571
|
+
const append = (end) => {
|
|
2572
|
+
if (captureStart === void 0 || end <= captureStart) return;
|
|
2573
|
+
this.bytes += end - captureStart;
|
|
2574
|
+
if (this.bytes > (this.capture === "key" ? MAX_KEY_BYTES : MAX_MODEL_BYTES))
|
|
2575
|
+
throw new Error("Request accounting metadata is too large");
|
|
2576
|
+
this.parts.push(data.subarray(captureStart, end));
|
|
2577
|
+
};
|
|
2578
|
+
const finish = (end) => {
|
|
2579
|
+
append(end);
|
|
2580
|
+
const value = JSON.parse(
|
|
2581
|
+
Buffer.concat(this.parts, this.bytes).toString("utf8")
|
|
2582
|
+
);
|
|
2583
|
+
this.capture = void 0;
|
|
2584
|
+
this.parts = [];
|
|
2585
|
+
this.bytes = 0;
|
|
2586
|
+
captureStart = void 0;
|
|
2587
|
+
return value;
|
|
2588
|
+
};
|
|
2589
|
+
const finishValue = (end) => {
|
|
2590
|
+
if (this.capture === "value" && this.key !== void 0)
|
|
2591
|
+
this.fields[this.key] = finish(end);
|
|
2592
|
+
this.key = void 0;
|
|
2593
|
+
this.inValue = false;
|
|
2594
|
+
};
|
|
2595
|
+
const text = data.toString("latin1");
|
|
2596
|
+
const tokens = new RegExp(TOKENS);
|
|
2597
|
+
for (let match = tokens.exec(text); match; match = tokens.exec(text)) {
|
|
2598
|
+
const index = match.index;
|
|
2599
|
+
const token = match[0];
|
|
2600
|
+
const absolute = this.offset + index;
|
|
2601
|
+
if (this.inString) {
|
|
2602
|
+
if (absolute === this.escapeAt + 1) {
|
|
2603
|
+
this.escapeAt = -2;
|
|
2604
|
+
continue;
|
|
2605
|
+
}
|
|
2606
|
+
if (token === "\\") {
|
|
2607
|
+
this.escapeAt = absolute;
|
|
2608
|
+
continue;
|
|
2609
|
+
}
|
|
2610
|
+
if (token !== '"') continue;
|
|
2611
|
+
this.inString = false;
|
|
2612
|
+
if (this.capture === "key") this.key = finish(index + 1);
|
|
2613
|
+
continue;
|
|
2614
|
+
}
|
|
2615
|
+
if (token === '"') {
|
|
2616
|
+
this.inString = true;
|
|
2617
|
+
if (this.depth === 1 && !this.inValue && this.key === void 0) {
|
|
2618
|
+
this.capture = "key";
|
|
2619
|
+
captureStart = index;
|
|
2620
|
+
}
|
|
2621
|
+
} else if (token === "{" || token === "[") this.depth++;
|
|
2622
|
+
else if (token === "}" || token === "]") {
|
|
2623
|
+
if (this.depth === 1) finishValue(index);
|
|
2624
|
+
this.depth--;
|
|
2625
|
+
if (this.depth === 0) {
|
|
2626
|
+
this.complete = true;
|
|
2627
|
+
if (data.subarray(index + 1).toString("utf8").trim())
|
|
2628
|
+
throw new Error("Extra request record data");
|
|
2629
|
+
break;
|
|
2630
|
+
}
|
|
2631
|
+
} else if (token === ":" && this.depth === 1 && !this.inValue) {
|
|
2632
|
+
this.inValue = true;
|
|
2633
|
+
if (this.key === "seq" || this.key === "model") {
|
|
2634
|
+
this.capture = "value";
|
|
2635
|
+
captureStart = index + 1;
|
|
2636
|
+
}
|
|
2637
|
+
} else if (token === "," && this.depth === 1) finishValue(index);
|
|
2638
|
+
}
|
|
2639
|
+
append(data.length);
|
|
2640
|
+
this.offset += data.length;
|
|
2641
|
+
}
|
|
2642
|
+
finish() {
|
|
2643
|
+
if (!this.complete || this.inString || this.capture)
|
|
2644
|
+
throw new Error("Incomplete request accounting metadata");
|
|
2645
|
+
const { seq, model } = this.fields;
|
|
2646
|
+
if (seq === void 0 && model === void 0) return void 0;
|
|
2647
|
+
if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 1)
|
|
2648
|
+
throw new Error("Invalid request accounting sequence");
|
|
2649
|
+
if (model === void 0 || model === null) return { seq };
|
|
2650
|
+
if (typeof model !== "object" || Array.isArray(model))
|
|
2651
|
+
throw new Error("Invalid request accounting model");
|
|
2652
|
+
const { provider, name } = model;
|
|
2653
|
+
if (provider !== void 0 && typeof provider !== "string" || name !== void 0 && typeof name !== "string")
|
|
2654
|
+
throw new Error("Invalid request accounting identity");
|
|
2655
|
+
return { seq, model: { provider, name } };
|
|
2656
|
+
}
|
|
2657
|
+
};
|
|
2658
|
+
|
|
2659
|
+
// src/run-log-usage.ts
|
|
2660
|
+
var MAX_USAGE_LINE_BYTES = 16 * 1024 * 1024;
|
|
2661
|
+
async function* readUsageRecords(file) {
|
|
2662
|
+
let parts = [];
|
|
2663
|
+
let length = 0;
|
|
2664
|
+
let request;
|
|
2665
|
+
for await (const part of readRunLogRecordParts(file)) {
|
|
2666
|
+
if (part.type === "llm.request") {
|
|
2667
|
+
if (part.start) request = new RunLogRequestModel();
|
|
2668
|
+
request?.push(part.data);
|
|
2669
|
+
if (part.end) {
|
|
2670
|
+
const identity = request?.finish();
|
|
2671
|
+
if (identity) yield { type: "request-identity", ...identity };
|
|
2672
|
+
request = void 0;
|
|
2673
|
+
}
|
|
2674
|
+
continue;
|
|
2675
|
+
}
|
|
2676
|
+
if (part.type !== "llm.usage" && part.type !== "llm.response") continue;
|
|
2677
|
+
length += part.data.length;
|
|
2678
|
+
if (length > MAX_USAGE_LINE_BYTES)
|
|
2679
|
+
throw new Error("Usage record is too large to migrate safely");
|
|
2680
|
+
parts.push(part.data);
|
|
2681
|
+
if (part.end) {
|
|
2682
|
+
yield JSON.parse(Buffer.concat(parts, length).toString("utf8"));
|
|
2683
|
+
parts = [];
|
|
2684
|
+
length = 0;
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
async function preserveRunUsage(paths, source) {
|
|
2689
|
+
const destination = usageLogPath(paths, source.datePath, source.runId);
|
|
2690
|
+
const records = /* @__PURE__ */ new Map();
|
|
2691
|
+
const requestModels = /* @__PURE__ */ new Map();
|
|
2692
|
+
try {
|
|
2693
|
+
const stat = await fs10.lstat(destination);
|
|
2694
|
+
if (!stat.isFile()) throw new Error("Invalid usage log");
|
|
2695
|
+
for await (const record2 of readUsageRecords(destination))
|
|
2696
|
+
if (record2.type === "llm.usage")
|
|
2697
|
+
records.set(
|
|
2698
|
+
record2.seq,
|
|
2699
|
+
toUsageRecord(record2, source.sessionId, record2.model)
|
|
2700
|
+
);
|
|
2701
|
+
} catch (error) {
|
|
2702
|
+
if (error.code !== "ENOENT") throw error;
|
|
2703
|
+
}
|
|
2704
|
+
for await (const record2 of readUsageRecords(source.file)) {
|
|
2705
|
+
if (record2.type === "request-identity") {
|
|
2706
|
+
requestModels.set(record2.seq, record2.model);
|
|
2707
|
+
const known = records.get(record2.seq);
|
|
2708
|
+
if (known)
|
|
2709
|
+
records.set(
|
|
2710
|
+
record2.seq,
|
|
2711
|
+
toUsageRecord(known, source.sessionId, {
|
|
2712
|
+
provider: known.model?.provider ?? record2.model?.provider,
|
|
2713
|
+
name: known.model?.name ?? record2.model?.name
|
|
2714
|
+
})
|
|
2715
|
+
);
|
|
2716
|
+
continue;
|
|
2717
|
+
}
|
|
2718
|
+
if (record2.run_id !== source.runId || !Number.isSafeInteger(record2.seq) || record2.seq < 1)
|
|
2719
|
+
throw new Error("Mismatched usage run");
|
|
2720
|
+
if (record2.type === "llm.response" && records.has(record2.seq)) continue;
|
|
2721
|
+
const usage = toUsageRecord(record2, source.sessionId, {
|
|
2722
|
+
provider: records.get(record2.seq)?.model?.provider ?? (record2.type === "llm.usage" ? record2.model?.provider : void 0) ?? requestModels.get(record2.seq)?.provider,
|
|
2723
|
+
name: records.get(record2.seq)?.model?.name ?? (record2.type === "llm.usage" ? record2.model?.name : void 0) ?? requestModels.get(record2.seq)?.name
|
|
2724
|
+
});
|
|
2725
|
+
records.set(usage.seq, usage);
|
|
2726
|
+
}
|
|
2727
|
+
if (records.size === 0) return [];
|
|
2728
|
+
const ordered = [...records.values()].sort((a, b) => a.seq - b.seq).map(
|
|
2729
|
+
(record2) => toUsageRecord(record2, source.sessionId, {
|
|
2730
|
+
provider: record2.model?.provider ?? source.model?.provider,
|
|
2731
|
+
name: record2.model?.name ?? source.model?.name
|
|
2732
|
+
})
|
|
2733
|
+
);
|
|
2734
|
+
await fs10.mkdir(path11.dirname(destination), { recursive: true });
|
|
2735
|
+
const temporary = `${destination}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
2736
|
+
try {
|
|
2737
|
+
const lines = ordered.map((record2) => JSON.stringify(record2)).join("\n");
|
|
2738
|
+
await fs10.writeFile(temporary, `${lines}
|
|
2739
|
+
`, { mode: 384 });
|
|
2740
|
+
await fs10.rename(temporary, destination);
|
|
2741
|
+
} finally {
|
|
2742
|
+
await fs10.rm(temporary, { force: true });
|
|
2743
|
+
}
|
|
2744
|
+
return ordered;
|
|
2745
|
+
}
|
|
2746
|
+
|
|
2747
|
+
// src/run-log-retention.ts
|
|
2748
|
+
var RUN_LOG_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
2749
|
+
var eligible = (summary, newestMtime, now) => {
|
|
2750
|
+
if (!summary || summary.pinned) return false;
|
|
2751
|
+
const updatedAt = Date.parse(summary.updated_at);
|
|
2752
|
+
if (!Number.isFinite(updatedAt)) return false;
|
|
2753
|
+
return Boolean(summary.archived_at) || now - newestMtime >= RUN_LOG_RETENTION_MS;
|
|
2754
|
+
};
|
|
2755
|
+
function commitCandidate(candidate, compressed, result) {
|
|
2756
|
+
try {
|
|
2757
|
+
const stat = lstatSync4(candidate.file);
|
|
2758
|
+
if (!stat.isFile() || stat.ino !== candidate.ino || stat.dev !== candidate.dev || stat.size !== candidate.size || stat.mtimeMs !== candidate.mtimeMs) {
|
|
2759
|
+
result.skipped++;
|
|
2760
|
+
return;
|
|
2761
|
+
}
|
|
2762
|
+
if (compressed) {
|
|
2763
|
+
const target = candidate.compressed ? candidate.file : `${candidate.file}.gz`;
|
|
2764
|
+
if (candidate.compressed) renameSync2(compressed.temporary, target);
|
|
2765
|
+
else linkSync(compressed.temporary, target);
|
|
2766
|
+
utimesSync(target, stat.atime, stat.mtime);
|
|
2767
|
+
if (!candidate.compressed) unlinkSync3(candidate.file);
|
|
2768
|
+
result.compressed++;
|
|
2769
|
+
result.reclaimed_bytes += Math.max(0, stat.size - compressed.size);
|
|
2770
|
+
} else {
|
|
2771
|
+
unlinkSync3(candidate.file);
|
|
2772
|
+
result.deleted++;
|
|
2773
|
+
result.reclaimed_bytes += stat.size;
|
|
2774
|
+
}
|
|
2775
|
+
} catch (error) {
|
|
2776
|
+
if (error.code !== "ENOENT") result.failed++;
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
async function processCandidate(context, candidate, newestMtime, usage) {
|
|
2780
|
+
const { paths, sessions, now, result } = context;
|
|
2781
|
+
let compressed;
|
|
2782
|
+
try {
|
|
2783
|
+
if (!candidate.diagnostic)
|
|
2784
|
+
compressed = await prepareCompressedLog(candidate.file, usage);
|
|
2785
|
+
await sessions.withRetentionGuard(candidate.sessionId, (summary) => {
|
|
2786
|
+
if (hasActiveRunWriter(paths, candidate.sessionId) || !eligible(summary, newestMtime, now)) {
|
|
2787
|
+
result.skipped++;
|
|
2788
|
+
return;
|
|
2789
|
+
}
|
|
2790
|
+
commitCandidate(candidate, compressed, result);
|
|
2791
|
+
});
|
|
2792
|
+
} catch {
|
|
2793
|
+
result.failed++;
|
|
2794
|
+
} finally {
|
|
2795
|
+
if (compressed) await fs11.rm(compressed.temporary, { force: true });
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
async function cleanupRunLogs(options) {
|
|
2799
|
+
const { paths, sessions } = options;
|
|
2800
|
+
const now = options.now ?? Date.now();
|
|
2801
|
+
const result = {
|
|
2802
|
+
deleted: 0,
|
|
2803
|
+
compressed: 0,
|
|
2804
|
+
skipped: 0,
|
|
2805
|
+
failed: 0,
|
|
2806
|
+
reclaimed_bytes: 0
|
|
2807
|
+
};
|
|
2808
|
+
const context = { paths, sessions, now, result };
|
|
2809
|
+
if (!await isRegularDirectory(paths.sessionsDir)) return result;
|
|
2810
|
+
const diagnosticsDir = path12.join(paths.sessionsDir, "diagnostics");
|
|
2811
|
+
let relPaths;
|
|
2812
|
+
if (options.sessionId) {
|
|
2813
|
+
try {
|
|
2814
|
+
relPaths = (await sessions.listSessionRuns(options.sessionId)).map(
|
|
2815
|
+
(entry) => entry.rel_path
|
|
2816
|
+
);
|
|
2817
|
+
} catch {
|
|
2818
|
+
relPaths = void 0;
|
|
2819
|
+
}
|
|
2820
|
+
}
|
|
2821
|
+
const candidates = relPaths ? [
|
|
2822
|
+
...await collectRunLogCandidatesAt(paths.sessionsDir, relPaths),
|
|
2823
|
+
...await collectRunLogCandidatesAt(diagnosticsDir, relPaths, true)
|
|
2824
|
+
] : [
|
|
2825
|
+
...await collectRunLogCandidates(paths.sessionsDir),
|
|
2826
|
+
...await collectRunLogCandidates(diagnosticsDir, true)
|
|
2827
|
+
];
|
|
2828
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2829
|
+
for (const candidate of candidates) {
|
|
2830
|
+
if (options.sessionId && candidate.sessionId !== options.sessionId)
|
|
2831
|
+
continue;
|
|
2832
|
+
const group = groups.get(candidate.sessionId) ?? [];
|
|
2833
|
+
group.push(candidate);
|
|
2834
|
+
groups.set(candidate.sessionId, group);
|
|
2835
|
+
}
|
|
2836
|
+
for (const [sessionId, group] of groups) {
|
|
2837
|
+
await removeReusedProcessMarkers(paths, sessionId);
|
|
2838
|
+
if (hasActiveRunWriter(paths, sessionId)) {
|
|
2839
|
+
result.skipped += group.length;
|
|
2840
|
+
continue;
|
|
2841
|
+
}
|
|
2842
|
+
const summary = await sessions.getSummary(sessionId);
|
|
2843
|
+
const runMtimes = /* @__PURE__ */ new Map();
|
|
2844
|
+
for (const candidate of group)
|
|
2845
|
+
runMtimes.set(
|
|
2846
|
+
candidate.runId,
|
|
2847
|
+
Math.max(runMtimes.get(candidate.runId) ?? 0, candidate.mtimeMs)
|
|
2848
|
+
);
|
|
2849
|
+
const selected = group.filter(
|
|
2850
|
+
(candidate) => eligible(
|
|
2851
|
+
summary,
|
|
2852
|
+
runMtimes.get(candidate.runId) ?? candidate.mtimeMs,
|
|
2853
|
+
now
|
|
2854
|
+
)
|
|
2855
|
+
);
|
|
2856
|
+
result.skipped += group.length - selected.length;
|
|
2857
|
+
if (selected.length === 0) continue;
|
|
2858
|
+
try {
|
|
2859
|
+
const snapshot = await fs11.lstat(
|
|
2860
|
+
path12.join(paths.sessionsDir, "messages", `${sessionId}.jsonl`)
|
|
2861
|
+
);
|
|
2862
|
+
if (!snapshot.isFile() || snapshot.size === 0) {
|
|
2863
|
+
result.skipped += selected.length;
|
|
2864
|
+
continue;
|
|
2865
|
+
}
|
|
2866
|
+
const usageByRun = /* @__PURE__ */ new Map();
|
|
2867
|
+
for (const candidate of selected)
|
|
2868
|
+
usageByRun.set(
|
|
2869
|
+
candidate.runId,
|
|
2870
|
+
await preserveRunUsage(paths, candidate)
|
|
2871
|
+
);
|
|
2872
|
+
for (const candidate of selected)
|
|
2873
|
+
await processCandidate(
|
|
2874
|
+
context,
|
|
2875
|
+
candidate,
|
|
2876
|
+
runMtimes.get(candidate.runId) ?? candidate.mtimeMs,
|
|
2877
|
+
usageByRun.get(candidate.runId) ?? []
|
|
2878
|
+
);
|
|
2879
|
+
} catch (error) {
|
|
2880
|
+
if (error.code === "ENOENT")
|
|
2881
|
+
result.skipped += selected.length;
|
|
2882
|
+
else result.failed += selected.length;
|
|
2883
|
+
}
|
|
2884
|
+
}
|
|
2885
|
+
return result;
|
|
2886
|
+
}
|
|
2887
|
+
|
|
2888
|
+
// src/service.ts
|
|
2889
|
+
var StoragePathServiceImpl = class {
|
|
2890
|
+
resolvePaths(options = {}) {
|
|
2891
|
+
return resolveStoragePaths(options);
|
|
2892
|
+
}
|
|
2893
|
+
};
|
|
2894
|
+
|
|
1168
2895
|
// src/task-registry.ts
|
|
1169
|
-
import { promises as
|
|
1170
|
-
import
|
|
2896
|
+
import { promises as fs12 } from "fs";
|
|
2897
|
+
import path13 from "path";
|
|
1171
2898
|
var TASKS_DIRNAME = "tasks";
|
|
1172
2899
|
var sortByUpdatedDesc = (tasks) => [...tasks].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
|
|
1173
2900
|
var toShellKeyBase = (label2) => {
|
|
@@ -1225,14 +2952,14 @@ var assignMissingShellKeys = (tasks) => {
|
|
|
1225
2952
|
return updates;
|
|
1226
2953
|
};
|
|
1227
2954
|
var atomicWrite = async (filePath, payload) => {
|
|
1228
|
-
const dir =
|
|
1229
|
-
const base =
|
|
1230
|
-
const tmp =
|
|
2955
|
+
const dir = path13.dirname(filePath);
|
|
2956
|
+
const base = path13.basename(filePath);
|
|
2957
|
+
const tmp = path13.join(
|
|
1231
2958
|
dir,
|
|
1232
2959
|
`${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
|
|
1233
2960
|
);
|
|
1234
|
-
await
|
|
1235
|
-
await
|
|
2961
|
+
await fs12.writeFile(tmp, payload, "utf8");
|
|
2962
|
+
await fs12.rename(tmp, filePath);
|
|
1236
2963
|
};
|
|
1237
2964
|
var isTaskState = (value) => value === "queued" || value === "running" || value === "completed" || value === "failed" || value === "cancelled";
|
|
1238
2965
|
var isTaskKind = (value) => value === "shell" || value === "subagent";
|
|
@@ -1343,7 +3070,7 @@ var normalizeTaskRecord = (value) => {
|
|
|
1343
3070
|
};
|
|
1344
3071
|
var readTaskFile = async (filePath) => {
|
|
1345
3072
|
try {
|
|
1346
|
-
const raw = await
|
|
3073
|
+
const raw = await fs12.readFile(filePath, "utf8");
|
|
1347
3074
|
return normalizeTaskRecord(JSON.parse(raw));
|
|
1348
3075
|
} catch {
|
|
1349
3076
|
return null;
|
|
@@ -1358,19 +3085,19 @@ var TaskRegistryStore = class {
|
|
|
1358
3085
|
return;
|
|
1359
3086
|
}
|
|
1360
3087
|
const root = resolveStoragePaths().root;
|
|
1361
|
-
this.tasksDir =
|
|
3088
|
+
this.tasksDir = path13.join(root, TASKS_DIRNAME);
|
|
1362
3089
|
}
|
|
1363
3090
|
async ensureDir() {
|
|
1364
|
-
await
|
|
3091
|
+
await fs12.mkdir(this.tasksDir, { recursive: true });
|
|
1365
3092
|
}
|
|
1366
3093
|
taskPath(taskId) {
|
|
1367
|
-
return
|
|
3094
|
+
return path13.join(this.tasksDir, taskFileName(taskId));
|
|
1368
3095
|
}
|
|
1369
3096
|
async list() {
|
|
1370
3097
|
await this.ensureDir();
|
|
1371
|
-
const
|
|
3098
|
+
const entries2 = await fs12.readdir(this.tasksDir, { withFileTypes: true });
|
|
1372
3099
|
const tasks = (await Promise.all(
|
|
1373
|
-
|
|
3100
|
+
entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(path13.join(this.tasksDir, entry.name)))
|
|
1374
3101
|
)).filter((task) => task !== null);
|
|
1375
3102
|
const keyBackfills = assignMissingShellKeys(tasks);
|
|
1376
3103
|
if (keyBackfills.length > 0) {
|
|
@@ -1412,8 +3139,8 @@ var TaskRegistryStore = class {
|
|
|
1412
3139
|
};
|
|
1413
3140
|
|
|
1414
3141
|
// src/tool-output-cache.ts
|
|
1415
|
-
import { promises as
|
|
1416
|
-
import
|
|
3142
|
+
import { promises as fs13 } from "fs";
|
|
3143
|
+
import path14 from "path";
|
|
1417
3144
|
var DEFAULT_MAX_MATCHES = 50;
|
|
1418
3145
|
var DEFAULT_MAX_LINE_LENGTH = 1e3;
|
|
1419
3146
|
var DEFAULT_MAX_READ_BYTES = 64 * 1024;
|
|
@@ -1525,15 +3252,15 @@ var ToolOutputCacheStoreImpl = class {
|
|
|
1525
3252
|
async save(record2) {
|
|
1526
3253
|
const refId = normalizeRefId(record2.tool_call_id);
|
|
1527
3254
|
const filePath = this.resolvePath(refId);
|
|
1528
|
-
await
|
|
1529
|
-
await
|
|
3255
|
+
await fs13.mkdir(this.baseDir, { recursive: true });
|
|
3256
|
+
await fs13.writeFile(filePath, record2.content, "utf8");
|
|
1530
3257
|
const byteSize = Buffer.byteLength(record2.content, "utf8");
|
|
1531
3258
|
const lineCount = record2.content.split(/\r?\n/).length;
|
|
1532
3259
|
return { id: refId, byte_size: byteSize, line_count: lineCount };
|
|
1533
3260
|
}
|
|
1534
3261
|
async read(refId, options = {}) {
|
|
1535
3262
|
const filePath = this.resolvePath(refId);
|
|
1536
|
-
const content = await
|
|
3263
|
+
const content = await fs13.readFile(filePath, "utf8");
|
|
1537
3264
|
const lines = content.split(/\r?\n/);
|
|
1538
3265
|
const offset = options.offset ?? 0;
|
|
1539
3266
|
const limit = options.limit ?? lines.length;
|
|
@@ -1592,7 +3319,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
|
|
|
1592
3319
|
}
|
|
1593
3320
|
async readTail(refId, options) {
|
|
1594
3321
|
const filePath = this.resolvePath(refId);
|
|
1595
|
-
const content = await
|
|
3322
|
+
const content = await fs13.readFile(filePath, "utf8");
|
|
1596
3323
|
const lines = content.split(/\r?\n/);
|
|
1597
3324
|
const tailLines = Math.max(1, Math.trunc(options.tail_lines));
|
|
1598
3325
|
const start = Math.max(0, lines.length - tailLines);
|
|
@@ -1604,7 +3331,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
|
|
|
1604
3331
|
}
|
|
1605
3332
|
async readLine(refId, options) {
|
|
1606
3333
|
const filePath = this.resolvePath(refId);
|
|
1607
|
-
const content = await
|
|
3334
|
+
const content = await fs13.readFile(filePath, "utf8");
|
|
1608
3335
|
const lines = content.split(/\r?\n/);
|
|
1609
3336
|
const lineIndex = options.line_number - 1;
|
|
1610
3337
|
if (lineIndex < 0 || lineIndex >= lines.length) {
|
|
@@ -1645,7 +3372,7 @@ tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${opti
|
|
|
1645
3372
|
}
|
|
1646
3373
|
async grep(refId, options) {
|
|
1647
3374
|
const filePath = this.resolvePath(refId);
|
|
1648
|
-
const content = await
|
|
3375
|
+
const content = await fs13.readFile(filePath, "utf8");
|
|
1649
3376
|
const lines = content.split(/\r?\n/);
|
|
1650
3377
|
const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
1651
3378
|
const before = Math.max(0, options.before ?? 0);
|
|
@@ -1696,21 +3423,33 @@ ${snippet}`;
|
|
|
1696
3423
|
return output;
|
|
1697
3424
|
}
|
|
1698
3425
|
resolvePath(refId) {
|
|
1699
|
-
return
|
|
3426
|
+
return path14.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
|
|
1700
3427
|
}
|
|
1701
3428
|
};
|
|
1702
3429
|
export {
|
|
3430
|
+
FileAttachmentStore,
|
|
1703
3431
|
IMAGE_MAX_BYTES,
|
|
1704
3432
|
ImageArtifactStore,
|
|
1705
3433
|
McpAuthStore,
|
|
1706
3434
|
ProjectsPolicyStore,
|
|
3435
|
+
RUN_LOG_RETENTION_MS,
|
|
1707
3436
|
RunEventStoreFactoryImpl,
|
|
1708
3437
|
SessionStateStoreImpl,
|
|
1709
3438
|
SessionStoreWriterImpl,
|
|
1710
3439
|
StoragePathServiceImpl,
|
|
1711
3440
|
TaskRegistryStore,
|
|
1712
3441
|
ToolOutputCacheStoreImpl,
|
|
3442
|
+
cleanupRunLogs,
|
|
3443
|
+
createAttachmentId,
|
|
3444
|
+
detectImageAttachmentType,
|
|
1713
3445
|
ensureStorageDirs,
|
|
3446
|
+
getProcessIdentity,
|
|
3447
|
+
isAttachmentId,
|
|
3448
|
+
readRunLogLines,
|
|
3449
|
+
resolveIndexedRunLog,
|
|
3450
|
+
resolveRunLogPath,
|
|
1714
3451
|
resolveStoragePaths,
|
|
3452
|
+
scanSessionRunLogs,
|
|
3453
|
+
validateImageAttachment,
|
|
1715
3454
|
validateImagePng
|
|
1716
3455
|
};
|