@codelia/storage 0.1.82 → 0.1.84

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