@codelia/storage 0.1.83 → 0.1.85

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