@codelia/storage 0.1.83 → 0.1.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -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 randomUUID2 } from "crypto";
3
- import { lstat as lstat2, mkdir as mkdir2, rename as rename2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
4
- import path2 from "path";
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 = 8 * 1024 * 1024;
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, <=8 MiB, <=4096 per side and <=16 MP."
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 > 4096 || height > 4096 || width * height > 16e6 || !channels || payload[8] !== 8 || payload[10] !== 0 || payload[11] !== 0 || payload[12] !== 0)
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
- const signatures = {
93
- "image/png": bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])),
94
- "image/jpeg": bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255,
95
- "image/webp": bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP",
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 > 4096 || height > 4096 || width * height > 16e6)
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 4096px/16 MP"
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 path from "path";
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) => path.join(root, VERSION);
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 lstat(dir)).isDirectory())
415
+ if (!(await lstat2(dir)).isDirectory())
226
416
  throw new Error("Invalid model view directory");
227
417
  const record2 = JSON.parse(
228
- (await readImageFileBounded(path.join(dir, "metadata.json"), 4096)).toString()
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
- path.join(dir, "view.jpg"),
237
- 8 * 1024 * 1024
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 lstat(directory(root));
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 pipeline = sharp(bytes, {
257
- limitInputPixels: 16e6,
446
+ const pipeline2 = sharp(bytes, {
447
+ limitInputPixels: 2e7,
258
448
  failOn: "warning"
259
449
  }).timeout({ seconds: 15 });
260
- const metadata = await pipeline.metadata();
261
- if ((metadata.pages ?? 1) > 1 || metadata.hasAlpha && !(await pipeline.clone().stats()).isOpaque)
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 pipeline.jpeg({ quality: 90, chromaSubsampling: "4:4:4" }).toBuffer();
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 = path.join(root, `.model-view-${randomUUID()}`);
272
- await mkdir(temporary, { mode: 448 });
461
+ const temporary = path2.join(root, `.model-view-${randomUUID2()}`);
462
+ await mkdir2(temporary, { mode: 448 });
273
463
  try {
274
- await writeFile(path.join(temporary, "view.jpg"), jpeg, {
464
+ await writeFile2(path2.join(temporary, "view.jpg"), jpeg, {
275
465
  flag: "wx",
276
466
  mode: 384
277
467
  });
278
- await writeFile(
279
- path.join(temporary, "metadata.json"),
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 rename(temporary, directory(root));
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 rm(temporary, { recursive: true, force: true });
481
+ await rm2(temporary, { recursive: true, force: true });
292
482
  }
293
483
  }
294
484
 
295
485
  // src/image-artifacts.ts
296
- var ID = /^codelia-image-[0-9a-f-]{36}$/;
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
- async save(bytes, provenance) {
303
- const dimensions = await validateImagePng(bytes);
304
- const artifact_id = `codelia-image-${randomUUID2()}`;
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: "image/png",
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: `codelia-image-${randomUUID2()}`,
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
- await this.persist(bytes, metadata);
331
- return metadata;
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
- async persist(bytes, metadata) {
334
- await mkdir2(this.root, { recursive: true, mode: 448 });
335
- const temporary = path2.join(this.root, `.pending-${randomUUID2()}`);
336
- await mkdir2(temporary, { mode: 448 });
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 writeFile2(
339
- path2.join(temporary, imageOriginalFilename(metadata.media_type)),
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 writeFile2(
347
- path2.join(temporary, "metadata.json"),
348
- JSON.stringify(metadata),
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 rename2(temporary, path2.join(this.root, metadata.artifact_id));
571
+ await rename3(temporary, path3.join(this.root, metadata.artifact_id));
352
572
  } catch (error) {
353
- await rm2(temporary, { recursive: true, force: true });
573
+ await rm3(temporary, { recursive: true, force: true });
354
574
  throw error;
355
575
  }
356
576
  }
357
- async read(artifactId) {
358
- if (!ID.test(artifactId)) throw new Error("Invalid image artifact id");
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 = path2.join(this.root, artifactId);
361
- if (!(await lstat2(dir)).isDirectory())
580
+ const dir = path3.join(this.root, artifactId);
581
+ if (!(await lstat3(dir)).isDirectory())
362
582
  throw new Error("Invalid artifact directory");
363
- const metadata = parseImageMetadata(
364
- JSON.parse(
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
- path2.join(dir, imageOriginalFilename(metadata.media_type)),
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
- path2.join(this.root, artifactId),
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
- path2.join(this.root, ref.artifact_id),
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 mkdir3 } from "fs/promises";
649
+ import { mkdir as mkdir4 } from "fs/promises";
426
650
  import os from "os";
427
- import path3 from "path";
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
- mkdir3(paths.configDir, { recursive: true }),
453
- mkdir3(paths.cacheDir, { recursive: true }),
454
- mkdir3(paths.toolOutputCacheDir, { recursive: true }),
455
- mkdir3(paths.sessionsDir, { recursive: true }),
456
- mkdir3(paths.logsDir, { recursive: true })
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 path3.join(os.homedir(), DEFAULT_ROOT_DIR);
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: path3.join(configDir, CONFIG_FILENAME),
472
- authFile: path3.join(configDir, AUTH_FILENAME),
473
- mcpAuthFile: path3.join(configDir, MCP_AUTH_FILENAME),
474
- projectsFile: path3.join(configDir, PROJECTS_FILENAME),
475
- cacheDir: path3.join(root, CACHE_DIRNAME),
476
- toolOutputCacheDir: path3.join(
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: path3.join(root, SESSIONS_DIRNAME),
482
- logsDir: path3.join(root, LOGS_DIRNAME)
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 ?? path3.join(home, ".config");
488
- const cacheRoot = process.env.XDG_CACHE_HOME ?? path3.join(home, ".cache");
489
- const stateRoot = process.env.XDG_STATE_HOME ?? path3.join(home, ".local", "state");
490
- const configDir = path3.join(configRoot, XDG_DIR_NAME);
491
- const cacheDir = path3.join(cacheRoot, XDG_DIR_NAME);
492
- const stateDir = path3.join(stateRoot, XDG_DIR_NAME);
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: path3.join(configDir, CONFIG_FILENAME),
497
- authFile: path3.join(configDir, AUTH_FILENAME),
498
- mcpAuthFile: path3.join(configDir, MCP_AUTH_FILENAME),
499
- projectsFile: path3.join(configDir, PROJECTS_FILENAME),
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: path3.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
502
- sessionsDir: path3.join(stateDir, SESSIONS_DIRNAME),
503
- logsDir: path3.join(stateDir, LOGS_DIRNAME)
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/projects-store.ts
793
+ // src/process-identity.ts
794
+ import { execFile } from "child_process";
570
795
  import { promises as fs2 } from "fs";
571
- import path4 from "path";
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 entries = {};
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
- entries[key] = {
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(entries).length > 0) {
623
- normalized.projects = entries;
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 = path4.dirname(filePath);
630
- const fileName = path4.basename(filePath);
631
- const tempPath = path4.join(
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 fs2.writeFile(tempPath, content, { mode: 384 });
636
- await fs2.rename(tempPath, filePath);
891
+ await fs3.writeFile(tempPath, content, { mode: 384 });
892
+ await fs3.rename(tempPath, filePath);
637
893
  if (process.platform !== "win32") {
638
- await fs2.chmod(filePath, 384);
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 fs2.readFile(this.paths.projectsFile, "utf8");
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 fs3 } from "fs";
674
- import path5 from "path";
675
- var pad2 = (value) => String(value).padStart(2, "0");
676
- var resolveDateParts = (startedAt) => {
677
- const parsed = new Date(startedAt);
678
- const date = Number.isNaN(parsed.getTime()) ? /* @__PURE__ */ new Date() : parsed;
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
- year: String(date.getUTCFullYear()),
681
- month: pad2(date.getUTCMonth() + 1),
682
- day: pad2(date.getUTCDate())
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
- ensureDir;
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
- const parts = resolveDateParts(options.startedAt);
692
- const baseDir = path5.join(
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
- parts.year,
695
- parts.month,
696
- parts.day
1175
+ datePath,
1176
+ `${this.runId}.jsonl`
697
1177
  );
698
- this.filePath = path5.join(baseDir, `${options.runId}.jsonl`);
699
- this.ensureDir = fs3.mkdir(baseDir, { recursive: true }).then(() => {
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
- let line;
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
- line = `${JSON.stringify(record2)}
1239
+ if (this.diagnosticFilePath) dump = `${JSON.stringify(record2)}
1240
+ `;
1241
+ const projected = this.projectNormalRecord(record2);
1242
+ if (projected) {
1243
+ normal = `${JSON.stringify(projected)}
706
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
- await this.ensureDir;
712
- await fs3.appendFile(this.filePath, line, "utf8");
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,267 @@ var SessionStoreWriterImpl = class {
717
1286
  }
718
1287
  };
719
1288
 
720
- // src/run-event-store.ts
721
- var RunEventStoreFactoryImpl = class {
722
- create(init) {
723
- return new SessionStoreWriterImpl({
724
- runId: init.runId,
725
- startedAt: init.startedAt
726
- });
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";
1304
+
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);
727
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;
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;
728
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
+ }
729
1465
 
730
- // src/service.ts
731
- var StoragePathServiceImpl = class {
732
- resolvePaths(options = {}) {
733
- return resolveStoragePaths(options);
1466
+ // src/session-goals.ts
1467
+ function initSessionGoals(db) {
1468
+ db.exec(`
1469
+ CREATE TABLE IF NOT EXISTS session_goals (
1470
+ session_id TEXT PRIMARY KEY,
1471
+ payload TEXT NOT NULL
1472
+ );
1473
+ CREATE TABLE IF NOT EXISTS goal_continuations (
1474
+ continuation_id TEXT PRIMARY KEY,
1475
+ session_id TEXT NOT NULL,
1476
+ goal_id TEXT NOT NULL,
1477
+ run_id TEXT NOT NULL
1478
+ );
1479
+ CREATE INDEX IF NOT EXISTS goal_continuations_session ON goal_continuations (session_id);
1480
+ `);
1481
+ }
1482
+ var SessionGoalStore = class {
1483
+ constructor(getDb) {
1484
+ this.getDb = getDb;
1485
+ }
1486
+ getDb;
1487
+ load(db, sessionId) {
1488
+ const row = db.get(
1489
+ "SELECT payload FROM session_goals WHERE session_id = ?",
1490
+ [sessionId]
1491
+ );
1492
+ return row ? JSON.parse(row.payload) : null;
1493
+ }
1494
+ async read(sessionId, continuationId) {
1495
+ const db = await this.getDb();
1496
+ const entry = this.load(db, sessionId);
1497
+ const acceptedRunId = continuationId && entry ? db.get(
1498
+ "SELECT run_id FROM goal_continuations WHERE session_id = ? AND goal_id = ? AND continuation_id = ?",
1499
+ [sessionId, entry.goal.goal_id, continuationId]
1500
+ )?.run_id : void 0;
1501
+ return { entry, acceptedRunId };
1502
+ }
1503
+ async update(sessionId, update) {
1504
+ const db = await this.getDb();
1505
+ db.exec("BEGIN IMMEDIATE");
1506
+ try {
1507
+ const tx = {
1508
+ entry: this.load(db, sessionId),
1509
+ consume: (continuationId, goalId, runId) => db.run(
1510
+ "INSERT INTO goal_continuations (continuation_id, session_id, goal_id, run_id) VALUES (?, ?, ?, ?)",
1511
+ [continuationId, sessionId, goalId, runId]
1512
+ )
1513
+ };
1514
+ const result = update(tx);
1515
+ if (tx.entry) {
1516
+ db.run(
1517
+ "INSERT INTO session_goals (session_id, payload) VALUES (?, ?) ON CONFLICT(session_id) DO UPDATE SET payload = excluded.payload",
1518
+ [sessionId, JSON.stringify(tx.entry)]
1519
+ );
1520
+ } else {
1521
+ db.run("DELETE FROM session_goals WHERE session_id = ?", [sessionId]);
1522
+ db.run("DELETE FROM goal_continuations WHERE session_id = ?", [
1523
+ sessionId
1524
+ ]);
1525
+ }
1526
+ db.exec("COMMIT");
1527
+ return result;
1528
+ } catch (error) {
1529
+ db.exec("ROLLBACK");
1530
+ throw error;
1531
+ }
734
1532
  }
735
1533
  };
736
1534
 
737
- // src/session-state.ts
738
- import { promises as fs4 } from "fs";
739
- import path6 from "path";
740
- import { stringifyContent } from "@codelia/core";
1535
+ // src/session-state.ts
741
1536
  var LEGACY_STATE_DIRNAME = "state";
742
1537
  var MESSAGES_DIRNAME = "messages";
743
1538
  var STATE_DB_FILENAME = "state.db";
744
1539
  var SESSION_WORKSPACE_ROOT_META_KEY = "codelia_workspace_root";
745
- var resolveLegacyStateDir = (paths) => path6.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
746
- var resolveMessagesDir = (paths) => path6.join(paths.sessionsDir, MESSAGES_DIRNAME);
747
- var resolveStateDbPath = (paths) => path6.join(paths.sessionsDir, STATE_DB_FILENAME);
1540
+ var RUN_INDEX_BACKFILL_KEY = "session_runs_backfilled_at";
1541
+ var resolveLegacyStateDir = (paths) => path9.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
1542
+ var resolveMessagesDir = (paths) => path9.join(paths.sessionsDir, MESSAGES_DIRNAME);
1543
+ var resolveStateDbPath = (paths) => path9.join(paths.sessionsDir, STATE_DB_FILENAME);
748
1544
  var extractLastUserMessage = (messages) => {
749
1545
  for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
750
1546
  const message = messages[idx];
751
1547
  if (!message || typeof message !== "object") continue;
752
1548
  if ("role" in message && message.role === "user" && "content" in message) {
753
- return stringifyContent(message.content, {
1549
+ return stringifyContent2(message.content, {
754
1550
  mode: "display"
755
1551
  });
756
1552
  }
@@ -777,13 +1573,10 @@ var fromSummaryRow = (row) => ({
777
1573
  run_id: row.run_id ?? void 0,
778
1574
  message_count: row.message_count ?? void 0,
779
1575
  last_user_message: row.last_user_message ?? void 0,
780
- workspace_root: row.workspace_root ?? void 0
1576
+ workspace_root: row.workspace_root ?? void 0,
1577
+ ...row.pinned === 1 ? { pinned: true } : {},
1578
+ ...row.archived_at ? { archived_at: row.archived_at } : {}
781
1579
  });
782
- var serializeMessages = (messages) => {
783
- if (messages.length === 0) return "";
784
- return `${messages.map((message) => JSON.stringify(message)).join("\n")}
785
- `;
786
- };
787
1580
  var deserializeMessages = (payload) => {
788
1581
  if (!payload.trim()) return [];
789
1582
  const messages = [];
@@ -799,44 +1592,32 @@ var deserializeMessages = (payload) => {
799
1592
  }
800
1593
  return messages;
801
1594
  };
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
1595
  var SessionStateStoreImpl = class {
1596
+ /** Root that `session_runs.rel_path` values are relative to. */
1597
+ sessionsDir;
1598
+ goals = new SessionGoalStore(() => this.requireDb("goals"));
823
1599
  legacyStateDir;
824
1600
  messagesDir;
1601
+ contextsDir;
825
1602
  stateDbPath;
826
1603
  ensureDirs;
827
1604
  db;
828
1605
  schemaInit;
829
1606
  onError;
830
1607
  lastDbUnavailableError;
1608
+ runIndexBackfill = null;
831
1609
  constructor(options = {}) {
832
1610
  const paths = options.paths ?? resolveStoragePaths();
1611
+ this.sessionsDir = paths.sessionsDir;
833
1612
  this.legacyStateDir = resolveLegacyStateDir(paths);
834
1613
  this.messagesDir = resolveMessagesDir(paths);
1614
+ this.contextsDir = path9.join(paths.sessionsDir, "contexts");
835
1615
  this.stateDbPath = resolveStateDbPath(paths);
836
1616
  this.ensureDirs = Promise.all([
837
- fs4.mkdir(paths.sessionsDir, { recursive: true }),
838
- fs4.mkdir(this.legacyStateDir, { recursive: true }),
839
- fs4.mkdir(this.messagesDir, { recursive: true })
1617
+ fs7.mkdir(paths.sessionsDir, { recursive: true }),
1618
+ fs7.mkdir(this.legacyStateDir, { recursive: true }),
1619
+ fs7.mkdir(this.messagesDir, { recursive: true }),
1620
+ fs7.mkdir(this.contextsDir, { recursive: true })
840
1621
  ]).then(() => {
841
1622
  });
842
1623
  this.onError = options.onError;
@@ -851,10 +1632,58 @@ var SessionStateStoreImpl = class {
851
1632
  return this.db;
852
1633
  }
853
1634
  resolveLegacyPath(sessionId) {
854
- return path6.join(this.legacyStateDir, `${sessionId}.json`);
1635
+ return path9.join(this.legacyStateDir, `${sessionId}.json`);
855
1636
  }
856
1637
  resolveMessagePath(sessionId) {
857
- return path6.join(this.messagesDir, `${sessionId}.jsonl`);
1638
+ return path9.join(this.messagesDir, `${validateRunLogId(sessionId)}.jsonl`);
1639
+ }
1640
+ contextPath(sessionId) {
1641
+ return path9.join(this.contextsDir, `${validateRunLogId(sessionId)}.json`);
1642
+ }
1643
+ writeContext(sessionId, messages) {
1644
+ const target = this.contextPath(sessionId);
1645
+ const temporary = `${target}.${crypto.randomUUID()}.tmp`;
1646
+ const archiveBytes = lstatSync2(this.resolveMessagePath(sessionId)).size;
1647
+ try {
1648
+ const fd = openSync2(temporary, "wx", 384);
1649
+ try {
1650
+ writeFileSync(
1651
+ fd,
1652
+ JSON.stringify({ version: 1, archive_bytes: archiveBytes, messages })
1653
+ );
1654
+ fsyncSync2(fd);
1655
+ } finally {
1656
+ closeSync2(fd);
1657
+ }
1658
+ renameSync(temporary, target);
1659
+ } finally {
1660
+ if (existsSync2(temporary)) unlinkSync(temporary);
1661
+ }
1662
+ }
1663
+ ensureArchive(sessionId, db) {
1664
+ const row = db.get(
1665
+ "SELECT archive_version FROM session_state WHERE session_id = ?",
1666
+ [sessionId]
1667
+ );
1668
+ if (row?.archive_version === 1) {
1669
+ if (!lstatSync2(this.resolveMessagePath(sessionId)).isFile())
1670
+ throw new Error("Invalid original conversation archive");
1671
+ return false;
1672
+ }
1673
+ const file = this.resolveMessagePath(sessionId);
1674
+ let messages = [];
1675
+ if (existsSync2(file)) {
1676
+ if (!lstatSync2(file).isFile())
1677
+ throw new Error("Invalid legacy conversation file");
1678
+ messages = deserializeMessages(readFileSync(file, "utf8"));
1679
+ } else appendOriginalMessages(file, []);
1680
+ this.writeContext(sessionId, messages);
1681
+ db.run(
1682
+ `INSERT INTO session_state (session_id, updated_at, schema_version, archive_version) VALUES (?, ?, 1, 1)
1683
+ ON CONFLICT(session_id) DO UPDATE SET archive_version = 1`,
1684
+ [sessionId, (/* @__PURE__ */ new Date()).toISOString()]
1685
+ );
1686
+ return messages.length === 0;
858
1687
  }
859
1688
  async openDatabase() {
860
1689
  await this.ensureDirs;
@@ -895,33 +1724,83 @@ var SessionStateStoreImpl = class {
895
1724
  };
896
1725
  }
897
1726
  initDatabaseSchema(db) {
1727
+ db.exec("PRAGMA busy_timeout = 5000;");
898
1728
  db.exec("PRAGMA journal_mode = WAL;");
899
- db.exec(`
900
- CREATE TABLE IF NOT EXISTS session_state (
901
- session_id TEXT PRIMARY KEY,
902
- updated_at TEXT NOT NULL,
903
- run_id TEXT,
904
- invoke_seq INTEGER,
905
- schema_version INTEGER NOT NULL,
906
- meta_json TEXT,
907
- message_count INTEGER,
908
- last_user_message TEXT,
909
- workspace_root TEXT
910
- );
911
- `);
912
- const columns = db.all(
913
- "PRAGMA table_info(session_state)"
914
- );
915
- const columnNames = new Set(
916
- columns.map((column) => column.name).filter((name) => typeof name === "string")
917
- );
918
- if (!columnNames.has("workspace_root")) {
919
- db.exec("ALTER TABLE session_state ADD COLUMN workspace_root TEXT;");
1729
+ db.exec("BEGIN IMMEDIATE");
1730
+ try {
1731
+ db.exec(`
1732
+ CREATE TABLE IF NOT EXISTS session_state (
1733
+ session_id TEXT PRIMARY KEY,
1734
+ updated_at TEXT NOT NULL,
1735
+ run_id TEXT,
1736
+ invoke_seq INTEGER,
1737
+ schema_version INTEGER NOT NULL,
1738
+ meta_json TEXT,
1739
+ message_count INTEGER,
1740
+ last_user_message TEXT,
1741
+ workspace_root TEXT
1742
+ );
1743
+ `);
1744
+ const columns = db.all(
1745
+ "PRAGMA table_info(session_state)"
1746
+ );
1747
+ const columnNames = new Set(
1748
+ columns.map((column) => column.name).filter((name) => typeof name === "string")
1749
+ );
1750
+ if (!columnNames.has("workspace_root")) {
1751
+ db.exec("ALTER TABLE session_state ADD COLUMN workspace_root TEXT;");
1752
+ }
1753
+ if (!columnNames.has("pinned"))
1754
+ db.exec(
1755
+ "ALTER TABLE session_state ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0;"
1756
+ );
1757
+ if (!columnNames.has("archived_at"))
1758
+ db.exec("ALTER TABLE session_state ADD COLUMN archived_at TEXT;");
1759
+ if (!columnNames.has("archive_version"))
1760
+ db.exec(
1761
+ "ALTER TABLE session_state ADD COLUMN archive_version INTEGER NOT NULL DEFAULT 0;"
1762
+ );
1763
+ db.exec(`
1764
+ CREATE INDEX IF NOT EXISTS idx_session_state_updated_at
1765
+ ON session_state(updated_at DESC);
1766
+ `);
1767
+ db.exec(`
1768
+ CREATE TABLE IF NOT EXISTS session_runs (
1769
+ rel_path TEXT PRIMARY KEY,
1770
+ session_id TEXT NOT NULL,
1771
+ run_id TEXT NOT NULL,
1772
+ started_at TEXT NOT NULL
1773
+ );
1774
+ `);
1775
+ db.exec(`
1776
+ CREATE INDEX IF NOT EXISTS idx_session_runs_session
1777
+ ON session_runs(session_id, started_at DESC);
1778
+ `);
1779
+ db.exec(`
1780
+ CREATE TABLE IF NOT EXISTS session_run_checks (
1781
+ session_id TEXT PRIMARY KEY,
1782
+ run_id TEXT NOT NULL,
1783
+ checked_at TEXT NOT NULL
1784
+ );
1785
+ `);
1786
+ db.exec(`
1787
+ CREATE TABLE IF NOT EXISTS session_run_rescans (
1788
+ session_id TEXT PRIMARY KEY,
1789
+ flagged_at TEXT NOT NULL
1790
+ );
1791
+ `);
1792
+ db.exec(`
1793
+ CREATE TABLE IF NOT EXISTS storage_meta (
1794
+ key TEXT PRIMARY KEY,
1795
+ value TEXT NOT NULL
1796
+ );
1797
+ `);
1798
+ initSessionGoals(db);
1799
+ db.exec("COMMIT");
1800
+ } catch (error) {
1801
+ db.exec("ROLLBACK");
1802
+ throw error;
920
1803
  }
921
- db.exec(`
922
- CREATE INDEX IF NOT EXISTS idx_session_state_updated_at
923
- ON session_state(updated_at DESC);
924
- `);
925
1804
  }
926
1805
  async tryGetDb(action, detail) {
927
1806
  try {
@@ -952,7 +1831,7 @@ var SessionStateStoreImpl = class {
952
1831
  }
953
1832
  async loadLegacy(sessionId) {
954
1833
  try {
955
- const file = await fs4.readFile(this.resolveLegacyPath(sessionId), "utf8");
1834
+ const file = await fs7.readFile(this.resolveLegacyPath(sessionId), "utf8");
956
1835
  const parsed = JSON.parse(file);
957
1836
  if (!parsed || typeof parsed !== "object") return null;
958
1837
  if (!parsed.session_id || !parsed.updated_at) return null;
@@ -978,7 +1857,7 @@ var SessionStateStoreImpl = class {
978
1857
  let row;
979
1858
  try {
980
1859
  row = db.get(
981
- `SELECT session_id, updated_at, run_id, invoke_seq, schema_version, meta_json
1860
+ `SELECT session_id, updated_at, run_id, invoke_seq, schema_version, meta_json, archive_version
982
1861
  FROM session_state
983
1862
  WHERE session_id = ?`,
984
1863
  [sessionId]
@@ -990,13 +1869,19 @@ var SessionStateStoreImpl = class {
990
1869
  if (!row) return null;
991
1870
  let messages;
992
1871
  try {
993
- const payload = await fs4.readFile(
994
- this.resolveMessagePath(sessionId),
995
- "utf8"
996
- );
997
- messages = deserializeMessages(payload);
1872
+ if (row.archive_version === 1) {
1873
+ const checkpoint = JSON.parse(
1874
+ await fs7.readFile(this.contextPath(sessionId), "utf8")
1875
+ );
1876
+ if (checkpoint.version !== 1 || !Array.isArray(checkpoint.messages))
1877
+ throw new Error("Invalid active conversation checkpoint");
1878
+ messages = checkpoint.messages;
1879
+ } else
1880
+ messages = deserializeMessages(
1881
+ await fs7.readFile(this.resolveMessagePath(sessionId), "utf8")
1882
+ );
998
1883
  } catch (error) {
999
- if (error.code === "ENOENT") {
1884
+ if (error.code === "ENOENT" && row.archive_version !== 1) {
1000
1885
  messages = [];
1001
1886
  } else {
1002
1887
  this.onError?.(error, { action: "messages.load", detail: sessionId });
@@ -1028,16 +1913,17 @@ var SessionStateStoreImpl = class {
1028
1913
  };
1029
1914
  }
1030
1915
  async saveToIndex(state, db) {
1031
- const messagePayload = serializeMessages(
1032
- Array.isArray(state.messages) ? state.messages : []
1033
- );
1034
- await atomicWriteFile2(
1035
- this.resolveMessagePath(state.session_id),
1036
- messagePayload
1037
- );
1038
- const summary = toSummary(state);
1039
- db.run(
1040
- `INSERT INTO session_state (
1916
+ await this.withRetentionGuard(state.session_id, () => {
1917
+ const seed = this.ensureArchive(state.session_id, db);
1918
+ if (seed)
1919
+ appendOriginalMessages(
1920
+ this.resolveMessagePath(state.session_id),
1921
+ state.messages
1922
+ );
1923
+ this.writeContext(state.session_id, state.messages);
1924
+ const summary = toSummary(state);
1925
+ db.run(
1926
+ `INSERT INTO session_state (
1041
1927
  session_id,
1042
1928
  updated_at,
1043
1929
  run_id,
@@ -1058,18 +1944,35 @@ var SessionStateStoreImpl = class {
1058
1944
  message_count = excluded.message_count,
1059
1945
  last_user_message = excluded.last_user_message,
1060
1946
  workspace_root = excluded.workspace_root`,
1061
- [
1062
- state.session_id,
1063
- state.updated_at,
1064
- state.run_id ?? null,
1065
- state.invoke_seq ?? null,
1066
- state.schema_version ?? 1,
1067
- state.meta ? JSON.stringify(state.meta) : null,
1068
- summary.message_count ?? null,
1069
- summary.last_user_message ?? null,
1070
- summary.workspace_root ?? null
1071
- ]
1072
- );
1947
+ [
1948
+ state.session_id,
1949
+ state.updated_at,
1950
+ state.run_id ?? null,
1951
+ state.invoke_seq ?? null,
1952
+ state.schema_version ?? 1,
1953
+ state.meta ? JSON.stringify(state.meta) : null,
1954
+ summary.message_count ?? null,
1955
+ summary.last_user_message ?? null,
1956
+ summary.workspace_root ?? null
1957
+ ]
1958
+ );
1959
+ });
1960
+ }
1961
+ async appendMessages(sessionId, messages) {
1962
+ const db = await this.requireDb("archive.append", sessionId);
1963
+ if (!await this.getSummary(sessionId)) await this.load(sessionId);
1964
+ await this.withRetentionGuard(sessionId, () => {
1965
+ this.ensureArchive(sessionId, db);
1966
+ appendOriginalMessages(this.resolveMessagePath(sessionId), messages);
1967
+ });
1968
+ }
1969
+ async searchMessages(sessionId, options) {
1970
+ if (!await this.getSummary(sessionId)) await this.load(sessionId);
1971
+ return searchOriginalMessages(this.resolveMessagePath(sessionId), options);
1972
+ }
1973
+ async readMessage(sessionId, options) {
1974
+ if (!await this.getSummary(sessionId)) await this.load(sessionId);
1975
+ return readOriginalMessage(this.resolveMessagePath(sessionId), options);
1073
1976
  }
1074
1977
  async load(sessionId) {
1075
1978
  const db = await this.requireDb("load", sessionId);
@@ -1090,6 +1993,7 @@ var SessionStateStoreImpl = class {
1090
1993
  action: "load.migrate_legacy",
1091
1994
  detail: sessionId
1092
1995
  });
1996
+ throw error;
1093
1997
  }
1094
1998
  }
1095
1999
  return legacy;
@@ -1104,10 +2008,192 @@ var SessionStateStoreImpl = class {
1104
2008
  throw error;
1105
2009
  }
1106
2010
  }
2011
+ async getSummary(sessionId) {
2012
+ const db = await this.requireDb("summary", sessionId);
2013
+ const row = db.get(
2014
+ "SELECT session_id, updated_at, run_id, message_count, last_user_message, workspace_root, pinned, archived_at FROM session_state WHERE session_id = ?",
2015
+ [sessionId]
2016
+ );
2017
+ return row ? fromSummaryRow(row) : null;
2018
+ }
2019
+ /** Serializes pin changes with the final, synchronous unlink decision. */
2020
+ async withRetentionGuard(sessionId, action) {
2021
+ const db = await this.requireDb("retention", sessionId);
2022
+ db.exec("BEGIN IMMEDIATE");
2023
+ try {
2024
+ const row = db.get(
2025
+ "SELECT session_id, updated_at, run_id, message_count, last_user_message, workspace_root, pinned, archived_at FROM session_state WHERE session_id = ?",
2026
+ [sessionId]
2027
+ );
2028
+ const result = action(row ? fromSummaryRow(row) : null);
2029
+ db.exec("COMMIT");
2030
+ return result;
2031
+ } catch (error) {
2032
+ db.exec("ROLLBACK");
2033
+ throw error;
2034
+ }
2035
+ }
2036
+ async updateMetadata(sessionId, patch) {
2037
+ if (!await this.getSummary(sessionId)) await this.load(sessionId);
2038
+ const db = await this.requireDb("updateMetadata", sessionId);
2039
+ return this.withRetentionGuard(sessionId, (summary) => {
2040
+ if (!summary) throw new Error("Session not found");
2041
+ if (patch.pinned !== void 0)
2042
+ db.run("UPDATE session_state SET pinned = ? WHERE session_id = ?", [
2043
+ patch.pinned ? 1 : 0,
2044
+ sessionId
2045
+ ]);
2046
+ const archivedAt = patch.archived === void 0 ? summary.archived_at : patch.archived ? summary.archived_at ?? (/* @__PURE__ */ new Date()).toISOString() : void 0;
2047
+ if (patch.archived !== void 0)
2048
+ db.run(
2049
+ "UPDATE session_state SET archived_at = ? WHERE session_id = ?",
2050
+ [archivedAt ?? null, sessionId]
2051
+ );
2052
+ return {
2053
+ ...summary,
2054
+ pinned: patch.pinned ?? summary.pinned,
2055
+ archived_at: archivedAt
2056
+ };
2057
+ });
2058
+ }
2059
+ /** Records a run log; idempotent, safe across concurrent runtimes. */
2060
+ async recordSessionRun(entry) {
2061
+ const db = await this.requireDb("runs.record", entry.session_id);
2062
+ db.exec("BEGIN IMMEDIATE");
2063
+ try {
2064
+ const previous = db.get(
2065
+ "SELECT run_id FROM session_state WHERE session_id = ?",
2066
+ [entry.session_id]
2067
+ )?.run_id;
2068
+ if (previous && previous !== entry.run_id && !this.isRunKnown(db, entry.session_id, previous))
2069
+ db.run(
2070
+ `INSERT INTO session_run_rescans (session_id, flagged_at) VALUES (?, ?)
2071
+ ON CONFLICT(session_id) DO UPDATE SET flagged_at = excluded.flagged_at`,
2072
+ [entry.session_id, (/* @__PURE__ */ new Date()).toISOString()]
2073
+ );
2074
+ db.run(
2075
+ `INSERT INTO session_runs (rel_path, session_id, run_id, started_at)
2076
+ VALUES (?, ?, ?, ?)
2077
+ ON CONFLICT(rel_path) DO NOTHING`,
2078
+ [
2079
+ entry.rel_path,
2080
+ entry.session_id,
2081
+ entry.run_id,
2082
+ normalizeRunStartedAt(entry.started_at)
2083
+ ]
2084
+ );
2085
+ db.exec("COMMIT");
2086
+ } catch (error) {
2087
+ db.exec("ROLLBACK");
2088
+ throw error;
2089
+ }
2090
+ }
2091
+ /** True when run_id is indexed for the session or was already rescanned. */
2092
+ isRunKnown(db, sessionId, runId) {
2093
+ return Boolean(
2094
+ db.get(
2095
+ "SELECT 1 AS ok FROM session_runs WHERE session_id = ? AND run_id = ? LIMIT 1",
2096
+ [sessionId, runId]
2097
+ ) ?? db.get(
2098
+ "SELECT 1 AS ok FROM session_run_checks WHERE session_id = ? AND run_id = ?",
2099
+ [sessionId, runId]
2100
+ )
2101
+ );
2102
+ }
2103
+ /**
2104
+ * The index answers for a session once a store-wide backfill finished and
2105
+ * the session's latest run_id is either indexed or was already rescanned.
2106
+ * The run_id check catches logs written by runtimes that predate the index.
2107
+ */
2108
+ isSessionRunIndexComplete(db, sessionId) {
2109
+ if (!db.get("SELECT 1 AS ok FROM storage_meta WHERE key = ?", [
2110
+ RUN_INDEX_BACKFILL_KEY
2111
+ ]))
2112
+ return false;
2113
+ if (db.get("SELECT 1 AS ok FROM session_run_rescans WHERE session_id = ?", [
2114
+ sessionId
2115
+ ]))
2116
+ return false;
2117
+ const latest = db.get(
2118
+ "SELECT run_id FROM session_state WHERE session_id = ?",
2119
+ [sessionId]
2120
+ )?.run_id;
2121
+ return !latest || this.isRunKnown(db, sessionId, latest);
2122
+ }
2123
+ /** One store-wide header scan per process at a time; rows are idempotent. */
2124
+ backfillSessionRuns(db) {
2125
+ if (!this.runIndexBackfill) {
2126
+ this.runIndexBackfill = (async () => {
2127
+ const scanStartedAt = (/* @__PURE__ */ new Date()).toISOString();
2128
+ const entries2 = await scanSessionRunLogs(this.sessionsDir);
2129
+ db.exec("BEGIN IMMEDIATE");
2130
+ try {
2131
+ for (const entry of entries2)
2132
+ db.run(
2133
+ `INSERT INTO session_runs (rel_path, session_id, run_id, started_at)
2134
+ VALUES (?, ?, ?, ?)
2135
+ ON CONFLICT(rel_path) DO NOTHING`,
2136
+ [
2137
+ entry.rel_path,
2138
+ entry.session_id,
2139
+ entry.run_id,
2140
+ entry.started_at
2141
+ ]
2142
+ );
2143
+ db.run(
2144
+ `INSERT INTO storage_meta (key, value) VALUES (?, ?)
2145
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
2146
+ [RUN_INDEX_BACKFILL_KEY, (/* @__PURE__ */ new Date()).toISOString()]
2147
+ );
2148
+ db.run("DELETE FROM session_run_rescans WHERE flagged_at <= ?", [
2149
+ scanStartedAt
2150
+ ]);
2151
+ db.exec("COMMIT");
2152
+ } catch (error) {
2153
+ db.exec("ROLLBACK");
2154
+ throw error;
2155
+ }
2156
+ })().finally(() => {
2157
+ this.runIndexBackfill = null;
2158
+ });
2159
+ }
2160
+ return this.runIndexBackfill;
2161
+ }
2162
+ /**
2163
+ * Returns the session's run logs, newest first. Falls back to one
2164
+ * store-wide header scan (which indexes every session) only while the
2165
+ * index cannot answer for this session.
2166
+ */
2167
+ async listSessionRuns(sessionId) {
2168
+ const db = await this.requireDb("runs.list", sessionId);
2169
+ if (!this.isSessionRunIndexComplete(db, sessionId)) {
2170
+ const latest = db.get(
2171
+ "SELECT run_id FROM session_state WHERE session_id = ?",
2172
+ [sessionId]
2173
+ )?.run_id;
2174
+ await this.backfillSessionRuns(db);
2175
+ if (latest)
2176
+ db.run(
2177
+ `INSERT INTO session_run_checks (session_id, run_id, checked_at)
2178
+ VALUES (?, ?, ?)
2179
+ ON CONFLICT(session_id) DO UPDATE SET
2180
+ run_id = excluded.run_id,
2181
+ checked_at = excluded.checked_at`,
2182
+ [sessionId, latest, (/* @__PURE__ */ new Date()).toISOString()]
2183
+ );
2184
+ }
2185
+ return db.all(
2186
+ `SELECT session_id, run_id, rel_path, started_at
2187
+ FROM session_runs
2188
+ WHERE session_id = ?
2189
+ ORDER BY started_at DESC, rel_path DESC`,
2190
+ [sessionId]
2191
+ );
2192
+ }
1107
2193
  async listLegacySummaries() {
1108
- let entries;
2194
+ let entries2;
1109
2195
  try {
1110
- entries = await fs4.readdir(this.legacyStateDir, {
2196
+ entries2 = await fs7.readdir(this.legacyStateDir, {
1111
2197
  withFileTypes: true,
1112
2198
  encoding: "utf8"
1113
2199
  });
@@ -1116,12 +2202,12 @@ var SessionStateStoreImpl = class {
1116
2202
  throw error;
1117
2203
  }
1118
2204
  const summaries = [];
1119
- for (const entry of entries) {
2205
+ for (const entry of entries2) {
1120
2206
  if (!entry.isFile()) continue;
1121
2207
  if (!entry.name.endsWith(".json")) continue;
1122
- const filePath = path6.join(this.legacyStateDir, entry.name);
2208
+ const filePath = path9.join(this.legacyStateDir, entry.name);
1123
2209
  try {
1124
- const contents = await fs4.readFile(filePath, "utf8");
2210
+ const contents = await fs7.readFile(filePath, "utf8");
1125
2211
  const parsed = JSON.parse(contents);
1126
2212
  if (!parsed || typeof parsed !== "object") continue;
1127
2213
  if (!parsed.session_id || !parsed.updated_at) continue;
@@ -1144,7 +2230,7 @@ var SessionStateStoreImpl = class {
1144
2230
  const db = await this.requireDb("list");
1145
2231
  try {
1146
2232
  const rows = db.all(
1147
- `SELECT session_id, updated_at, run_id, message_count, last_user_message, workspace_root
2233
+ `SELECT session_id, updated_at, run_id, message_count, last_user_message, workspace_root, pinned, archived_at
1148
2234
  FROM session_state
1149
2235
  ORDER BY updated_at DESC`
1150
2236
  );
@@ -1165,9 +2251,721 @@ var SessionStateStoreImpl = class {
1165
2251
  }
1166
2252
  };
1167
2253
 
2254
+ // src/run-event-store.ts
2255
+ var RunEventStoreFactoryImpl = class {
2256
+ runIndex;
2257
+ onRunIndexError;
2258
+ /**
2259
+ * `runIndex` records each run in state.db (`session_runs`). When omitted, a
2260
+ * default-path SessionStateStoreImpl is created on the first run so every
2261
+ * normal run log stays indexed.
2262
+ */
2263
+ constructor(options = {}) {
2264
+ this.runIndex = options.runIndex;
2265
+ this.onRunIndexError = options.onRunIndexError;
2266
+ }
2267
+ create(init) {
2268
+ this.runIndex ??= new SessionStateStoreImpl();
2269
+ return new SessionStoreWriterImpl({
2270
+ runId: init.runId,
2271
+ startedAt: init.startedAt,
2272
+ runIndex: this.runIndex,
2273
+ onRunIndexError: this.onRunIndexError
2274
+ });
2275
+ }
2276
+ };
2277
+
2278
+ // src/run-log-retention.ts
2279
+ import {
2280
+ promises as fs11,
2281
+ linkSync,
2282
+ lstatSync as lstatSync4,
2283
+ renameSync as renameSync2,
2284
+ unlinkSync as unlinkSync3,
2285
+ utimesSync
2286
+ } from "fs";
2287
+ import path12 from "path";
2288
+
2289
+ // src/run-log-compression.ts
2290
+ import { createHash as createHash4 } from "crypto";
2291
+ import { createReadStream as createReadStream2, createWriteStream, promises as fs8 } from "fs";
2292
+ import { Readable as Readable2, Transform } from "stream";
2293
+ import { pipeline } from "stream/promises";
2294
+ import { createGunzip as createGunzip2, createGzip } from "zlib";
2295
+
2296
+ // src/run-log-records.ts
2297
+ var MAX_RECORD_PREFIX_BYTES = 256;
2298
+ var RECORD_TYPE = /^\s*\{\s*"type"\s*:\s*"([^"\\]+)"/;
2299
+ async function* readRunLogRecordParts(file) {
2300
+ let prefix = Buffer.alloc(0);
2301
+ let type;
2302
+ for await (const chunk of readRunLogChunks(file)) {
2303
+ let offset = 0;
2304
+ while (offset < chunk.length) {
2305
+ const newline = chunk.indexOf(10, offset);
2306
+ const next = newline < 0 ? chunk.length : newline + 1;
2307
+ const data = chunk.subarray(offset, next);
2308
+ const end = newline >= 0;
2309
+ if (type === void 0) {
2310
+ const consumed = Math.min(
2311
+ MAX_RECORD_PREFIX_BYTES - prefix.length,
2312
+ data.length
2313
+ );
2314
+ prefix = Buffer.concat([prefix, data.subarray(0, consumed)]);
2315
+ const match = RECORD_TYPE.exec(prefix.toString("utf8"));
2316
+ if (!match) {
2317
+ if (end || prefix.length === MAX_RECORD_PREFIX_BYTES)
2318
+ throw new Error("Invalid run log record prefix");
2319
+ } else {
2320
+ type = match[1];
2321
+ yield {
2322
+ type,
2323
+ data: prefix,
2324
+ start: true,
2325
+ end: end && consumed === data.length
2326
+ };
2327
+ prefix = Buffer.alloc(0);
2328
+ if (consumed < data.length)
2329
+ yield { type, data: data.subarray(consumed), start: false, end };
2330
+ }
2331
+ } else yield { type, data, start: false, end };
2332
+ if (end) type = void 0;
2333
+ offset = next;
2334
+ }
2335
+ }
2336
+ if (type !== void 0 || prefix.length)
2337
+ throw new Error("Incomplete run log record");
2338
+ }
2339
+
2340
+ // src/run-log-archive.ts
2341
+ var RUN_LOG_ARCHIVE_VERSION = 1;
2342
+ var MAX_RUN_LOG_HEADER_BYTES = 256 * 1024;
2343
+ var DIAGNOSTIC_RECORDS = /* @__PURE__ */ new Set([
2344
+ "llm.request",
2345
+ "llm.response",
2346
+ "tool.output"
2347
+ ]);
2348
+ async function* projectArchivedRunLog(file, usage) {
2349
+ let headerSeen = false;
2350
+ let headerParts = [];
2351
+ let headerBytes = 0;
2352
+ for await (const part of readRunLogRecordParts(file)) {
2353
+ if (!headerSeen && part.type !== "header")
2354
+ throw new Error("Run log must start with its header");
2355
+ if (part.type === "header") {
2356
+ if (headerSeen) throw new Error("Duplicate run log header");
2357
+ headerBytes += part.data.length;
2358
+ if (headerBytes > MAX_RUN_LOG_HEADER_BYTES)
2359
+ throw new Error("Run log header is too large");
2360
+ headerParts.push(part.data);
2361
+ if (part.end) {
2362
+ const header = JSON.parse(
2363
+ Buffer.concat(headerParts, headerBytes).toString("utf8")
2364
+ );
2365
+ const { prompts: _prompts, tools: _tools, ...retained } = header;
2366
+ yield Buffer.from(
2367
+ `${JSON.stringify({
2368
+ ...retained,
2369
+ meta: {
2370
+ ...retained.meta,
2371
+ codelia_log_archive_version: RUN_LOG_ARCHIVE_VERSION
2372
+ }
2373
+ })}
2374
+ `
2375
+ );
2376
+ headerSeen = true;
2377
+ headerParts = [];
2378
+ }
2379
+ } else if (part.type !== "llm.usage" && !DIAGNOSTIC_RECORDS.has(part.type)) {
2380
+ yield part.data;
2381
+ }
2382
+ }
2383
+ if (!headerSeen) throw new Error("Missing run log header");
2384
+ for (const record2 of usage) yield Buffer.from(`${JSON.stringify(record2)}
2385
+ `);
2386
+ }
2387
+
2388
+ // src/run-log-compression.ts
2389
+ async function prepareCompressedLog(file, usage) {
2390
+ const temporary = `${file}.${crypto.randomUUID()}.gz.tmp`;
2391
+ const hash = createHash4("sha256");
2392
+ let bytes = 0;
2393
+ try {
2394
+ await pipeline(
2395
+ Readable2.from(projectArchivedRunLog(file, usage)),
2396
+ new Transform({
2397
+ transform(chunk, _encoding, callback) {
2398
+ bytes += chunk.length;
2399
+ hash.update(chunk);
2400
+ callback(null, chunk);
2401
+ }
2402
+ }),
2403
+ createGzip(),
2404
+ createWriteStream(temporary, { flags: "wx", mode: 384 })
2405
+ );
2406
+ const expected = hash.digest("hex");
2407
+ const verification = createHash4("sha256");
2408
+ let decoded = 0;
2409
+ await pipeline(
2410
+ createReadStream2(temporary),
2411
+ createGunzip2(),
2412
+ new Transform({
2413
+ transform(chunk, _encoding, callback) {
2414
+ decoded += chunk.length;
2415
+ verification.update(chunk);
2416
+ callback();
2417
+ }
2418
+ })
2419
+ );
2420
+ if (decoded !== bytes || verification.digest("hex") !== expected)
2421
+ throw new Error("Compressed run log verification failed");
2422
+ const persisted = await fs8.open(temporary, "r+");
2423
+ try {
2424
+ await persisted.sync();
2425
+ } finally {
2426
+ await persisted.close();
2427
+ }
2428
+ return { temporary, size: (await fs8.stat(temporary)).size };
2429
+ } catch (error) {
2430
+ await fs8.rm(temporary, { force: true });
2431
+ throw error;
2432
+ }
2433
+ }
2434
+
2435
+ // src/run-log-files.ts
2436
+ import {
2437
+ promises as fs9,
2438
+ lstatSync as lstatSync3,
2439
+ readdirSync,
2440
+ readFileSync as readFileSync2,
2441
+ unlinkSync as unlinkSync2
2442
+ } from "fs";
2443
+ import path10 from "path";
2444
+ var MAX_ACTIVE_RUN_MARKER_BYTES = 256;
2445
+ var isRegularDirectory = async (directory2) => {
2446
+ try {
2447
+ return (await fs9.lstat(directory2)).isDirectory();
2448
+ } catch {
2449
+ return false;
2450
+ }
2451
+ };
2452
+ async function readHeader2(file) {
2453
+ const parts = [];
2454
+ let length = 0;
2455
+ for await (const chunk of readRunLogChunks(file)) {
2456
+ const newline = chunk.indexOf(10);
2457
+ const part = newline < 0 ? chunk : chunk.subarray(0, newline + 1);
2458
+ length += part.length;
2459
+ if (length > MAX_RUN_LOG_HEADER_BYTES) return null;
2460
+ parts.push(part);
2461
+ if (newline < 0) continue;
2462
+ const record2 = JSON.parse(Buffer.concat(parts, length).toString("utf8"));
2463
+ if (record2.type !== "header" || typeof record2.run_id !== "string" || typeof record2.session_id !== "string")
2464
+ return null;
2465
+ validateRunLogId(record2.run_id);
2466
+ validateRunLogId(record2.session_id);
2467
+ return record2;
2468
+ }
2469
+ return null;
2470
+ }
2471
+ async function inspectCandidate(root, datePath, name, diagnostic) {
2472
+ const compressed = name.endsWith(".jsonl.gz");
2473
+ const file = path10.join(root, datePath, name);
2474
+ try {
2475
+ const stat = await fs9.lstat(file);
2476
+ if (!stat.isFile()) return void 0;
2477
+ const header = await readHeader2(file);
2478
+ if (!header || name !== `${header.run_id}.jsonl${compressed ? ".gz" : ""}` || compressed && header.meta?.codelia_log_archive_version === RUN_LOG_ARCHIVE_VERSION)
2479
+ return void 0;
2480
+ return {
2481
+ file,
2482
+ runId: header.run_id,
2483
+ sessionId: header.session_id,
2484
+ datePath,
2485
+ mtimeMs: stat.mtimeMs,
2486
+ size: stat.size,
2487
+ ino: stat.ino,
2488
+ dev: stat.dev,
2489
+ diagnostic,
2490
+ compressed,
2491
+ model: header.model ? { provider: header.model.provider, name: header.model.name } : void 0
2492
+ };
2493
+ } catch {
2494
+ return void 0;
2495
+ }
2496
+ }
2497
+ async function collectRunLogCandidates(root, diagnostic = false) {
2498
+ if (!await isRegularDirectory(root)) return [];
2499
+ const candidates = [];
2500
+ for (const year of await fs9.readdir(root, { withFileTypes: true })) {
2501
+ if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
2502
+ for (const month of await fs9.readdir(path10.join(root, year.name), {
2503
+ withFileTypes: true
2504
+ })) {
2505
+ if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
2506
+ for (const day of await fs9.readdir(
2507
+ path10.join(root, year.name, month.name),
2508
+ { withFileTypes: true }
2509
+ )) {
2510
+ if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
2511
+ const datePath = path10.join(year.name, month.name, day.name);
2512
+ const entries2 = await fs9.readdir(path10.join(root, datePath), {
2513
+ withFileTypes: true
2514
+ });
2515
+ const plain = new Set(
2516
+ entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".jsonl")).map((entry) => entry.name)
2517
+ );
2518
+ for (const entry of entries2) {
2519
+ const compressed = entry.name.endsWith(".jsonl.gz");
2520
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl") && (diagnostic || !compressed))
2521
+ continue;
2522
+ if (compressed && plain.has(entry.name.slice(0, -3))) continue;
2523
+ const candidate = await inspectCandidate(
2524
+ root,
2525
+ datePath,
2526
+ entry.name,
2527
+ diagnostic
2528
+ );
2529
+ if (candidate) candidates.push(candidate);
2530
+ }
2531
+ }
2532
+ }
2533
+ }
2534
+ return candidates;
2535
+ }
2536
+ async function collectRunLogCandidatesAt(root, relPaths, diagnostic = false) {
2537
+ if (!await isRegularDirectory(root)) return [];
2538
+ const candidates = [];
2539
+ for (const relPath of relPaths) {
2540
+ const parts = relPath.split("/");
2541
+ const name = parts.pop();
2542
+ if (!name?.endsWith(".jsonl") || parts.length !== 3 || !/^\d{4}$/.test(parts[0] ?? "") || !/^\d{2}$/.test(parts[1] ?? "") || !/^\d{2}$/.test(parts[2] ?? "") || name.includes("\\"))
2543
+ continue;
2544
+ const datePath = path10.join(...parts);
2545
+ let selected = name;
2546
+ try {
2547
+ await fs9.lstat(path10.join(root, datePath, name));
2548
+ } catch {
2549
+ if (diagnostic) continue;
2550
+ selected = `${name}.gz`;
2551
+ }
2552
+ const candidate = await inspectCandidate(
2553
+ root,
2554
+ datePath,
2555
+ selected,
2556
+ diagnostic
2557
+ );
2558
+ if (candidate) candidates.push(candidate);
2559
+ }
2560
+ return candidates;
2561
+ }
2562
+ async function removeReusedProcessMarkers(paths, sessionId, identify = (pid) => getProcessIdentity(pid, { canonicalEnvironment: true })) {
2563
+ const directory2 = activeRunDirectory(paths, sessionId);
2564
+ let entries2;
2565
+ try {
2566
+ entries2 = readdirSync(directory2);
2567
+ } catch {
2568
+ return;
2569
+ }
2570
+ for (const entry of entries2) {
2571
+ const file = path10.join(directory2, entry);
2572
+ try {
2573
+ const before = lstatSync3(file);
2574
+ if (!before.isFile() || before.size > MAX_ACTIVE_RUN_MARKER_BYTES)
2575
+ continue;
2576
+ const contents = readFileSync2(file, "utf8");
2577
+ const { pid, identity } = JSON.parse(contents);
2578
+ if (!Number.isSafeInteger(pid) || pid < 1 || typeof identity !== "string" || !identity)
2579
+ continue;
2580
+ const current = await identify(pid);
2581
+ if (!current || current === identity) continue;
2582
+ const after = lstatSync3(file);
2583
+ if (after.isFile() && after.ino === before.ino && after.dev === before.dev && after.size === before.size && after.mtimeMs === before.mtimeMs && readFileSync2(file, "utf8") === contents)
2584
+ unlinkSync2(file);
2585
+ } catch {
2586
+ }
2587
+ }
2588
+ }
2589
+ function hasActiveRunWriter(paths, sessionId) {
2590
+ try {
2591
+ const directory2 = activeRunDirectory(paths, sessionId);
2592
+ for (const entry of readdirSync(directory2, { withFileTypes: true })) {
2593
+ if (!entry.isFile()) return true;
2594
+ try {
2595
+ const file = path10.join(directory2, entry.name);
2596
+ if (lstatSync3(file).size > MAX_ACTIVE_RUN_MARKER_BYTES) return true;
2597
+ const { pid } = JSON.parse(readFileSync2(file, "utf8"));
2598
+ if (!Number.isSafeInteger(pid) || pid < 1) return true;
2599
+ try {
2600
+ process.kill(pid, 0);
2601
+ return true;
2602
+ } catch (error) {
2603
+ if (error.code !== "ESRCH") return true;
2604
+ }
2605
+ } catch {
2606
+ return true;
2607
+ }
2608
+ }
2609
+ return false;
2610
+ } catch (error) {
2611
+ return error.code !== "ENOENT";
2612
+ }
2613
+ }
2614
+
2615
+ // src/run-log-usage.ts
2616
+ import { promises as fs10 } from "fs";
2617
+ import path11 from "path";
2618
+
2619
+ // src/run-log-request-model.ts
2620
+ var TOKENS = /["\\{}[\]:,]/g;
2621
+ var MAX_KEY_BYTES = 256;
2622
+ var MAX_MODEL_BYTES = 64 * 1024;
2623
+ var RunLogRequestModel = class {
2624
+ depth = 0;
2625
+ inString = false;
2626
+ escapeAt = -2;
2627
+ offset = 0;
2628
+ complete = false;
2629
+ key;
2630
+ inValue = false;
2631
+ capture;
2632
+ parts = [];
2633
+ bytes = 0;
2634
+ fields = {};
2635
+ push(data) {
2636
+ if (this.complete) {
2637
+ if (data.toString("utf8").trim())
2638
+ throw new Error("Extra request record data");
2639
+ return;
2640
+ }
2641
+ let captureStart = this.capture ? 0 : void 0;
2642
+ const append = (end) => {
2643
+ if (captureStart === void 0 || end <= captureStart) return;
2644
+ this.bytes += end - captureStart;
2645
+ if (this.bytes > (this.capture === "key" ? MAX_KEY_BYTES : MAX_MODEL_BYTES))
2646
+ throw new Error("Request accounting metadata is too large");
2647
+ this.parts.push(data.subarray(captureStart, end));
2648
+ };
2649
+ const finish = (end) => {
2650
+ append(end);
2651
+ const value = JSON.parse(
2652
+ Buffer.concat(this.parts, this.bytes).toString("utf8")
2653
+ );
2654
+ this.capture = void 0;
2655
+ this.parts = [];
2656
+ this.bytes = 0;
2657
+ captureStart = void 0;
2658
+ return value;
2659
+ };
2660
+ const finishValue = (end) => {
2661
+ if (this.capture === "value" && this.key !== void 0)
2662
+ this.fields[this.key] = finish(end);
2663
+ this.key = void 0;
2664
+ this.inValue = false;
2665
+ };
2666
+ const text = data.toString("latin1");
2667
+ const tokens = new RegExp(TOKENS);
2668
+ for (let match = tokens.exec(text); match; match = tokens.exec(text)) {
2669
+ const index = match.index;
2670
+ const token = match[0];
2671
+ const absolute = this.offset + index;
2672
+ if (this.inString) {
2673
+ if (absolute === this.escapeAt + 1) {
2674
+ this.escapeAt = -2;
2675
+ continue;
2676
+ }
2677
+ if (token === "\\") {
2678
+ this.escapeAt = absolute;
2679
+ continue;
2680
+ }
2681
+ if (token !== '"') continue;
2682
+ this.inString = false;
2683
+ if (this.capture === "key") this.key = finish(index + 1);
2684
+ continue;
2685
+ }
2686
+ if (token === '"') {
2687
+ this.inString = true;
2688
+ if (this.depth === 1 && !this.inValue && this.key === void 0) {
2689
+ this.capture = "key";
2690
+ captureStart = index;
2691
+ }
2692
+ } else if (token === "{" || token === "[") this.depth++;
2693
+ else if (token === "}" || token === "]") {
2694
+ if (this.depth === 1) finishValue(index);
2695
+ this.depth--;
2696
+ if (this.depth === 0) {
2697
+ this.complete = true;
2698
+ if (data.subarray(index + 1).toString("utf8").trim())
2699
+ throw new Error("Extra request record data");
2700
+ break;
2701
+ }
2702
+ } else if (token === ":" && this.depth === 1 && !this.inValue) {
2703
+ this.inValue = true;
2704
+ if (this.key === "seq" || this.key === "model") {
2705
+ this.capture = "value";
2706
+ captureStart = index + 1;
2707
+ }
2708
+ } else if (token === "," && this.depth === 1) finishValue(index);
2709
+ }
2710
+ append(data.length);
2711
+ this.offset += data.length;
2712
+ }
2713
+ finish() {
2714
+ if (!this.complete || this.inString || this.capture)
2715
+ throw new Error("Incomplete request accounting metadata");
2716
+ const { seq, model } = this.fields;
2717
+ if (seq === void 0 && model === void 0) return void 0;
2718
+ if (typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 1)
2719
+ throw new Error("Invalid request accounting sequence");
2720
+ if (model === void 0 || model === null) return { seq };
2721
+ if (typeof model !== "object" || Array.isArray(model))
2722
+ throw new Error("Invalid request accounting model");
2723
+ const { provider, name } = model;
2724
+ if (provider !== void 0 && typeof provider !== "string" || name !== void 0 && typeof name !== "string")
2725
+ throw new Error("Invalid request accounting identity");
2726
+ return { seq, model: { provider, name } };
2727
+ }
2728
+ };
2729
+
2730
+ // src/run-log-usage.ts
2731
+ var MAX_USAGE_LINE_BYTES = 16 * 1024 * 1024;
2732
+ async function* readUsageRecords(file) {
2733
+ let parts = [];
2734
+ let length = 0;
2735
+ let request;
2736
+ for await (const part of readRunLogRecordParts(file)) {
2737
+ if (part.type === "llm.request") {
2738
+ if (part.start) request = new RunLogRequestModel();
2739
+ request?.push(part.data);
2740
+ if (part.end) {
2741
+ const identity = request?.finish();
2742
+ if (identity) yield { type: "request-identity", ...identity };
2743
+ request = void 0;
2744
+ }
2745
+ continue;
2746
+ }
2747
+ if (part.type !== "llm.usage" && part.type !== "llm.response") continue;
2748
+ length += part.data.length;
2749
+ if (length > MAX_USAGE_LINE_BYTES)
2750
+ throw new Error("Usage record is too large to migrate safely");
2751
+ parts.push(part.data);
2752
+ if (part.end) {
2753
+ yield JSON.parse(Buffer.concat(parts, length).toString("utf8"));
2754
+ parts = [];
2755
+ length = 0;
2756
+ }
2757
+ }
2758
+ }
2759
+ async function preserveRunUsage(paths, source) {
2760
+ const destination = usageLogPath(paths, source.datePath, source.runId);
2761
+ const records = /* @__PURE__ */ new Map();
2762
+ const requestModels = /* @__PURE__ */ new Map();
2763
+ try {
2764
+ const stat = await fs10.lstat(destination);
2765
+ if (!stat.isFile()) throw new Error("Invalid usage log");
2766
+ for await (const record2 of readUsageRecords(destination))
2767
+ if (record2.type === "llm.usage")
2768
+ records.set(
2769
+ record2.seq,
2770
+ toUsageRecord(record2, source.sessionId, record2.model)
2771
+ );
2772
+ } catch (error) {
2773
+ if (error.code !== "ENOENT") throw error;
2774
+ }
2775
+ for await (const record2 of readUsageRecords(source.file)) {
2776
+ if (record2.type === "request-identity") {
2777
+ requestModels.set(record2.seq, record2.model);
2778
+ const known = records.get(record2.seq);
2779
+ if (known)
2780
+ records.set(
2781
+ record2.seq,
2782
+ toUsageRecord(known, source.sessionId, {
2783
+ provider: known.model?.provider ?? record2.model?.provider,
2784
+ name: known.model?.name ?? record2.model?.name
2785
+ })
2786
+ );
2787
+ continue;
2788
+ }
2789
+ if (record2.run_id !== source.runId || !Number.isSafeInteger(record2.seq) || record2.seq < 1)
2790
+ throw new Error("Mismatched usage run");
2791
+ if (record2.type === "llm.response" && records.has(record2.seq)) continue;
2792
+ const usage = toUsageRecord(record2, source.sessionId, {
2793
+ provider: records.get(record2.seq)?.model?.provider ?? (record2.type === "llm.usage" ? record2.model?.provider : void 0) ?? requestModels.get(record2.seq)?.provider,
2794
+ name: records.get(record2.seq)?.model?.name ?? (record2.type === "llm.usage" ? record2.model?.name : void 0) ?? requestModels.get(record2.seq)?.name
2795
+ });
2796
+ records.set(usage.seq, usage);
2797
+ }
2798
+ if (records.size === 0) return [];
2799
+ const ordered = [...records.values()].sort((a, b) => a.seq - b.seq).map(
2800
+ (record2) => toUsageRecord(record2, source.sessionId, {
2801
+ provider: record2.model?.provider ?? source.model?.provider,
2802
+ name: record2.model?.name ?? source.model?.name
2803
+ })
2804
+ );
2805
+ await fs10.mkdir(path11.dirname(destination), { recursive: true });
2806
+ const temporary = `${destination}.${process.pid}.${crypto.randomUUID()}.tmp`;
2807
+ try {
2808
+ const lines = ordered.map((record2) => JSON.stringify(record2)).join("\n");
2809
+ await fs10.writeFile(temporary, `${lines}
2810
+ `, { mode: 384 });
2811
+ await fs10.rename(temporary, destination);
2812
+ } finally {
2813
+ await fs10.rm(temporary, { force: true });
2814
+ }
2815
+ return ordered;
2816
+ }
2817
+
2818
+ // src/run-log-retention.ts
2819
+ var RUN_LOG_RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
2820
+ var eligible = (summary, newestMtime, now) => {
2821
+ if (!summary || summary.pinned) return false;
2822
+ const updatedAt = Date.parse(summary.updated_at);
2823
+ if (!Number.isFinite(updatedAt)) return false;
2824
+ return Boolean(summary.archived_at) || now - newestMtime >= RUN_LOG_RETENTION_MS;
2825
+ };
2826
+ function commitCandidate(candidate, compressed, result) {
2827
+ try {
2828
+ const stat = lstatSync4(candidate.file);
2829
+ if (!stat.isFile() || stat.ino !== candidate.ino || stat.dev !== candidate.dev || stat.size !== candidate.size || stat.mtimeMs !== candidate.mtimeMs) {
2830
+ result.skipped++;
2831
+ return;
2832
+ }
2833
+ if (compressed) {
2834
+ const target = candidate.compressed ? candidate.file : `${candidate.file}.gz`;
2835
+ if (candidate.compressed) renameSync2(compressed.temporary, target);
2836
+ else linkSync(compressed.temporary, target);
2837
+ utimesSync(target, stat.atime, stat.mtime);
2838
+ if (!candidate.compressed) unlinkSync3(candidate.file);
2839
+ result.compressed++;
2840
+ result.reclaimed_bytes += Math.max(0, stat.size - compressed.size);
2841
+ } else {
2842
+ unlinkSync3(candidate.file);
2843
+ result.deleted++;
2844
+ result.reclaimed_bytes += stat.size;
2845
+ }
2846
+ } catch (error) {
2847
+ if (error.code !== "ENOENT") result.failed++;
2848
+ }
2849
+ }
2850
+ async function processCandidate(context, candidate, newestMtime, usage) {
2851
+ const { paths, sessions, now, result } = context;
2852
+ let compressed;
2853
+ try {
2854
+ if (!candidate.diagnostic)
2855
+ compressed = await prepareCompressedLog(candidate.file, usage);
2856
+ await sessions.withRetentionGuard(candidate.sessionId, (summary) => {
2857
+ if (hasActiveRunWriter(paths, candidate.sessionId) || !eligible(summary, newestMtime, now)) {
2858
+ result.skipped++;
2859
+ return;
2860
+ }
2861
+ commitCandidate(candidate, compressed, result);
2862
+ });
2863
+ } catch {
2864
+ result.failed++;
2865
+ } finally {
2866
+ if (compressed) await fs11.rm(compressed.temporary, { force: true });
2867
+ }
2868
+ }
2869
+ async function cleanupRunLogs(options) {
2870
+ const { paths, sessions } = options;
2871
+ const now = options.now ?? Date.now();
2872
+ const result = {
2873
+ deleted: 0,
2874
+ compressed: 0,
2875
+ skipped: 0,
2876
+ failed: 0,
2877
+ reclaimed_bytes: 0
2878
+ };
2879
+ const context = { paths, sessions, now, result };
2880
+ if (!await isRegularDirectory(paths.sessionsDir)) return result;
2881
+ const diagnosticsDir = path12.join(paths.sessionsDir, "diagnostics");
2882
+ let relPaths;
2883
+ if (options.sessionId) {
2884
+ try {
2885
+ relPaths = (await sessions.listSessionRuns(options.sessionId)).map(
2886
+ (entry) => entry.rel_path
2887
+ );
2888
+ } catch {
2889
+ relPaths = void 0;
2890
+ }
2891
+ }
2892
+ const candidates = relPaths ? [
2893
+ ...await collectRunLogCandidatesAt(paths.sessionsDir, relPaths),
2894
+ ...await collectRunLogCandidatesAt(diagnosticsDir, relPaths, true)
2895
+ ] : [
2896
+ ...await collectRunLogCandidates(paths.sessionsDir),
2897
+ ...await collectRunLogCandidates(diagnosticsDir, true)
2898
+ ];
2899
+ const groups = /* @__PURE__ */ new Map();
2900
+ for (const candidate of candidates) {
2901
+ if (options.sessionId && candidate.sessionId !== options.sessionId)
2902
+ continue;
2903
+ const group = groups.get(candidate.sessionId) ?? [];
2904
+ group.push(candidate);
2905
+ groups.set(candidate.sessionId, group);
2906
+ }
2907
+ for (const [sessionId, group] of groups) {
2908
+ await removeReusedProcessMarkers(paths, sessionId);
2909
+ if (hasActiveRunWriter(paths, sessionId)) {
2910
+ result.skipped += group.length;
2911
+ continue;
2912
+ }
2913
+ const summary = await sessions.getSummary(sessionId);
2914
+ const runMtimes = /* @__PURE__ */ new Map();
2915
+ for (const candidate of group)
2916
+ runMtimes.set(
2917
+ candidate.runId,
2918
+ Math.max(runMtimes.get(candidate.runId) ?? 0, candidate.mtimeMs)
2919
+ );
2920
+ const selected = group.filter(
2921
+ (candidate) => eligible(
2922
+ summary,
2923
+ runMtimes.get(candidate.runId) ?? candidate.mtimeMs,
2924
+ now
2925
+ )
2926
+ );
2927
+ result.skipped += group.length - selected.length;
2928
+ if (selected.length === 0) continue;
2929
+ try {
2930
+ const snapshot = await fs11.lstat(
2931
+ path12.join(paths.sessionsDir, "messages", `${sessionId}.jsonl`)
2932
+ );
2933
+ if (!snapshot.isFile() || snapshot.size === 0) {
2934
+ result.skipped += selected.length;
2935
+ continue;
2936
+ }
2937
+ const usageByRun = /* @__PURE__ */ new Map();
2938
+ for (const candidate of selected)
2939
+ usageByRun.set(
2940
+ candidate.runId,
2941
+ await preserveRunUsage(paths, candidate)
2942
+ );
2943
+ for (const candidate of selected)
2944
+ await processCandidate(
2945
+ context,
2946
+ candidate,
2947
+ runMtimes.get(candidate.runId) ?? candidate.mtimeMs,
2948
+ usageByRun.get(candidate.runId) ?? []
2949
+ );
2950
+ } catch (error) {
2951
+ if (error.code === "ENOENT")
2952
+ result.skipped += selected.length;
2953
+ else result.failed += selected.length;
2954
+ }
2955
+ }
2956
+ return result;
2957
+ }
2958
+
2959
+ // src/service.ts
2960
+ var StoragePathServiceImpl = class {
2961
+ resolvePaths(options = {}) {
2962
+ return resolveStoragePaths(options);
2963
+ }
2964
+ };
2965
+
1168
2966
  // src/task-registry.ts
1169
- import { promises as fs5 } from "fs";
1170
- import path7 from "path";
2967
+ import { promises as fs12 } from "fs";
2968
+ import path13 from "path";
1171
2969
  var TASKS_DIRNAME = "tasks";
1172
2970
  var sortByUpdatedDesc = (tasks) => [...tasks].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
1173
2971
  var toShellKeyBase = (label2) => {
@@ -1225,14 +3023,14 @@ var assignMissingShellKeys = (tasks) => {
1225
3023
  return updates;
1226
3024
  };
1227
3025
  var atomicWrite = async (filePath, payload) => {
1228
- const dir = path7.dirname(filePath);
1229
- const base = path7.basename(filePath);
1230
- const tmp = path7.join(
3026
+ const dir = path13.dirname(filePath);
3027
+ const base = path13.basename(filePath);
3028
+ const tmp = path13.join(
1231
3029
  dir,
1232
3030
  `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
1233
3031
  );
1234
- await fs5.writeFile(tmp, payload, "utf8");
1235
- await fs5.rename(tmp, filePath);
3032
+ await fs12.writeFile(tmp, payload, "utf8");
3033
+ await fs12.rename(tmp, filePath);
1236
3034
  };
1237
3035
  var isTaskState = (value) => value === "queued" || value === "running" || value === "completed" || value === "failed" || value === "cancelled";
1238
3036
  var isTaskKind = (value) => value === "shell" || value === "subagent";
@@ -1343,7 +3141,7 @@ var normalizeTaskRecord = (value) => {
1343
3141
  };
1344
3142
  var readTaskFile = async (filePath) => {
1345
3143
  try {
1346
- const raw = await fs5.readFile(filePath, "utf8");
3144
+ const raw = await fs12.readFile(filePath, "utf8");
1347
3145
  return normalizeTaskRecord(JSON.parse(raw));
1348
3146
  } catch {
1349
3147
  return null;
@@ -1358,19 +3156,19 @@ var TaskRegistryStore = class {
1358
3156
  return;
1359
3157
  }
1360
3158
  const root = resolveStoragePaths().root;
1361
- this.tasksDir = path7.join(root, TASKS_DIRNAME);
3159
+ this.tasksDir = path13.join(root, TASKS_DIRNAME);
1362
3160
  }
1363
3161
  async ensureDir() {
1364
- await fs5.mkdir(this.tasksDir, { recursive: true });
3162
+ await fs12.mkdir(this.tasksDir, { recursive: true });
1365
3163
  }
1366
3164
  taskPath(taskId) {
1367
- return path7.join(this.tasksDir, taskFileName(taskId));
3165
+ return path13.join(this.tasksDir, taskFileName(taskId));
1368
3166
  }
1369
3167
  async list() {
1370
3168
  await this.ensureDir();
1371
- const entries = await fs5.readdir(this.tasksDir, { withFileTypes: true });
3169
+ const entries2 = await fs12.readdir(this.tasksDir, { withFileTypes: true });
1372
3170
  const tasks = (await Promise.all(
1373
- entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(path7.join(this.tasksDir, entry.name)))
3171
+ entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(path13.join(this.tasksDir, entry.name)))
1374
3172
  )).filter((task) => task !== null);
1375
3173
  const keyBackfills = assignMissingShellKeys(tasks);
1376
3174
  if (keyBackfills.length > 0) {
@@ -1412,8 +3210,8 @@ var TaskRegistryStore = class {
1412
3210
  };
1413
3211
 
1414
3212
  // src/tool-output-cache.ts
1415
- import { promises as fs6 } from "fs";
1416
- import path8 from "path";
3213
+ import { promises as fs13 } from "fs";
3214
+ import path14 from "path";
1417
3215
  var DEFAULT_MAX_MATCHES = 50;
1418
3216
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
1419
3217
  var DEFAULT_MAX_READ_BYTES = 64 * 1024;
@@ -1525,15 +3323,15 @@ var ToolOutputCacheStoreImpl = class {
1525
3323
  async save(record2) {
1526
3324
  const refId = normalizeRefId(record2.tool_call_id);
1527
3325
  const filePath = this.resolvePath(refId);
1528
- await fs6.mkdir(this.baseDir, { recursive: true });
1529
- await fs6.writeFile(filePath, record2.content, "utf8");
3326
+ await fs13.mkdir(this.baseDir, { recursive: true });
3327
+ await fs13.writeFile(filePath, record2.content, "utf8");
1530
3328
  const byteSize = Buffer.byteLength(record2.content, "utf8");
1531
3329
  const lineCount = record2.content.split(/\r?\n/).length;
1532
3330
  return { id: refId, byte_size: byteSize, line_count: lineCount };
1533
3331
  }
1534
3332
  async read(refId, options = {}) {
1535
3333
  const filePath = this.resolvePath(refId);
1536
- const content = await fs6.readFile(filePath, "utf8");
3334
+ const content = await fs13.readFile(filePath, "utf8");
1537
3335
  const lines = content.split(/\r?\n/);
1538
3336
  const offset = options.offset ?? 0;
1539
3337
  const limit = options.limit ?? lines.length;
@@ -1592,7 +3390,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
1592
3390
  }
1593
3391
  async readTail(refId, options) {
1594
3392
  const filePath = this.resolvePath(refId);
1595
- const content = await fs6.readFile(filePath, "utf8");
3393
+ const content = await fs13.readFile(filePath, "utf8");
1596
3394
  const lines = content.split(/\r?\n/);
1597
3395
  const tailLines = Math.max(1, Math.trunc(options.tail_lines));
1598
3396
  const start = Math.max(0, lines.length - tailLines);
@@ -1604,7 +3402,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
1604
3402
  }
1605
3403
  async readLine(refId, options) {
1606
3404
  const filePath = this.resolvePath(refId);
1607
- const content = await fs6.readFile(filePath, "utf8");
3405
+ const content = await fs13.readFile(filePath, "utf8");
1608
3406
  const lines = content.split(/\r?\n/);
1609
3407
  const lineIndex = options.line_number - 1;
1610
3408
  if (lineIndex < 0 || lineIndex >= lines.length) {
@@ -1645,7 +3443,7 @@ tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${opti
1645
3443
  }
1646
3444
  async grep(refId, options) {
1647
3445
  const filePath = this.resolvePath(refId);
1648
- const content = await fs6.readFile(filePath, "utf8");
3446
+ const content = await fs13.readFile(filePath, "utf8");
1649
3447
  const lines = content.split(/\r?\n/);
1650
3448
  const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
1651
3449
  const before = Math.max(0, options.before ?? 0);
@@ -1696,21 +3494,34 @@ ${snippet}`;
1696
3494
  return output;
1697
3495
  }
1698
3496
  resolvePath(refId) {
1699
- return path8.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
3497
+ return path14.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
1700
3498
  }
1701
3499
  };
1702
3500
  export {
3501
+ FileAttachmentStore,
1703
3502
  IMAGE_MAX_BYTES,
1704
3503
  ImageArtifactStore,
1705
3504
  McpAuthStore,
1706
3505
  ProjectsPolicyStore,
3506
+ RUN_LOG_RETENTION_MS,
1707
3507
  RunEventStoreFactoryImpl,
3508
+ SessionGoalStore,
1708
3509
  SessionStateStoreImpl,
1709
3510
  SessionStoreWriterImpl,
1710
3511
  StoragePathServiceImpl,
1711
3512
  TaskRegistryStore,
1712
3513
  ToolOutputCacheStoreImpl,
3514
+ cleanupRunLogs,
3515
+ createAttachmentId,
3516
+ detectImageAttachmentType,
1713
3517
  ensureStorageDirs,
3518
+ getProcessIdentity,
3519
+ isAttachmentId,
3520
+ readRunLogLines,
3521
+ resolveIndexedRunLog,
3522
+ resolveRunLogPath,
1714
3523
  resolveStoragePaths,
3524
+ scanSessionRunLogs,
3525
+ validateImageAttachment,
1715
3526
  validateImagePng
1716
3527
  };