@codelia/storage 0.1.80 → 0.1.82

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,6 +30,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ IMAGE_MAX_BYTES: () => IMAGE_MAX_BYTES,
34
+ ImageArtifactStore: () => ImageArtifactStore,
33
35
  McpAuthStore: () => McpAuthStore,
34
36
  ProjectsPolicyStore: () => ProjectsPolicyStore,
35
37
  RunEventStoreFactoryImpl: () => RunEventStoreFactoryImpl,
@@ -39,17 +41,434 @@ __export(index_exports, {
39
41
  TaskRegistryStore: () => TaskRegistryStore,
40
42
  ToolOutputCacheStoreImpl: () => ToolOutputCacheStoreImpl,
41
43
  ensureStorageDirs: () => ensureStorageDirs,
42
- resolveStoragePaths: () => resolveStoragePaths
44
+ resolveStoragePaths: () => resolveStoragePaths,
45
+ validateImagePng: () => validateImagePng
43
46
  });
44
47
  module.exports = __toCommonJS(index_exports);
45
48
 
46
- // src/mcp-auth-store.ts
49
+ // 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);
53
+
54
+ // src/image-attachment.ts
55
+ var import_image_size = require("image-size");
56
+
57
+ // src/image-png.ts
58
+ var import_node_util = require("util");
59
+ var import_node_zlib = require("zlib");
60
+ var IMAGE_MAX_BYTES = 8 * 1024 * 1024;
61
+ var inflateAsync = (0, import_node_util.promisify)(import_node_zlib.inflate);
62
+ var crcTable = Uint32Array.from({ length: 256 }, (_, n) => {
63
+ let c = n;
64
+ for (let i = 0; i < 8; i++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
65
+ return c >>> 0;
66
+ });
67
+ var crc32 = (data) => {
68
+ let crc = 4294967295;
69
+ for (const b of data) crc = (crcTable[(crc ^ b) & 255] ?? 0) ^ crc >>> 8;
70
+ return (crc ^ 4294967295) >>> 0;
71
+ };
72
+ var invalid = () => {
73
+ throw new Error(
74
+ "Invalid or unsupported image: require a complete non-interlaced 8-bit PNG, <=8 MiB, <=4096 per side and <=16 MP."
75
+ );
76
+ };
77
+ async function validateImagePng(bytes) {
78
+ if (bytes.length < 57 || bytes.length > IMAGE_MAX_BYTES || !bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
79
+ invalid();
80
+ let offset = 8;
81
+ let width = 0;
82
+ let height = 0;
83
+ let channels = 0;
84
+ let ended = false;
85
+ let dataEnded = false;
86
+ let palette = false;
87
+ let color = -1;
88
+ const data = [];
89
+ while (offset + 12 <= bytes.length) {
90
+ const len = bytes.readUInt32BE(offset);
91
+ if (offset + 12 + len > bytes.length) invalid();
92
+ const type = bytes.toString("ascii", offset + 4, offset + 8);
93
+ const payload = bytes.subarray(offset + 8, offset + 8 + len);
94
+ if (crc32(bytes.subarray(offset + 4, offset + 8 + len)) !== bytes.readUInt32BE(offset + 8 + len))
95
+ invalid();
96
+ if (offset === 8 && type !== "IHDR") invalid();
97
+ if (type === "IHDR") {
98
+ if (offset !== 8 || len !== 13) invalid();
99
+ width = payload.readUInt32BE(0);
100
+ height = payload.readUInt32BE(4);
101
+ color = payload[9] ?? -1;
102
+ 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)
104
+ invalid();
105
+ } else if (type === "IDAT") {
106
+ if (dataEnded || color === 3 && !palette) invalid();
107
+ data.push(payload);
108
+ } else if (type === "IEND") {
109
+ if (len !== 0 || !data.length) invalid();
110
+ ended = true;
111
+ offset += 12;
112
+ break;
113
+ } else {
114
+ if (data.length) dataEnded = true;
115
+ if (type === "PLTE") {
116
+ if (palette || data.length || len === 0 || len > 768 || len % 3)
117
+ invalid();
118
+ palette = true;
119
+ } else if (!/^[a-z][A-Za-z]{3}$/.test(type) || type === "acTL") invalid();
120
+ }
121
+ offset += 12 + len;
122
+ }
123
+ if (!ended || offset !== bytes.length) invalid();
124
+ const rowBytes = width * channels + 1;
125
+ try {
126
+ const raw = await inflateAsync(Buffer.concat(data), {
127
+ maxOutputLength: rowBytes * height
128
+ });
129
+ if (raw.length !== rowBytes * height) invalid();
130
+ for (let row = 0; row < height; row++)
131
+ if ((raw[row * rowBytes] ?? 255) > 4) invalid();
132
+ } catch {
133
+ invalid();
134
+ }
135
+ return { width, height };
136
+ }
137
+
138
+ // src/image-attachment.ts
139
+ 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");
148
+ try {
149
+ const { width, height } = (0, import_image_size.imageSize)(bytes);
150
+ if (!width || !height || width > 4096 || height > 4096 || width * height > 16e6)
151
+ throw new Error("dimensions");
152
+ return { width, height };
153
+ } catch {
154
+ throw new Error(
155
+ "Invalid image attachment: unreadable header or exceeds 4096px/16 MP"
156
+ );
157
+ }
158
+ }
159
+ var imageOriginalFilename = (mediaType) => `original.${{ "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif" }[mediaType]}`;
160
+
161
+ // src/image-files.ts
162
+ var import_node_crypto = require("crypto");
47
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
+ // src/image-metadata.ts
195
+ var import_shared_types = require("@codelia/shared-types");
196
+ var record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
197
+ var label = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && [...value].every((c) => c.charCodeAt(0) >= 32 && c.charCodeAt(0) !== 127);
198
+ var id = (value) => typeof value === "string" && /^codelia-image-[0-9a-f-]{36}$/.test(value);
199
+ var positive = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
200
+ function parseImageMetadata(value) {
201
+ if (!record(value) || !id(value.artifact_id) || typeof value.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(value.sha256) || !["image/png", "image/jpeg", "image/webp", "image/gif"].includes(
202
+ String(value.media_type)
203
+ ) || !positive(value.byte_size) || !positive(value.width) || !positive(value.height) || !label(value.created_at, 40) || !Number.isFinite(Date.parse(value.created_at)))
204
+ throw new Error("Invalid image artifact metadata");
205
+ if (value.kind === "attachment") {
206
+ if ([
207
+ "provider",
208
+ "requested_model",
209
+ "endpoint",
210
+ "usage",
211
+ "parent_artifact_ids"
212
+ ].some((key) => key in value))
213
+ throw new Error("Invalid attachment provenance");
214
+ return {
215
+ kind: "attachment",
216
+ artifact_id: value.artifact_id,
217
+ sha256: value.sha256,
218
+ media_type: value.media_type,
219
+ byte_size: value.byte_size,
220
+ width: value.width,
221
+ height: value.height,
222
+ created_at: value.created_at
223
+ };
224
+ }
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))
226
+ throw new Error("Invalid image artifact metadata");
227
+ let usage;
228
+ if (value.usage !== void 0) {
229
+ if (!record(value.usage)) throw new Error("Invalid image usage metadata");
230
+ usage = {};
231
+ for (const key of ["input_tokens", "output_tokens", "cost_usd"]) {
232
+ const number = value.usage[key];
233
+ if (number === void 0) continue;
234
+ if (typeof number !== "number" || !Number.isFinite(number) || number < 0)
235
+ throw new Error("Invalid image usage metadata");
236
+ usage[key] = number;
237
+ }
238
+ }
239
+ return {
240
+ artifact_id: value.artifact_id,
241
+ sha256: value.sha256,
242
+ media_type: value.media_type,
243
+ byte_size: value.byte_size,
244
+ width: value.width,
245
+ height: value.height,
246
+ created_at: value.created_at,
247
+ provider: value.provider,
248
+ requested_model: value.requested_model,
249
+ endpoint: value.endpoint,
250
+ parent_artifact_ids: value.parent_artifact_ids,
251
+ ...value.effective_model !== void 0 ? { effective_model: value.effective_model } : {},
252
+ ...usage ? { usage } : {}
253
+ };
254
+ }
255
+
256
+ // 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);
260
+ var import_shared_types2 = require("@codelia/shared-types");
261
+ var import_image_size2 = require("image-size");
262
+ var VERSION = "jpeg-q90-444-v1";
263
+ var directory = (root) => import_node_path.default.join(root, VERSION);
264
+ var errorCode = (error) => error && typeof error === "object" && "code" in error ? error.code : void 0;
265
+ async function readModelView(root, original, expected) {
266
+ if (expected !== void 0 && !(0, import_shared_types2.isImageModelView)(expected))
267
+ throw new Error("Invalid image model view");
268
+ const dir = directory(root);
269
+ if (!(await (0, import_promises2.lstat)(dir)).isDirectory())
270
+ throw new Error("Invalid model view directory");
271
+ const record2 = JSON.parse(
272
+ (await readImageFileBounded(import_node_path.default.join(dir, "metadata.json"), 4096)).toString()
273
+ );
274
+ if (!record2 || record2.original_sha256 !== original.sha256 || !(0, import_shared_types2.isImageModelView)(record2.view))
275
+ throw new Error("Invalid model view metadata");
276
+ const view = record2.view;
277
+ if (expected && (view.sha256 !== expected.sha256 || view.byte_size !== expected.byte_size))
278
+ throw new Error("Image model view reference mismatch");
279
+ const bytes = await readImageFileBounded(
280
+ import_node_path.default.join(dir, "view.jpg"),
281
+ 8 * 1024 * 1024
282
+ );
283
+ const dims = (0, import_image_size2.imageSize)(bytes);
284
+ 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)
285
+ throw new Error("Corrupt image model view");
286
+ return { view, bytes };
287
+ }
288
+ async function prepareModelView(root, original, bytes) {
289
+ if (original.kind === "attachment" || bytes.length < 256 * 1024)
290
+ return void 0;
291
+ let exists = true;
292
+ try {
293
+ await (0, import_promises2.lstat)(directory(root));
294
+ } catch (error) {
295
+ if (errorCode(error) !== "ENOENT") throw error;
296
+ exists = false;
297
+ }
298
+ if (exists) return (await readModelView(root, original)).view;
299
+ const { default: sharp } = await import("sharp");
300
+ const pipeline = sharp(bytes, {
301
+ limitInputPixels: 16e6,
302
+ failOn: "warning"
303
+ }).timeout({ seconds: 15 });
304
+ const metadata = await pipeline.metadata();
305
+ if ((metadata.pages ?? 1) > 1 || metadata.hasAlpha && !(await pipeline.clone().stats()).isOpaque)
306
+ return void 0;
307
+ const jpeg = await pipeline.jpeg({ quality: 90, chromaSubsampling: "4:4:4" }).toBuffer();
308
+ if (jpeg.length >= bytes.length) return void 0;
309
+ const view = {
310
+ version: VERSION,
311
+ media_type: "image/jpeg",
312
+ sha256: imageHash(jpeg),
313
+ byte_size: jpeg.length
314
+ };
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 });
317
+ try {
318
+ await (0, import_promises2.writeFile)(import_node_path.default.join(temporary, "view.jpg"), jpeg, {
319
+ flag: "wx",
320
+ mode: 384
321
+ });
322
+ await (0, import_promises2.writeFile)(
323
+ import_node_path.default.join(temporary, "metadata.json"),
324
+ JSON.stringify({ original_sha256: original.sha256, view }),
325
+ { flag: "wx", mode: 384 }
326
+ );
327
+ try {
328
+ await (0, import_promises2.rename)(temporary, directory(root));
329
+ } catch (error) {
330
+ if (!["EEXIST", "ENOTEMPTY"].includes(String(errorCode(error))))
331
+ throw error;
332
+ }
333
+ return (await readModelView(root, original)).view;
334
+ } finally {
335
+ await (0, import_promises2.rm)(temporary, { recursive: true, force: true });
336
+ }
337
+ }
338
+
339
+ // src/image-artifacts.ts
340
+ var ID = /^codelia-image-[0-9a-f-]{36}$/;
341
+ var ImageArtifactStore = class {
342
+ constructor(root) {
343
+ this.root = root;
344
+ }
345
+ root;
346
+ async save(bytes, provenance) {
347
+ const dimensions = await validateImagePng(bytes);
348
+ const artifact_id = `codelia-image-${(0, import_node_crypto3.randomUUID)()}`;
349
+ const metadata = parseImageMetadata({
350
+ ...provenance,
351
+ ...dimensions,
352
+ artifact_id,
353
+ sha256: imageHash(bytes),
354
+ media_type: "image/png",
355
+ byte_size: bytes.length,
356
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
357
+ });
358
+ if (metadata.kind === "attachment")
359
+ throw new Error("Invalid generation provenance");
360
+ await this.persist(bytes, metadata);
361
+ return metadata;
362
+ }
363
+ async saveAttachment(bytes, mediaType) {
364
+ const dimensions = validateImageAttachment(bytes, mediaType);
365
+ const metadata = {
366
+ kind: "attachment",
367
+ artifact_id: `codelia-image-${(0, import_node_crypto3.randomUUID)()}`,
368
+ sha256: imageHash(bytes),
369
+ media_type: mediaType,
370
+ byte_size: bytes.length,
371
+ ...dimensions,
372
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
373
+ };
374
+ await this.persist(bytes, metadata);
375
+ return metadata;
376
+ }
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 });
381
+ try {
382
+ await (0, import_promises3.writeFile)(
383
+ import_node_path2.default.join(temporary, imageOriginalFilename(metadata.media_type)),
384
+ bytes,
385
+ {
386
+ flag: "wx",
387
+ mode: 384
388
+ }
389
+ );
390
+ await (0, import_promises3.writeFile)(
391
+ import_node_path2.default.join(temporary, "metadata.json"),
392
+ JSON.stringify(metadata),
393
+ { flag: "wx", mode: 384 }
394
+ );
395
+ await (0, import_promises3.rename)(temporary, import_node_path2.default.join(this.root, metadata.artifact_id));
396
+ } catch (error) {
397
+ await (0, import_promises3.rm)(temporary, { recursive: true, force: true });
398
+ throw error;
399
+ }
400
+ }
401
+ async read(artifactId) {
402
+ if (!ID.test(artifactId)) throw new Error("Invalid image artifact id");
403
+ try {
404
+ const dir = import_node_path2.default.join(this.root, artifactId);
405
+ if (!(await (0, import_promises3.lstat)(dir)).isDirectory())
406
+ 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
+ )
411
+ );
412
+ const bytes = await readImageFileBounded(
413
+ import_node_path2.default.join(dir, imageOriginalFilename(metadata.media_type)),
414
+ IMAGE_MAX_BYTES
415
+ );
416
+ const dims = metadata.kind === "attachment" ? validateImageAttachment(bytes, metadata.media_type) : await validateImagePng(bytes);
417
+ if (metadata.artifact_id !== artifactId || metadata.byte_size !== bytes.length || metadata.sha256 !== imageHash(bytes) || metadata.width !== dims.width || metadata.height !== dims.height)
418
+ throw new Error("Invalid artifact metadata");
419
+ return { metadata, bytes };
420
+ } catch {
421
+ throw new Error(
422
+ "Image artifact missing, corrupt, or inaccessible in this workspace"
423
+ );
424
+ }
425
+ }
426
+ /** Prepare a new history reference, never upgrade an already persisted reference. */
427
+ async modelReference(artifactId, original = false) {
428
+ const { metadata, bytes } = await this.read(artifactId);
429
+ const { artifact_id, sha256, media_type, byte_size, width, height } = metadata;
430
+ const ref = {
431
+ artifact_id,
432
+ sha256,
433
+ media_type,
434
+ byte_size,
435
+ width,
436
+ height
437
+ };
438
+ if (original) return ref;
439
+ const model_view = await prepareModelView(
440
+ import_node_path2.default.join(this.root, artifactId),
441
+ metadata,
442
+ bytes
443
+ );
444
+ return model_view ? { ...ref, model_view } : ref;
445
+ }
446
+ async resolve(ref) {
447
+ const { metadata, bytes } = await this.read(ref.artifact_id);
448
+ 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
+ throw new Error("Image artifact reference mismatch");
450
+ const input = ref.model_view !== void 0 ? await readModelView(
451
+ import_node_path2.default.join(this.root, ref.artifact_id),
452
+ metadata,
453
+ ref.model_view
454
+ ) : { bytes, view: metadata };
455
+ return {
456
+ type: "image_url",
457
+ image_url: {
458
+ url: `data:${input.view.media_type};base64,${input.bytes.toString("base64")}`,
459
+ media_type: input.view.media_type
460
+ }
461
+ };
462
+ }
463
+ };
464
+
465
+ // src/mcp-auth-store.ts
466
+ var import_node_fs2 = require("fs");
48
467
 
49
468
  // src/paths.ts
50
- var import_promises = require("fs/promises");
469
+ var import_promises4 = require("fs/promises");
51
470
  var import_node_os = __toESM(require("os"), 1);
52
- var import_node_path = __toESM(require("path"), 1);
471
+ var import_node_path3 = __toESM(require("path"), 1);
53
472
  var DEFAULT_ROOT_DIR = ".codelia";
54
473
  var LAYOUT_ENV = "CODELIA_LAYOUT";
55
474
  var XDG_DIR_NAME = "codelia";
@@ -74,11 +493,11 @@ function resolveStoragePaths(options = {}) {
74
493
  }
75
494
  async function ensureStorageDirs(paths) {
76
495
  await Promise.all([
77
- (0, import_promises.mkdir)(paths.configDir, { recursive: true }),
78
- (0, import_promises.mkdir)(paths.cacheDir, { recursive: true }),
79
- (0, import_promises.mkdir)(paths.toolOutputCacheDir, { recursive: true }),
80
- (0, import_promises.mkdir)(paths.sessionsDir, { recursive: true }),
81
- (0, import_promises.mkdir)(paths.logsDir, { recursive: true })
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 })
82
501
  ]);
83
502
  }
84
503
  function normalizeLayout(value) {
@@ -86,46 +505,46 @@ function normalizeLayout(value) {
86
505
  return "home";
87
506
  }
88
507
  function defaultHomeRoot() {
89
- return import_node_path.default.join(import_node_os.default.homedir(), DEFAULT_ROOT_DIR);
508
+ return import_node_path3.default.join(import_node_os.default.homedir(), DEFAULT_ROOT_DIR);
90
509
  }
91
510
  function buildHomeLayout(root) {
92
511
  const configDir = root;
93
512
  return {
94
513
  root,
95
514
  configDir,
96
- configFile: import_node_path.default.join(configDir, CONFIG_FILENAME),
97
- authFile: import_node_path.default.join(configDir, AUTH_FILENAME),
98
- mcpAuthFile: import_node_path.default.join(configDir, MCP_AUTH_FILENAME),
99
- projectsFile: import_node_path.default.join(configDir, PROJECTS_FILENAME),
100
- cacheDir: import_node_path.default.join(root, CACHE_DIRNAME),
101
- toolOutputCacheDir: import_node_path.default.join(
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(
102
521
  root,
103
522
  CACHE_DIRNAME,
104
523
  TOOL_OUTPUT_CACHE_DIRNAME
105
524
  ),
106
- sessionsDir: import_node_path.default.join(root, SESSIONS_DIRNAME),
107
- logsDir: import_node_path.default.join(root, LOGS_DIRNAME)
525
+ sessionsDir: import_node_path3.default.join(root, SESSIONS_DIRNAME),
526
+ logsDir: import_node_path3.default.join(root, LOGS_DIRNAME)
108
527
  };
109
528
  }
110
529
  function buildXdgLayout() {
111
530
  const home = import_node_os.default.homedir();
112
- const configRoot = process.env.XDG_CONFIG_HOME ?? import_node_path.default.join(home, ".config");
113
- const cacheRoot = process.env.XDG_CACHE_HOME ?? import_node_path.default.join(home, ".cache");
114
- const stateRoot = process.env.XDG_STATE_HOME ?? import_node_path.default.join(home, ".local", "state");
115
- const configDir = import_node_path.default.join(configRoot, XDG_DIR_NAME);
116
- const cacheDir = import_node_path.default.join(cacheRoot, XDG_DIR_NAME);
117
- const stateDir = import_node_path.default.join(stateRoot, XDG_DIR_NAME);
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);
118
537
  return {
119
538
  root: stateDir,
120
539
  configDir,
121
- configFile: import_node_path.default.join(configDir, CONFIG_FILENAME),
122
- authFile: import_node_path.default.join(configDir, AUTH_FILENAME),
123
- mcpAuthFile: import_node_path.default.join(configDir, MCP_AUTH_FILENAME),
124
- projectsFile: import_node_path.default.join(configDir, PROJECTS_FILENAME),
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),
125
544
  cacheDir,
126
- toolOutputCacheDir: import_node_path.default.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
127
- sessionsDir: import_node_path.default.join(stateDir, SESSIONS_DIRNAME),
128
- logsDir: import_node_path.default.join(stateDir, LOGS_DIRNAME)
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)
129
548
  };
130
549
  }
131
550
 
@@ -155,17 +574,17 @@ var McpAuthStore = class {
155
574
  }
156
575
  async load() {
157
576
  try {
158
- const text = await import_node_fs.promises.readFile(this.paths.mcpAuthFile, "utf8");
577
+ const text = await import_node_fs2.promises.readFile(this.paths.mcpAuthFile, "utf8");
159
578
  const parsed = JSON.parse(text);
160
579
  if (!isRecord(parsed) || parsed.version !== MCP_AUTH_VERSION) {
161
580
  throw new Error("mcp-auth.json has unsupported version");
162
581
  }
163
582
  const serversRaw = isRecord(parsed.servers) ? parsed.servers : {};
164
583
  const servers = {};
165
- for (const [id, entry] of Object.entries(serversRaw)) {
584
+ for (const [id2, entry] of Object.entries(serversRaw)) {
166
585
  const normalized = normalizeTokens(entry);
167
586
  if (normalized) {
168
- servers[id] = normalized;
587
+ servers[id2] = normalized;
169
588
  }
170
589
  }
171
590
  return {
@@ -183,21 +602,21 @@ var McpAuthStore = class {
183
602
  async save(auth) {
184
603
  await ensureStorageDirs(this.paths);
185
604
  const data = JSON.stringify(auth, null, 2);
186
- await import_node_fs.promises.writeFile(this.paths.mcpAuthFile, data, { mode: 384 });
605
+ await import_node_fs2.promises.writeFile(this.paths.mcpAuthFile, data, { mode: 384 });
187
606
  try {
188
- await import_node_fs.promises.chmod(this.paths.mcpAuthFile, 384);
607
+ await import_node_fs2.promises.chmod(this.paths.mcpAuthFile, 384);
189
608
  } catch {
190
609
  }
191
610
  }
192
611
  };
193
612
 
194
613
  // src/projects-store.ts
195
- var import_node_fs2 = require("fs");
196
- var import_node_path2 = __toESM(require("path"), 1);
197
- var import_shared_types = require("@codelia/shared-types");
614
+ var import_node_fs3 = require("fs");
615
+ var import_node_path4 = __toESM(require("path"), 1);
616
+ var import_shared_types3 = require("@codelia/shared-types");
198
617
  var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
199
618
  var parseApprovalModeField = (fieldPath, value) => {
200
- const parsed = (0, import_shared_types.parseApprovalMode)(value);
619
+ const parsed = (0, import_shared_types3.parseApprovalMode)(value);
201
620
  if (!parsed) {
202
621
  throw new Error(`${fieldPath} is invalid`);
203
622
  }
@@ -251,16 +670,16 @@ var normalizeProjectsPolicyFile = (value) => {
251
670
  return normalized;
252
671
  };
253
672
  var atomicWriteFile = async (filePath, content) => {
254
- const dirPath = import_node_path2.default.dirname(filePath);
255
- const fileName = import_node_path2.default.basename(filePath);
256
- const tempPath = import_node_path2.default.join(
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(
257
676
  dirPath,
258
677
  `.${fileName}.${process.pid}.${Date.now()}.tmp`
259
678
  );
260
- await import_node_fs2.promises.writeFile(tempPath, content, { mode: 384 });
261
- await import_node_fs2.promises.rename(tempPath, filePath);
679
+ await import_node_fs3.promises.writeFile(tempPath, content, { mode: 384 });
680
+ await import_node_fs3.promises.rename(tempPath, filePath);
262
681
  if (process.platform !== "win32") {
263
- await import_node_fs2.promises.chmod(filePath, 384);
682
+ await import_node_fs3.promises.chmod(filePath, 384);
264
683
  }
265
684
  };
266
685
  var ProjectsPolicyStore = class {
@@ -273,7 +692,7 @@ var ProjectsPolicyStore = class {
273
692
  }
274
693
  async load() {
275
694
  try {
276
- const raw = await import_node_fs2.promises.readFile(this.paths.projectsFile, "utf8");
695
+ const raw = await import_node_fs3.promises.readFile(this.paths.projectsFile, "utf8");
277
696
  const parsed = JSON.parse(raw);
278
697
  return normalizeProjectsPolicyFile(parsed);
279
698
  } catch (error) {
@@ -295,8 +714,8 @@ var ProjectsPolicyStore = class {
295
714
  };
296
715
 
297
716
  // src/session-store.ts
298
- var import_node_fs3 = require("fs");
299
- var import_node_path3 = __toESM(require("path"), 1);
717
+ var import_node_fs4 = require("fs");
718
+ var import_node_path5 = __toESM(require("path"), 1);
300
719
  var pad2 = (value) => String(value).padStart(2, "0");
301
720
  var resolveDateParts = (startedAt) => {
302
721
  const parsed = new Date(startedAt);
@@ -314,27 +733,27 @@ var SessionStoreWriterImpl = class {
314
733
  constructor(options) {
315
734
  const paths = options.paths ?? resolveStoragePaths();
316
735
  const parts = resolveDateParts(options.startedAt);
317
- const baseDir = import_node_path3.default.join(
736
+ const baseDir = import_node_path5.default.join(
318
737
  paths.sessionsDir,
319
738
  parts.year,
320
739
  parts.month,
321
740
  parts.day
322
741
  );
323
- this.filePath = import_node_path3.default.join(baseDir, `${options.runId}.jsonl`);
324
- this.ensureDir = import_node_fs3.promises.mkdir(baseDir, { recursive: true }).then(() => {
742
+ this.filePath = import_node_path5.default.join(baseDir, `${options.runId}.jsonl`);
743
+ this.ensureDir = import_node_fs4.promises.mkdir(baseDir, { recursive: true }).then(() => {
325
744
  });
326
745
  }
327
- append(record) {
746
+ append(record2) {
328
747
  let line;
329
748
  try {
330
- line = `${JSON.stringify(record)}
749
+ line = `${JSON.stringify(record2)}
331
750
  `;
332
751
  } catch (error) {
333
752
  return Promise.reject(error);
334
753
  }
335
754
  const write = this.writeChain.then(async () => {
336
755
  await this.ensureDir;
337
- await import_node_fs3.promises.appendFile(this.filePath, line, "utf8");
756
+ await import_node_fs4.promises.appendFile(this.filePath, line, "utf8");
338
757
  });
339
758
  this.writeChain = write.catch(() => {
340
759
  });
@@ -360,16 +779,16 @@ var StoragePathServiceImpl = class {
360
779
  };
361
780
 
362
781
  // src/session-state.ts
363
- var import_node_fs4 = require("fs");
364
- var import_node_path4 = __toESM(require("path"), 1);
782
+ var import_node_fs5 = require("fs");
783
+ var import_node_path6 = __toESM(require("path"), 1);
365
784
  var import_core = require("@codelia/core");
366
785
  var LEGACY_STATE_DIRNAME = "state";
367
786
  var MESSAGES_DIRNAME = "messages";
368
787
  var STATE_DB_FILENAME = "state.db";
369
788
  var SESSION_WORKSPACE_ROOT_META_KEY = "codelia_workspace_root";
370
- var resolveLegacyStateDir = (paths) => import_node_path4.default.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
371
- var resolveMessagesDir = (paths) => import_node_path4.default.join(paths.sessionsDir, MESSAGES_DIRNAME);
372
- var resolveStateDbPath = (paths) => import_node_path4.default.join(paths.sessionsDir, STATE_DB_FILENAME);
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);
373
792
  var extractLastUserMessage = (messages) => {
374
793
  for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
375
794
  const message = messages[idx];
@@ -425,20 +844,20 @@ var deserializeMessages = (payload) => {
425
844
  return messages;
426
845
  };
427
846
  var atomicWriteFile2 = async (filePath, payload) => {
428
- const dirname = import_node_path4.default.dirname(filePath);
429
- const basename = import_node_path4.default.basename(filePath);
430
- const tempFile = import_node_path4.default.join(
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(
431
850
  dirname,
432
851
  `${basename}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
433
852
  );
434
853
  let wroteTemp = false;
435
854
  try {
436
- await import_node_fs4.promises.writeFile(tempFile, payload, "utf8");
855
+ await import_node_fs5.promises.writeFile(tempFile, payload, "utf8");
437
856
  wroteTemp = true;
438
- await import_node_fs4.promises.rename(tempFile, filePath);
857
+ await import_node_fs5.promises.rename(tempFile, filePath);
439
858
  } catch (error) {
440
859
  if (wroteTemp) {
441
- await import_node_fs4.promises.rm(tempFile, { force: true }).catch(() => {
860
+ await import_node_fs5.promises.rm(tempFile, { force: true }).catch(() => {
442
861
  });
443
862
  }
444
863
  throw error;
@@ -459,9 +878,9 @@ var SessionStateStoreImpl = class {
459
878
  this.messagesDir = resolveMessagesDir(paths);
460
879
  this.stateDbPath = resolveStateDbPath(paths);
461
880
  this.ensureDirs = Promise.all([
462
- import_node_fs4.promises.mkdir(paths.sessionsDir, { recursive: true }),
463
- import_node_fs4.promises.mkdir(this.legacyStateDir, { recursive: true }),
464
- import_node_fs4.promises.mkdir(this.messagesDir, { recursive: true })
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 })
465
884
  ]).then(() => {
466
885
  });
467
886
  this.onError = options.onError;
@@ -476,10 +895,10 @@ var SessionStateStoreImpl = class {
476
895
  return this.db;
477
896
  }
478
897
  resolveLegacyPath(sessionId) {
479
- return import_node_path4.default.join(this.legacyStateDir, `${sessionId}.json`);
898
+ return import_node_path6.default.join(this.legacyStateDir, `${sessionId}.json`);
480
899
  }
481
900
  resolveMessagePath(sessionId) {
482
- return import_node_path4.default.join(this.messagesDir, `${sessionId}.jsonl`);
901
+ return import_node_path6.default.join(this.messagesDir, `${sessionId}.jsonl`);
483
902
  }
484
903
  async openDatabase() {
485
904
  await this.ensureDirs;
@@ -577,7 +996,7 @@ var SessionStateStoreImpl = class {
577
996
  }
578
997
  async loadLegacy(sessionId) {
579
998
  try {
580
- const file = await import_node_fs4.promises.readFile(this.resolveLegacyPath(sessionId), "utf8");
999
+ const file = await import_node_fs5.promises.readFile(this.resolveLegacyPath(sessionId), "utf8");
581
1000
  const parsed = JSON.parse(file);
582
1001
  if (!parsed || typeof parsed !== "object") return null;
583
1002
  if (!parsed.session_id || !parsed.updated_at) return null;
@@ -615,7 +1034,7 @@ var SessionStateStoreImpl = class {
615
1034
  if (!row) return null;
616
1035
  let messages;
617
1036
  try {
618
- const payload = await import_node_fs4.promises.readFile(
1037
+ const payload = await import_node_fs5.promises.readFile(
619
1038
  this.resolveMessagePath(sessionId),
620
1039
  "utf8"
621
1040
  );
@@ -732,7 +1151,7 @@ var SessionStateStoreImpl = class {
732
1151
  async listLegacySummaries() {
733
1152
  let entries;
734
1153
  try {
735
- entries = await import_node_fs4.promises.readdir(this.legacyStateDir, {
1154
+ entries = await import_node_fs5.promises.readdir(this.legacyStateDir, {
736
1155
  withFileTypes: true,
737
1156
  encoding: "utf8"
738
1157
  });
@@ -744,9 +1163,9 @@ var SessionStateStoreImpl = class {
744
1163
  for (const entry of entries) {
745
1164
  if (!entry.isFile()) continue;
746
1165
  if (!entry.name.endsWith(".json")) continue;
747
- const filePath = import_node_path4.default.join(this.legacyStateDir, entry.name);
1166
+ const filePath = import_node_path6.default.join(this.legacyStateDir, entry.name);
748
1167
  try {
749
- const contents = await import_node_fs4.promises.readFile(filePath, "utf8");
1168
+ const contents = await import_node_fs5.promises.readFile(filePath, "utf8");
750
1169
  const parsed = JSON.parse(contents);
751
1170
  if (!parsed || typeof parsed !== "object") continue;
752
1171
  if (!parsed.session_id || !parsed.updated_at) continue;
@@ -791,12 +1210,12 @@ var SessionStateStoreImpl = class {
791
1210
  };
792
1211
 
793
1212
  // src/task-registry.ts
794
- var import_node_fs5 = require("fs");
795
- var import_node_path5 = __toESM(require("path"), 1);
1213
+ var import_node_fs6 = require("fs");
1214
+ var import_node_path7 = __toESM(require("path"), 1);
796
1215
  var TASKS_DIRNAME = "tasks";
797
1216
  var sortByUpdatedDesc = (tasks) => [...tasks].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
798
- var toShellKeyBase = (label) => {
799
- const source = label?.trim() ?? "";
1217
+ var toShellKeyBase = (label2) => {
1218
+ const source = label2?.trim() ?? "";
800
1219
  const slug = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
801
1220
  return slug || "shell";
802
1221
  };
@@ -850,14 +1269,14 @@ var assignMissingShellKeys = (tasks) => {
850
1269
  return updates;
851
1270
  };
852
1271
  var atomicWrite = async (filePath, payload) => {
853
- const dir = import_node_path5.default.dirname(filePath);
854
- const base = import_node_path5.default.basename(filePath);
855
- const tmp = import_node_path5.default.join(
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(
856
1275
  dir,
857
1276
  `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
858
1277
  );
859
- await import_node_fs5.promises.writeFile(tmp, payload, "utf8");
860
- await import_node_fs5.promises.rename(tmp, filePath);
1278
+ await import_node_fs6.promises.writeFile(tmp, payload, "utf8");
1279
+ await import_node_fs6.promises.rename(tmp, filePath);
861
1280
  };
862
1281
  var isTaskState = (value) => value === "queued" || value === "running" || value === "completed" || value === "failed" || value === "cancelled";
863
1282
  var isTaskKind = (value) => value === "shell" || value === "subagent";
@@ -877,67 +1296,98 @@ var isTaskTruncatedOutput = (value) => {
877
1296
  var isTaskResult = (value) => {
878
1297
  if (!value || typeof value !== "object") return false;
879
1298
  const result = value;
880
- return (result.summary === void 0 || isString(result.summary)) && (result.stdout === void 0 || isString(result.stdout)) && (result.stderr === void 0 || isString(result.stderr)) && (result.stdout_cache_id === void 0 || isString(result.stdout_cache_id)) && (result.stderr_cache_id === void 0 || isString(result.stderr_cache_id)) && (result.child_session_id === void 0 || isString(result.child_session_id)) && (result.worktree_path === void 0 || isString(result.worktree_path)) && (result.exit_code === void 0 || result.exit_code === null || isNumber(result.exit_code)) && (result.signal === void 0 || result.signal === null || isString(result.signal)) && (result.duration_ms === void 0 || isNumber(result.duration_ms)) && (result.truncated === void 0 || isTaskTruncatedOutput(result.truncated)) && (result.artifacts === void 0 || Array.isArray(result.artifacts) && result.artifacts.every(isTaskArtifact));
1299
+ return (result.termination_reason === void 0 || [
1300
+ "normal",
1301
+ "max_steps",
1302
+ "timeout",
1303
+ "cancelled",
1304
+ "startup_error",
1305
+ "execution_error"
1306
+ ].includes(result.termination_reason)) && (result.summary_cache_id === void 0 || isString(result.summary_cache_id)) && (result.usage === void 0 || isNumber(result.usage.total_tokens) && result.usage.total_tokens >= 0 && (result.usage.total_cost_usd == null || isNumber(result.usage.total_cost_usd))) && (result.summary === void 0 || isString(result.summary)) && (result.stdout === void 0 || isString(result.stdout)) && (result.stderr === void 0 || isString(result.stderr)) && (result.stdout_cache_id === void 0 || isString(result.stdout_cache_id)) && (result.stderr_cache_id === void 0 || isString(result.stderr_cache_id)) && (result.child_session_id === void 0 || isString(result.child_session_id)) && (result.worktree_path === void 0 || isString(result.worktree_path)) && (result.exit_code === void 0 || result.exit_code === null || isNumber(result.exit_code)) && (result.signal === void 0 || result.signal === null || isString(result.signal)) && (result.duration_ms === void 0 || isNumber(result.duration_ms)) && (result.truncated === void 0 || isTaskTruncatedOutput(result.truncated)) && (result.artifacts === void 0 || Array.isArray(result.artifacts) && result.artifacts.every(isTaskArtifact));
881
1307
  };
882
1308
  var normalizeTaskRecord = (value) => {
883
1309
  if (!value || typeof value !== "object") return null;
884
- const record = value;
885
- if (record.version !== 1 || !isString(record.task_id) || !isTaskKind(record.kind) || !isWorkspaceMode(record.workspace_mode) || !isTaskState(record.state) || !isString(record.owner_runtime_id) || !isNumber(record.owner_pid) || !isString(record.created_at) || !isString(record.updated_at)) {
1310
+ const record2 = value;
1311
+ if (record2.version !== 1 || !isString(record2.task_id) || !isTaskKind(record2.kind) || !isWorkspaceMode(record2.workspace_mode) || !isTaskState(record2.state) || !isString(record2.owner_runtime_id) || !isNumber(record2.owner_pid) || !isString(record2.created_at) || !isString(record2.updated_at)) {
886
1312
  return null;
887
1313
  }
888
- if (record.key !== void 0 && !isString(record.key)) {
1314
+ if (record2.messages !== void 0 && (!Array.isArray(record2.messages) || record2.messages.length > 256 || !record2.messages.every(
1315
+ (message) => message && [
1316
+ message.message_id,
1317
+ message.sender,
1318
+ message.recipient,
1319
+ message.created_at,
1320
+ message.content
1321
+ ].every(isString) && (message.sender_name === void 0 || isString(message.sender_name)) && (message.recipient_name === void 0 || isString(message.recipient_name))
1322
+ )))
889
1323
  return null;
1324
+ if (record2.subagent !== void 0) {
1325
+ const node = record2.subagent;
1326
+ if (record2.kind !== "subagent" || node.name !== void 0 && (!isString(node.name) || !node.name.trim() || node.name.length > 48) || node.depth !== 1 || node.context_mode !== "fresh" || !Number.isInteger(node.spawn_index) || node.spawn_index < 1 || ![
1327
+ node.tree_id,
1328
+ node.node_id,
1329
+ node.parent_node_id,
1330
+ node.owner_session_id,
1331
+ node.effective_policy_id,
1332
+ node.workspace_lease_id
1333
+ ].every(isString) || node.node_id !== record2.task_id)
1334
+ return null;
890
1335
  }
891
- if (record.label !== void 0 && !isString(record.label)) {
1336
+ if (record2.executor_identity !== void 0 && !isString(record2.executor_identity))
1337
+ return null;
1338
+ if (record2.key !== void 0 && !isString(record2.key)) {
892
1339
  return null;
893
1340
  }
894
- if (record.title !== void 0 && !isString(record.title)) {
1341
+ if (record2.label !== void 0 && !isString(record2.label)) {
895
1342
  return null;
896
1343
  }
897
- if (record.working_directory !== void 0 && !isString(record.working_directory)) {
1344
+ if (record2.title !== void 0 && !isString(record2.title)) {
898
1345
  return null;
899
1346
  }
900
- if (record.executor_pid !== void 0 && !isNumber(record.executor_pid)) {
1347
+ if (record2.working_directory !== void 0 && !isString(record2.working_directory)) {
901
1348
  return null;
902
1349
  }
903
- if (record.executor_pgid !== void 0 && !isNumber(record.executor_pgid)) {
1350
+ if (record2.executor_pid !== void 0 && !isNumber(record2.executor_pid)) {
904
1351
  return null;
905
1352
  }
906
- if (record.parent_session_id !== void 0 && !isString(record.parent_session_id)) {
1353
+ if (record2.executor_pgid !== void 0 && !isNumber(record2.executor_pgid)) {
907
1354
  return null;
908
1355
  }
909
- if (record.parent_run_id !== void 0 && !isString(record.parent_run_id)) {
1356
+ if (record2.parent_session_id !== void 0 && !isString(record2.parent_session_id)) {
910
1357
  return null;
911
1358
  }
912
- if (record.parent_tool_call_id !== void 0 && !isString(record.parent_tool_call_id)) {
1359
+ if (record2.parent_run_id !== void 0 && !isString(record2.parent_run_id)) {
913
1360
  return null;
914
1361
  }
915
- if (record.child_session_id !== void 0 && !isString(record.child_session_id)) {
1362
+ if (record2.parent_tool_call_id !== void 0 && !isString(record2.parent_tool_call_id)) {
916
1363
  return null;
917
1364
  }
918
- if (record.started_at !== void 0 && !isString(record.started_at)) {
1365
+ if (record2.child_session_id !== void 0 && !isString(record2.child_session_id)) {
919
1366
  return null;
920
1367
  }
921
- if (record.ended_at !== void 0 && !isString(record.ended_at)) {
1368
+ if (record2.started_at !== void 0 && !isString(record2.started_at)) {
922
1369
  return null;
923
1370
  }
924
- if (record.result !== void 0 && !isTaskResult(record.result)) {
1371
+ if (record2.ended_at !== void 0 && !isString(record2.ended_at)) {
925
1372
  return null;
926
1373
  }
927
- if (record.failure_message !== void 0 && !isString(record.failure_message)) {
1374
+ if (record2.result !== void 0 && !isTaskResult(record2.result)) {
928
1375
  return null;
929
1376
  }
930
- if (record.cancellation_reason !== void 0 && !isString(record.cancellation_reason)) {
1377
+ if (record2.failure_message !== void 0 && !isString(record2.failure_message)) {
931
1378
  return null;
932
1379
  }
933
- if (record.cleanup_reason !== void 0 && !isString(record.cleanup_reason)) {
1380
+ if (record2.cancellation_reason !== void 0 && !isString(record2.cancellation_reason)) {
934
1381
  return null;
935
1382
  }
936
- return record;
1383
+ if (record2.cleanup_reason !== void 0 && !isString(record2.cleanup_reason)) {
1384
+ return null;
1385
+ }
1386
+ return record2;
937
1387
  };
938
1388
  var readTaskFile = async (filePath) => {
939
1389
  try {
940
- const raw = await import_node_fs5.promises.readFile(filePath, "utf8");
1390
+ const raw = await import_node_fs6.promises.readFile(filePath, "utf8");
941
1391
  return normalizeTaskRecord(JSON.parse(raw));
942
1392
  } catch {
943
1393
  return null;
@@ -952,19 +1402,19 @@ var TaskRegistryStore = class {
952
1402
  return;
953
1403
  }
954
1404
  const root = resolveStoragePaths().root;
955
- this.tasksDir = import_node_path5.default.join(root, TASKS_DIRNAME);
1405
+ this.tasksDir = import_node_path7.default.join(root, TASKS_DIRNAME);
956
1406
  }
957
1407
  async ensureDir() {
958
- await import_node_fs5.promises.mkdir(this.tasksDir, { recursive: true });
1408
+ await import_node_fs6.promises.mkdir(this.tasksDir, { recursive: true });
959
1409
  }
960
1410
  taskPath(taskId) {
961
- return import_node_path5.default.join(this.tasksDir, taskFileName(taskId));
1411
+ return import_node_path7.default.join(this.tasksDir, taskFileName(taskId));
962
1412
  }
963
1413
  async list() {
964
1414
  await this.ensureDir();
965
- const entries = await import_node_fs5.promises.readdir(this.tasksDir, { withFileTypes: true });
1415
+ const entries = await import_node_fs6.promises.readdir(this.tasksDir, { withFileTypes: true });
966
1416
  const tasks = (await Promise.all(
967
- entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(import_node_path5.default.join(this.tasksDir, entry.name)))
1417
+ entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(import_node_path7.default.join(this.tasksDir, entry.name)))
968
1418
  )).filter((task) => task !== null);
969
1419
  const keyBackfills = assignMissingShellKeys(tasks);
970
1420
  if (keyBackfills.length > 0) {
@@ -982,11 +1432,11 @@ var TaskRegistryStore = class {
982
1432
  const tasks = await this.list();
983
1433
  return tasks.find((task) => task.task_id === taskId) ?? null;
984
1434
  }
985
- async upsert(record) {
1435
+ async upsert(record2) {
986
1436
  await this.ensureDir();
987
1437
  await atomicWrite(
988
- this.taskPath(record.task_id),
989
- `${JSON.stringify(record, null, 2)}
1438
+ this.taskPath(record2.task_id),
1439
+ `${JSON.stringify(record2, null, 2)}
990
1440
  `
991
1441
  );
992
1442
  }
@@ -1006,8 +1456,8 @@ var TaskRegistryStore = class {
1006
1456
  };
1007
1457
 
1008
1458
  // src/tool-output-cache.ts
1009
- var import_node_fs6 = require("fs");
1010
- var import_node_path6 = __toESM(require("path"), 1);
1459
+ var import_node_fs7 = require("fs");
1460
+ var import_node_path8 = __toESM(require("path"), 1);
1011
1461
  var DEFAULT_MAX_MATCHES = 50;
1012
1462
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
1013
1463
  var DEFAULT_MAX_READ_BYTES = 64 * 1024;
@@ -1116,18 +1566,18 @@ var ToolOutputCacheStoreImpl = class {
1116
1566
  DEFAULT_MAX_GREP_BYTES
1117
1567
  );
1118
1568
  }
1119
- async save(record) {
1120
- const refId = normalizeRefId(record.tool_call_id);
1569
+ async save(record2) {
1570
+ const refId = normalizeRefId(record2.tool_call_id);
1121
1571
  const filePath = this.resolvePath(refId);
1122
- await import_node_fs6.promises.mkdir(this.baseDir, { recursive: true });
1123
- await import_node_fs6.promises.writeFile(filePath, record.content, "utf8");
1124
- const byteSize = Buffer.byteLength(record.content, "utf8");
1125
- const lineCount = record.content.split(/\r?\n/).length;
1572
+ await import_node_fs7.promises.mkdir(this.baseDir, { recursive: true });
1573
+ await import_node_fs7.promises.writeFile(filePath, record2.content, "utf8");
1574
+ const byteSize = Buffer.byteLength(record2.content, "utf8");
1575
+ const lineCount = record2.content.split(/\r?\n/).length;
1126
1576
  return { id: refId, byte_size: byteSize, line_count: lineCount };
1127
1577
  }
1128
1578
  async read(refId, options = {}) {
1129
1579
  const filePath = this.resolvePath(refId);
1130
- const content = await import_node_fs6.promises.readFile(filePath, "utf8");
1580
+ const content = await import_node_fs7.promises.readFile(filePath, "utf8");
1131
1581
  const lines = content.split(/\r?\n/);
1132
1582
  const offset = options.offset ?? 0;
1133
1583
  const limit = options.limit ?? lines.length;
@@ -1186,7 +1636,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
1186
1636
  }
1187
1637
  async readTail(refId, options) {
1188
1638
  const filePath = this.resolvePath(refId);
1189
- const content = await import_node_fs6.promises.readFile(filePath, "utf8");
1639
+ const content = await import_node_fs7.promises.readFile(filePath, "utf8");
1190
1640
  const lines = content.split(/\r?\n/);
1191
1641
  const tailLines = Math.max(1, Math.trunc(options.tail_lines));
1192
1642
  const start = Math.max(0, lines.length - tailLines);
@@ -1198,7 +1648,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
1198
1648
  }
1199
1649
  async readLine(refId, options) {
1200
1650
  const filePath = this.resolvePath(refId);
1201
- const content = await import_node_fs6.promises.readFile(filePath, "utf8");
1651
+ const content = await import_node_fs7.promises.readFile(filePath, "utf8");
1202
1652
  const lines = content.split(/\r?\n/);
1203
1653
  const lineIndex = options.line_number - 1;
1204
1654
  if (lineIndex < 0 || lineIndex >= lines.length) {
@@ -1239,7 +1689,7 @@ tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${opti
1239
1689
  }
1240
1690
  async grep(refId, options) {
1241
1691
  const filePath = this.resolvePath(refId);
1242
- const content = await import_node_fs6.promises.readFile(filePath, "utf8");
1692
+ const content = await import_node_fs7.promises.readFile(filePath, "utf8");
1243
1693
  const lines = content.split(/\r?\n/);
1244
1694
  const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
1245
1695
  const before = Math.max(0, options.before ?? 0);
@@ -1290,11 +1740,13 @@ ${snippet}`;
1290
1740
  return output;
1291
1741
  }
1292
1742
  resolvePath(refId) {
1293
- return import_node_path6.default.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
1743
+ return import_node_path8.default.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
1294
1744
  }
1295
1745
  };
1296
1746
  // Annotate the CommonJS export names for ESM import in node:
1297
1747
  0 && (module.exports = {
1748
+ IMAGE_MAX_BYTES,
1749
+ ImageArtifactStore,
1298
1750
  McpAuthStore,
1299
1751
  ProjectsPolicyStore,
1300
1752
  RunEventStoreFactoryImpl,
@@ -1304,5 +1756,6 @@ ${snippet}`;
1304
1756
  TaskRegistryStore,
1305
1757
  ToolOutputCacheStoreImpl,
1306
1758
  ensureStorageDirs,
1307
- resolveStoragePaths
1759
+ resolveStoragePaths,
1760
+ validateImagePng
1308
1761
  });