@codelia/storage 0.1.81 → 0.1.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,430 @@
1
+ // src/image-artifacts.ts
2
+ import { randomUUID as randomUUID2 } from "crypto";
3
+ import { lstat as lstat2, mkdir as mkdir2, rename as rename2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
4
+ import path2 from "path";
5
+
6
+ // src/image-attachment.ts
7
+ import { imageSize } from "image-size";
8
+
9
+ // src/image-png.ts
10
+ import { promisify } from "util";
11
+ import { inflate } from "zlib";
12
+ var IMAGE_MAX_BYTES = 8 * 1024 * 1024;
13
+ var inflateAsync = promisify(inflate);
14
+ var crcTable = Uint32Array.from({ length: 256 }, (_, n) => {
15
+ let c = n;
16
+ for (let i = 0; i < 8; i++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
17
+ return c >>> 0;
18
+ });
19
+ var crc32 = (data) => {
20
+ let crc = 4294967295;
21
+ for (const b of data) crc = (crcTable[(crc ^ b) & 255] ?? 0) ^ crc >>> 8;
22
+ return (crc ^ 4294967295) >>> 0;
23
+ };
24
+ var invalid = () => {
25
+ throw new Error(
26
+ "Invalid or unsupported image: require a complete non-interlaced 8-bit PNG, <=8 MiB, <=4096 per side and <=16 MP."
27
+ );
28
+ };
29
+ async function validateImagePng(bytes) {
30
+ if (bytes.length < 57 || bytes.length > IMAGE_MAX_BYTES || !bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
31
+ invalid();
32
+ let offset = 8;
33
+ let width = 0;
34
+ let height = 0;
35
+ let channels = 0;
36
+ let ended = false;
37
+ let dataEnded = false;
38
+ let palette = false;
39
+ let color = -1;
40
+ const data = [];
41
+ while (offset + 12 <= bytes.length) {
42
+ const len = bytes.readUInt32BE(offset);
43
+ if (offset + 12 + len > bytes.length) invalid();
44
+ const type = bytes.toString("ascii", offset + 4, offset + 8);
45
+ const payload = bytes.subarray(offset + 8, offset + 8 + len);
46
+ if (crc32(bytes.subarray(offset + 4, offset + 8 + len)) !== bytes.readUInt32BE(offset + 8 + len))
47
+ invalid();
48
+ if (offset === 8 && type !== "IHDR") invalid();
49
+ if (type === "IHDR") {
50
+ if (offset !== 8 || len !== 13) invalid();
51
+ width = payload.readUInt32BE(0);
52
+ height = payload.readUInt32BE(4);
53
+ color = payload[9] ?? -1;
54
+ channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[color] ?? 0;
55
+ if (!width || !height || width > 4096 || height > 4096 || width * height > 16e6 || !channels || payload[8] !== 8 || payload[10] !== 0 || payload[11] !== 0 || payload[12] !== 0)
56
+ invalid();
57
+ } else if (type === "IDAT") {
58
+ if (dataEnded || color === 3 && !palette) invalid();
59
+ data.push(payload);
60
+ } else if (type === "IEND") {
61
+ if (len !== 0 || !data.length) invalid();
62
+ ended = true;
63
+ offset += 12;
64
+ break;
65
+ } else {
66
+ if (data.length) dataEnded = true;
67
+ if (type === "PLTE") {
68
+ if (palette || data.length || len === 0 || len > 768 || len % 3)
69
+ invalid();
70
+ palette = true;
71
+ } else if (!/^[a-z][A-Za-z]{3}$/.test(type) || type === "acTL") invalid();
72
+ }
73
+ offset += 12 + len;
74
+ }
75
+ if (!ended || offset !== bytes.length) invalid();
76
+ const rowBytes = width * channels + 1;
77
+ try {
78
+ const raw = await inflateAsync(Buffer.concat(data), {
79
+ maxOutputLength: rowBytes * height
80
+ });
81
+ if (raw.length !== rowBytes * height) invalid();
82
+ for (let row = 0; row < height; row++)
83
+ if ((raw[row * rowBytes] ?? 255) > 4) invalid();
84
+ } catch {
85
+ invalid();
86
+ }
87
+ return { width, height };
88
+ }
89
+
90
+ // src/image-attachment.ts
91
+ function validateImageAttachment(bytes, mediaType) {
92
+ const signatures = {
93
+ "image/png": bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])),
94
+ "image/jpeg": bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255,
95
+ "image/webp": bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP",
96
+ "image/gif": ["GIF87a", "GIF89a"].includes(bytes.toString("ascii", 0, 6))
97
+ };
98
+ if (!bytes.length || bytes.length > IMAGE_MAX_BYTES || !signatures[mediaType])
99
+ throw new Error("Invalid image attachment: MIME mismatch or exceeds 8 MiB");
100
+ try {
101
+ const { width, height } = imageSize(bytes);
102
+ if (!width || !height || width > 4096 || height > 4096 || width * height > 16e6)
103
+ throw new Error("dimensions");
104
+ return { width, height };
105
+ } catch {
106
+ throw new Error(
107
+ "Invalid image attachment: unreadable header or exceeds 4096px/16 MP"
108
+ );
109
+ }
110
+ }
111
+ var imageOriginalFilename = (mediaType) => `original.${{ "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/gif": "gif" }[mediaType]}`;
112
+
113
+ // src/image-files.ts
114
+ import { createHash } from "crypto";
115
+ import { constants } from "fs";
116
+ import { open } from "fs/promises";
117
+ var imageHash = (bytes) => createHash("sha256").update(bytes).digest("hex");
118
+ async function readImageFileBounded(file, limit) {
119
+ const handle = await open(
120
+ file,
121
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)
122
+ );
123
+ try {
124
+ const stat = await handle.stat();
125
+ if (!stat.isFile() || stat.size > limit)
126
+ throw new Error("Invalid artifact file");
127
+ const bytes = Buffer.alloc(stat.size + 1);
128
+ let offset = 0;
129
+ while (offset < bytes.length) {
130
+ const read = await handle.read(
131
+ bytes,
132
+ offset,
133
+ bytes.length - offset,
134
+ offset
135
+ );
136
+ if (!read.bytesRead) break;
137
+ offset += read.bytesRead;
138
+ }
139
+ if (offset !== stat.size) throw new Error("Artifact changed during read");
140
+ return bytes.subarray(0, offset);
141
+ } finally {
142
+ await handle.close();
143
+ }
144
+ }
145
+
146
+ // src/image-metadata.ts
147
+ import {
148
+ IMAGE_REFERENCE_MAX_COUNT
149
+ } from "@codelia/shared-types";
150
+ var record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
151
+ var label = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && [...value].every((c) => c.charCodeAt(0) >= 32 && c.charCodeAt(0) !== 127);
152
+ var id = (value) => typeof value === "string" && /^codelia-image-[0-9a-f-]{36}$/.test(value);
153
+ var positive = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
154
+ function parseImageMetadata(value) {
155
+ 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(
156
+ String(value.media_type)
157
+ ) || !positive(value.byte_size) || !positive(value.width) || !positive(value.height) || !label(value.created_at, 40) || !Number.isFinite(Date.parse(value.created_at)))
158
+ throw new Error("Invalid image artifact metadata");
159
+ if (value.kind === "attachment") {
160
+ if ([
161
+ "provider",
162
+ "requested_model",
163
+ "endpoint",
164
+ "usage",
165
+ "parent_artifact_ids"
166
+ ].some((key) => key in value))
167
+ throw new Error("Invalid attachment provenance");
168
+ return {
169
+ kind: "attachment",
170
+ artifact_id: value.artifact_id,
171
+ sha256: value.sha256,
172
+ media_type: value.media_type,
173
+ byte_size: value.byte_size,
174
+ width: value.width,
175
+ height: value.height,
176
+ created_at: value.created_at
177
+ };
178
+ }
179
+ if (value.kind !== void 0 && value.kind !== "generated" || value.media_type !== "image/png" || !label(value.provider, 160) || !label(value.requested_model, 160) || !label(value.endpoint, 256) || value.effective_model !== void 0 && !label(value.effective_model, 160) || !Array.isArray(value.parent_artifact_ids) || value.parent_artifact_ids.length > IMAGE_REFERENCE_MAX_COUNT || !value.parent_artifact_ids.every(id))
180
+ throw new Error("Invalid image artifact metadata");
181
+ let usage;
182
+ if (value.usage !== void 0) {
183
+ if (!record(value.usage)) throw new Error("Invalid image usage metadata");
184
+ usage = {};
185
+ for (const key of ["input_tokens", "output_tokens", "cost_usd"]) {
186
+ const number = value.usage[key];
187
+ if (number === void 0) continue;
188
+ if (typeof number !== "number" || !Number.isFinite(number) || number < 0)
189
+ throw new Error("Invalid image usage metadata");
190
+ usage[key] = number;
191
+ }
192
+ }
193
+ return {
194
+ artifact_id: value.artifact_id,
195
+ sha256: value.sha256,
196
+ media_type: value.media_type,
197
+ byte_size: value.byte_size,
198
+ width: value.width,
199
+ height: value.height,
200
+ created_at: value.created_at,
201
+ provider: value.provider,
202
+ requested_model: value.requested_model,
203
+ endpoint: value.endpoint,
204
+ parent_artifact_ids: value.parent_artifact_ids,
205
+ ...value.effective_model !== void 0 ? { effective_model: value.effective_model } : {},
206
+ ...usage ? { usage } : {}
207
+ };
208
+ }
209
+
210
+ // src/image-model-view.ts
211
+ import { randomUUID } from "crypto";
212
+ import { lstat, mkdir, rename, rm, writeFile } from "fs/promises";
213
+ import path from "path";
214
+ import {
215
+ isImageModelView
216
+ } from "@codelia/shared-types";
217
+ import { imageSize as imageSize2 } from "image-size";
218
+ var VERSION = "jpeg-q90-444-v1";
219
+ var directory = (root) => path.join(root, VERSION);
220
+ var errorCode = (error) => error && typeof error === "object" && "code" in error ? error.code : void 0;
221
+ async function readModelView(root, original, expected) {
222
+ if (expected !== void 0 && !isImageModelView(expected))
223
+ throw new Error("Invalid image model view");
224
+ const dir = directory(root);
225
+ if (!(await lstat(dir)).isDirectory())
226
+ throw new Error("Invalid model view directory");
227
+ const record2 = JSON.parse(
228
+ (await readImageFileBounded(path.join(dir, "metadata.json"), 4096)).toString()
229
+ );
230
+ if (!record2 || record2.original_sha256 !== original.sha256 || !isImageModelView(record2.view))
231
+ throw new Error("Invalid model view metadata");
232
+ const view = record2.view;
233
+ if (expected && (view.sha256 !== expected.sha256 || view.byte_size !== expected.byte_size))
234
+ throw new Error("Image model view reference mismatch");
235
+ const bytes = await readImageFileBounded(
236
+ path.join(dir, "view.jpg"),
237
+ 8 * 1024 * 1024
238
+ );
239
+ const dims = imageSize2(bytes);
240
+ 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)
241
+ throw new Error("Corrupt image model view");
242
+ return { view, bytes };
243
+ }
244
+ async function prepareModelView(root, original, bytes) {
245
+ if (original.kind === "attachment" || bytes.length < 256 * 1024)
246
+ return void 0;
247
+ let exists = true;
248
+ try {
249
+ await lstat(directory(root));
250
+ } catch (error) {
251
+ if (errorCode(error) !== "ENOENT") throw error;
252
+ exists = false;
253
+ }
254
+ if (exists) return (await readModelView(root, original)).view;
255
+ const { default: sharp } = await import("sharp");
256
+ const pipeline = sharp(bytes, {
257
+ limitInputPixels: 16e6,
258
+ failOn: "warning"
259
+ }).timeout({ seconds: 15 });
260
+ const metadata = await pipeline.metadata();
261
+ if ((metadata.pages ?? 1) > 1 || metadata.hasAlpha && !(await pipeline.clone().stats()).isOpaque)
262
+ return void 0;
263
+ const jpeg = await pipeline.jpeg({ quality: 90, chromaSubsampling: "4:4:4" }).toBuffer();
264
+ if (jpeg.length >= bytes.length) return void 0;
265
+ const view = {
266
+ version: VERSION,
267
+ media_type: "image/jpeg",
268
+ sha256: imageHash(jpeg),
269
+ byte_size: jpeg.length
270
+ };
271
+ const temporary = path.join(root, `.model-view-${randomUUID()}`);
272
+ await mkdir(temporary, { mode: 448 });
273
+ try {
274
+ await writeFile(path.join(temporary, "view.jpg"), jpeg, {
275
+ flag: "wx",
276
+ mode: 384
277
+ });
278
+ await writeFile(
279
+ path.join(temporary, "metadata.json"),
280
+ JSON.stringify({ original_sha256: original.sha256, view }),
281
+ { flag: "wx", mode: 384 }
282
+ );
283
+ try {
284
+ await rename(temporary, directory(root));
285
+ } catch (error) {
286
+ if (!["EEXIST", "ENOTEMPTY"].includes(String(errorCode(error))))
287
+ throw error;
288
+ }
289
+ return (await readModelView(root, original)).view;
290
+ } finally {
291
+ await rm(temporary, { recursive: true, force: true });
292
+ }
293
+ }
294
+
295
+ // src/image-artifacts.ts
296
+ var ID = /^codelia-image-[0-9a-f-]{36}$/;
297
+ var ImageArtifactStore = class {
298
+ constructor(root) {
299
+ this.root = root;
300
+ }
301
+ root;
302
+ async save(bytes, provenance) {
303
+ const dimensions = await validateImagePng(bytes);
304
+ const artifact_id = `codelia-image-${randomUUID2()}`;
305
+ const metadata = parseImageMetadata({
306
+ ...provenance,
307
+ ...dimensions,
308
+ artifact_id,
309
+ sha256: imageHash(bytes),
310
+ media_type: "image/png",
311
+ byte_size: bytes.length,
312
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
313
+ });
314
+ if (metadata.kind === "attachment")
315
+ throw new Error("Invalid generation provenance");
316
+ await this.persist(bytes, metadata);
317
+ return metadata;
318
+ }
319
+ async saveAttachment(bytes, mediaType) {
320
+ const dimensions = validateImageAttachment(bytes, mediaType);
321
+ const metadata = {
322
+ kind: "attachment",
323
+ artifact_id: `codelia-image-${randomUUID2()}`,
324
+ sha256: imageHash(bytes),
325
+ media_type: mediaType,
326
+ byte_size: bytes.length,
327
+ ...dimensions,
328
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
329
+ };
330
+ await this.persist(bytes, metadata);
331
+ return metadata;
332
+ }
333
+ async persist(bytes, metadata) {
334
+ await mkdir2(this.root, { recursive: true, mode: 448 });
335
+ const temporary = path2.join(this.root, `.pending-${randomUUID2()}`);
336
+ await mkdir2(temporary, { mode: 448 });
337
+ try {
338
+ await writeFile2(
339
+ path2.join(temporary, imageOriginalFilename(metadata.media_type)),
340
+ bytes,
341
+ {
342
+ flag: "wx",
343
+ mode: 384
344
+ }
345
+ );
346
+ await writeFile2(
347
+ path2.join(temporary, "metadata.json"),
348
+ JSON.stringify(metadata),
349
+ { flag: "wx", mode: 384 }
350
+ );
351
+ await rename2(temporary, path2.join(this.root, metadata.artifact_id));
352
+ } catch (error) {
353
+ await rm2(temporary, { recursive: true, force: true });
354
+ throw error;
355
+ }
356
+ }
357
+ async read(artifactId) {
358
+ if (!ID.test(artifactId)) throw new Error("Invalid image artifact id");
359
+ try {
360
+ const dir = path2.join(this.root, artifactId);
361
+ if (!(await lstat2(dir)).isDirectory())
362
+ throw new Error("Invalid artifact directory");
363
+ const metadata = parseImageMetadata(
364
+ JSON.parse(
365
+ (await readImageFileBounded(path2.join(dir, "metadata.json"), 16384)).toString()
366
+ )
367
+ );
368
+ const bytes = await readImageFileBounded(
369
+ path2.join(dir, imageOriginalFilename(metadata.media_type)),
370
+ IMAGE_MAX_BYTES
371
+ );
372
+ const dims = metadata.kind === "attachment" ? validateImageAttachment(bytes, metadata.media_type) : await validateImagePng(bytes);
373
+ if (metadata.artifact_id !== artifactId || metadata.byte_size !== bytes.length || metadata.sha256 !== imageHash(bytes) || metadata.width !== dims.width || metadata.height !== dims.height)
374
+ throw new Error("Invalid artifact metadata");
375
+ return { metadata, bytes };
376
+ } catch {
377
+ throw new Error(
378
+ "Image artifact missing, corrupt, or inaccessible in this workspace"
379
+ );
380
+ }
381
+ }
382
+ /** Prepare a new history reference, never upgrade an already persisted reference. */
383
+ async modelReference(artifactId, original = false) {
384
+ const { metadata, bytes } = await this.read(artifactId);
385
+ const { artifact_id, sha256, media_type, byte_size, width, height } = metadata;
386
+ const ref = {
387
+ artifact_id,
388
+ sha256,
389
+ media_type,
390
+ byte_size,
391
+ width,
392
+ height
393
+ };
394
+ if (original) return ref;
395
+ const model_view = await prepareModelView(
396
+ path2.join(this.root, artifactId),
397
+ metadata,
398
+ bytes
399
+ );
400
+ return model_view ? { ...ref, model_view } : ref;
401
+ }
402
+ async resolve(ref) {
403
+ const { metadata, bytes } = await this.read(ref.artifact_id);
404
+ if (metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size || metadata.media_type !== ref.media_type || metadata.width !== ref.width || metadata.height !== ref.height)
405
+ throw new Error("Image artifact reference mismatch");
406
+ const input = ref.model_view !== void 0 ? await readModelView(
407
+ path2.join(this.root, ref.artifact_id),
408
+ metadata,
409
+ ref.model_view
410
+ ) : { bytes, view: metadata };
411
+ return {
412
+ type: "image_url",
413
+ image_url: {
414
+ url: `data:${input.view.media_type};base64,${input.bytes.toString("base64")}`,
415
+ media_type: input.view.media_type
416
+ }
417
+ };
418
+ }
419
+ };
420
+
1
421
  // src/mcp-auth-store.ts
2
422
  import { promises as fs } from "fs";
3
423
 
4
424
  // src/paths.ts
5
- import { mkdir } from "fs/promises";
425
+ import { mkdir as mkdir3 } from "fs/promises";
6
426
  import os from "os";
7
- import path from "path";
427
+ import path3 from "path";
8
428
  var DEFAULT_ROOT_DIR = ".codelia";
9
429
  var LAYOUT_ENV = "CODELIA_LAYOUT";
10
430
  var XDG_DIR_NAME = "codelia";
@@ -29,11 +449,11 @@ function resolveStoragePaths(options = {}) {
29
449
  }
30
450
  async function ensureStorageDirs(paths) {
31
451
  await Promise.all([
32
- mkdir(paths.configDir, { recursive: true }),
33
- mkdir(paths.cacheDir, { recursive: true }),
34
- mkdir(paths.toolOutputCacheDir, { recursive: true }),
35
- mkdir(paths.sessionsDir, { recursive: true }),
36
- mkdir(paths.logsDir, { recursive: true })
452
+ mkdir3(paths.configDir, { recursive: true }),
453
+ mkdir3(paths.cacheDir, { recursive: true }),
454
+ mkdir3(paths.toolOutputCacheDir, { recursive: true }),
455
+ mkdir3(paths.sessionsDir, { recursive: true }),
456
+ mkdir3(paths.logsDir, { recursive: true })
37
457
  ]);
38
458
  }
39
459
  function normalizeLayout(value) {
@@ -41,46 +461,46 @@ function normalizeLayout(value) {
41
461
  return "home";
42
462
  }
43
463
  function defaultHomeRoot() {
44
- return path.join(os.homedir(), DEFAULT_ROOT_DIR);
464
+ return path3.join(os.homedir(), DEFAULT_ROOT_DIR);
45
465
  }
46
466
  function buildHomeLayout(root) {
47
467
  const configDir = root;
48
468
  return {
49
469
  root,
50
470
  configDir,
51
- configFile: path.join(configDir, CONFIG_FILENAME),
52
- authFile: path.join(configDir, AUTH_FILENAME),
53
- mcpAuthFile: path.join(configDir, MCP_AUTH_FILENAME),
54
- projectsFile: path.join(configDir, PROJECTS_FILENAME),
55
- cacheDir: path.join(root, CACHE_DIRNAME),
56
- toolOutputCacheDir: path.join(
471
+ configFile: path3.join(configDir, CONFIG_FILENAME),
472
+ authFile: path3.join(configDir, AUTH_FILENAME),
473
+ mcpAuthFile: path3.join(configDir, MCP_AUTH_FILENAME),
474
+ projectsFile: path3.join(configDir, PROJECTS_FILENAME),
475
+ cacheDir: path3.join(root, CACHE_DIRNAME),
476
+ toolOutputCacheDir: path3.join(
57
477
  root,
58
478
  CACHE_DIRNAME,
59
479
  TOOL_OUTPUT_CACHE_DIRNAME
60
480
  ),
61
- sessionsDir: path.join(root, SESSIONS_DIRNAME),
62
- logsDir: path.join(root, LOGS_DIRNAME)
481
+ sessionsDir: path3.join(root, SESSIONS_DIRNAME),
482
+ logsDir: path3.join(root, LOGS_DIRNAME)
63
483
  };
64
484
  }
65
485
  function buildXdgLayout() {
66
486
  const home = os.homedir();
67
- const configRoot = process.env.XDG_CONFIG_HOME ?? path.join(home, ".config");
68
- const cacheRoot = process.env.XDG_CACHE_HOME ?? path.join(home, ".cache");
69
- const stateRoot = process.env.XDG_STATE_HOME ?? path.join(home, ".local", "state");
70
- const configDir = path.join(configRoot, XDG_DIR_NAME);
71
- const cacheDir = path.join(cacheRoot, XDG_DIR_NAME);
72
- const stateDir = path.join(stateRoot, XDG_DIR_NAME);
487
+ const configRoot = process.env.XDG_CONFIG_HOME ?? path3.join(home, ".config");
488
+ const cacheRoot = process.env.XDG_CACHE_HOME ?? path3.join(home, ".cache");
489
+ const stateRoot = process.env.XDG_STATE_HOME ?? path3.join(home, ".local", "state");
490
+ const configDir = path3.join(configRoot, XDG_DIR_NAME);
491
+ const cacheDir = path3.join(cacheRoot, XDG_DIR_NAME);
492
+ const stateDir = path3.join(stateRoot, XDG_DIR_NAME);
73
493
  return {
74
494
  root: stateDir,
75
495
  configDir,
76
- configFile: path.join(configDir, CONFIG_FILENAME),
77
- authFile: path.join(configDir, AUTH_FILENAME),
78
- mcpAuthFile: path.join(configDir, MCP_AUTH_FILENAME),
79
- projectsFile: path.join(configDir, PROJECTS_FILENAME),
496
+ configFile: path3.join(configDir, CONFIG_FILENAME),
497
+ authFile: path3.join(configDir, AUTH_FILENAME),
498
+ mcpAuthFile: path3.join(configDir, MCP_AUTH_FILENAME),
499
+ projectsFile: path3.join(configDir, PROJECTS_FILENAME),
80
500
  cacheDir,
81
- toolOutputCacheDir: path.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
82
- sessionsDir: path.join(stateDir, SESSIONS_DIRNAME),
83
- logsDir: path.join(stateDir, LOGS_DIRNAME)
501
+ toolOutputCacheDir: path3.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
502
+ sessionsDir: path3.join(stateDir, SESSIONS_DIRNAME),
503
+ logsDir: path3.join(stateDir, LOGS_DIRNAME)
84
504
  };
85
505
  }
86
506
 
@@ -117,10 +537,10 @@ var McpAuthStore = class {
117
537
  }
118
538
  const serversRaw = isRecord(parsed.servers) ? parsed.servers : {};
119
539
  const servers = {};
120
- for (const [id, entry] of Object.entries(serversRaw)) {
540
+ for (const [id2, entry] of Object.entries(serversRaw)) {
121
541
  const normalized = normalizeTokens(entry);
122
542
  if (normalized) {
123
- servers[id] = normalized;
543
+ servers[id2] = normalized;
124
544
  }
125
545
  }
126
546
  return {
@@ -148,7 +568,7 @@ var McpAuthStore = class {
148
568
 
149
569
  // src/projects-store.ts
150
570
  import { promises as fs2 } from "fs";
151
- import path2 from "path";
571
+ import path4 from "path";
152
572
  import { parseApprovalMode } from "@codelia/shared-types";
153
573
  var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
154
574
  var parseApprovalModeField = (fieldPath, value) => {
@@ -206,9 +626,9 @@ var normalizeProjectsPolicyFile = (value) => {
206
626
  return normalized;
207
627
  };
208
628
  var atomicWriteFile = async (filePath, content) => {
209
- const dirPath = path2.dirname(filePath);
210
- const fileName = path2.basename(filePath);
211
- const tempPath = path2.join(
629
+ const dirPath = path4.dirname(filePath);
630
+ const fileName = path4.basename(filePath);
631
+ const tempPath = path4.join(
212
632
  dirPath,
213
633
  `.${fileName}.${process.pid}.${Date.now()}.tmp`
214
634
  );
@@ -251,7 +671,7 @@ var ProjectsPolicyStore = class {
251
671
 
252
672
  // src/session-store.ts
253
673
  import { promises as fs3 } from "fs";
254
- import path3 from "path";
674
+ import path5 from "path";
255
675
  var pad2 = (value) => String(value).padStart(2, "0");
256
676
  var resolveDateParts = (startedAt) => {
257
677
  const parsed = new Date(startedAt);
@@ -269,20 +689,20 @@ var SessionStoreWriterImpl = class {
269
689
  constructor(options) {
270
690
  const paths = options.paths ?? resolveStoragePaths();
271
691
  const parts = resolveDateParts(options.startedAt);
272
- const baseDir = path3.join(
692
+ const baseDir = path5.join(
273
693
  paths.sessionsDir,
274
694
  parts.year,
275
695
  parts.month,
276
696
  parts.day
277
697
  );
278
- this.filePath = path3.join(baseDir, `${options.runId}.jsonl`);
698
+ this.filePath = path5.join(baseDir, `${options.runId}.jsonl`);
279
699
  this.ensureDir = fs3.mkdir(baseDir, { recursive: true }).then(() => {
280
700
  });
281
701
  }
282
- append(record) {
702
+ append(record2) {
283
703
  let line;
284
704
  try {
285
- line = `${JSON.stringify(record)}
705
+ line = `${JSON.stringify(record2)}
286
706
  `;
287
707
  } catch (error) {
288
708
  return Promise.reject(error);
@@ -316,15 +736,15 @@ var StoragePathServiceImpl = class {
316
736
 
317
737
  // src/session-state.ts
318
738
  import { promises as fs4 } from "fs";
319
- import path4 from "path";
739
+ import path6 from "path";
320
740
  import { stringifyContent } from "@codelia/core";
321
741
  var LEGACY_STATE_DIRNAME = "state";
322
742
  var MESSAGES_DIRNAME = "messages";
323
743
  var STATE_DB_FILENAME = "state.db";
324
744
  var SESSION_WORKSPACE_ROOT_META_KEY = "codelia_workspace_root";
325
- var resolveLegacyStateDir = (paths) => path4.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
326
- var resolveMessagesDir = (paths) => path4.join(paths.sessionsDir, MESSAGES_DIRNAME);
327
- var resolveStateDbPath = (paths) => path4.join(paths.sessionsDir, STATE_DB_FILENAME);
745
+ var resolveLegacyStateDir = (paths) => path6.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
746
+ var resolveMessagesDir = (paths) => path6.join(paths.sessionsDir, MESSAGES_DIRNAME);
747
+ var resolveStateDbPath = (paths) => path6.join(paths.sessionsDir, STATE_DB_FILENAME);
328
748
  var extractLastUserMessage = (messages) => {
329
749
  for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
330
750
  const message = messages[idx];
@@ -380,9 +800,9 @@ var deserializeMessages = (payload) => {
380
800
  return messages;
381
801
  };
382
802
  var atomicWriteFile2 = async (filePath, payload) => {
383
- const dirname = path4.dirname(filePath);
384
- const basename = path4.basename(filePath);
385
- const tempFile = path4.join(
803
+ const dirname = path6.dirname(filePath);
804
+ const basename = path6.basename(filePath);
805
+ const tempFile = path6.join(
386
806
  dirname,
387
807
  `${basename}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
388
808
  );
@@ -431,10 +851,10 @@ var SessionStateStoreImpl = class {
431
851
  return this.db;
432
852
  }
433
853
  resolveLegacyPath(sessionId) {
434
- return path4.join(this.legacyStateDir, `${sessionId}.json`);
854
+ return path6.join(this.legacyStateDir, `${sessionId}.json`);
435
855
  }
436
856
  resolveMessagePath(sessionId) {
437
- return path4.join(this.messagesDir, `${sessionId}.jsonl`);
857
+ return path6.join(this.messagesDir, `${sessionId}.jsonl`);
438
858
  }
439
859
  async openDatabase() {
440
860
  await this.ensureDirs;
@@ -699,7 +1119,7 @@ var SessionStateStoreImpl = class {
699
1119
  for (const entry of entries) {
700
1120
  if (!entry.isFile()) continue;
701
1121
  if (!entry.name.endsWith(".json")) continue;
702
- const filePath = path4.join(this.legacyStateDir, entry.name);
1122
+ const filePath = path6.join(this.legacyStateDir, entry.name);
703
1123
  try {
704
1124
  const contents = await fs4.readFile(filePath, "utf8");
705
1125
  const parsed = JSON.parse(contents);
@@ -747,11 +1167,11 @@ var SessionStateStoreImpl = class {
747
1167
 
748
1168
  // src/task-registry.ts
749
1169
  import { promises as fs5 } from "fs";
750
- import path5 from "path";
1170
+ import path7 from "path";
751
1171
  var TASKS_DIRNAME = "tasks";
752
1172
  var sortByUpdatedDesc = (tasks) => [...tasks].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
753
- var toShellKeyBase = (label) => {
754
- const source = label?.trim() ?? "";
1173
+ var toShellKeyBase = (label2) => {
1174
+ const source = label2?.trim() ?? "";
755
1175
  const slug = source.toLowerCase().replaceAll(/[^a-z0-9]+/g, "-").replaceAll(/^-+|-+$/g, "");
756
1176
  return slug || "shell";
757
1177
  };
@@ -805,9 +1225,9 @@ var assignMissingShellKeys = (tasks) => {
805
1225
  return updates;
806
1226
  };
807
1227
  var atomicWrite = async (filePath, payload) => {
808
- const dir = path5.dirname(filePath);
809
- const base = path5.basename(filePath);
810
- const tmp = path5.join(
1228
+ const dir = path7.dirname(filePath);
1229
+ const base = path7.basename(filePath);
1230
+ const tmp = path7.join(
811
1231
  dir,
812
1232
  `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
813
1233
  );
@@ -843,11 +1263,11 @@ var isTaskResult = (value) => {
843
1263
  };
844
1264
  var normalizeTaskRecord = (value) => {
845
1265
  if (!value || typeof value !== "object") return null;
846
- const record = value;
847
- 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)) {
1266
+ const record2 = value;
1267
+ 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)) {
848
1268
  return null;
849
1269
  }
850
- if (record.messages !== void 0 && (!Array.isArray(record.messages) || record.messages.length > 256 || !record.messages.every(
1270
+ if (record2.messages !== void 0 && (!Array.isArray(record2.messages) || record2.messages.length > 256 || !record2.messages.every(
851
1271
  (message) => message && [
852
1272
  message.message_id,
853
1273
  message.sender,
@@ -857,69 +1277,69 @@ var normalizeTaskRecord = (value) => {
857
1277
  ].every(isString) && (message.sender_name === void 0 || isString(message.sender_name)) && (message.recipient_name === void 0 || isString(message.recipient_name))
858
1278
  )))
859
1279
  return null;
860
- if (record.subagent !== void 0) {
861
- const node = record.subagent;
862
- if (record.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 || ![
1280
+ if (record2.subagent !== void 0) {
1281
+ const node = record2.subagent;
1282
+ 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 || ![
863
1283
  node.tree_id,
864
1284
  node.node_id,
865
1285
  node.parent_node_id,
866
1286
  node.owner_session_id,
867
1287
  node.effective_policy_id,
868
1288
  node.workspace_lease_id
869
- ].every(isString) || node.node_id !== record.task_id)
1289
+ ].every(isString) || node.node_id !== record2.task_id)
870
1290
  return null;
871
1291
  }
872
- if (record.executor_identity !== void 0 && !isString(record.executor_identity))
1292
+ if (record2.executor_identity !== void 0 && !isString(record2.executor_identity))
873
1293
  return null;
874
- if (record.key !== void 0 && !isString(record.key)) {
1294
+ if (record2.key !== void 0 && !isString(record2.key)) {
875
1295
  return null;
876
1296
  }
877
- if (record.label !== void 0 && !isString(record.label)) {
1297
+ if (record2.label !== void 0 && !isString(record2.label)) {
878
1298
  return null;
879
1299
  }
880
- if (record.title !== void 0 && !isString(record.title)) {
1300
+ if (record2.title !== void 0 && !isString(record2.title)) {
881
1301
  return null;
882
1302
  }
883
- if (record.working_directory !== void 0 && !isString(record.working_directory)) {
1303
+ if (record2.working_directory !== void 0 && !isString(record2.working_directory)) {
884
1304
  return null;
885
1305
  }
886
- if (record.executor_pid !== void 0 && !isNumber(record.executor_pid)) {
1306
+ if (record2.executor_pid !== void 0 && !isNumber(record2.executor_pid)) {
887
1307
  return null;
888
1308
  }
889
- if (record.executor_pgid !== void 0 && !isNumber(record.executor_pgid)) {
1309
+ if (record2.executor_pgid !== void 0 && !isNumber(record2.executor_pgid)) {
890
1310
  return null;
891
1311
  }
892
- if (record.parent_session_id !== void 0 && !isString(record.parent_session_id)) {
1312
+ if (record2.parent_session_id !== void 0 && !isString(record2.parent_session_id)) {
893
1313
  return null;
894
1314
  }
895
- if (record.parent_run_id !== void 0 && !isString(record.parent_run_id)) {
1315
+ if (record2.parent_run_id !== void 0 && !isString(record2.parent_run_id)) {
896
1316
  return null;
897
1317
  }
898
- if (record.parent_tool_call_id !== void 0 && !isString(record.parent_tool_call_id)) {
1318
+ if (record2.parent_tool_call_id !== void 0 && !isString(record2.parent_tool_call_id)) {
899
1319
  return null;
900
1320
  }
901
- if (record.child_session_id !== void 0 && !isString(record.child_session_id)) {
1321
+ if (record2.child_session_id !== void 0 && !isString(record2.child_session_id)) {
902
1322
  return null;
903
1323
  }
904
- if (record.started_at !== void 0 && !isString(record.started_at)) {
1324
+ if (record2.started_at !== void 0 && !isString(record2.started_at)) {
905
1325
  return null;
906
1326
  }
907
- if (record.ended_at !== void 0 && !isString(record.ended_at)) {
1327
+ if (record2.ended_at !== void 0 && !isString(record2.ended_at)) {
908
1328
  return null;
909
1329
  }
910
- if (record.result !== void 0 && !isTaskResult(record.result)) {
1330
+ if (record2.result !== void 0 && !isTaskResult(record2.result)) {
911
1331
  return null;
912
1332
  }
913
- if (record.failure_message !== void 0 && !isString(record.failure_message)) {
1333
+ if (record2.failure_message !== void 0 && !isString(record2.failure_message)) {
914
1334
  return null;
915
1335
  }
916
- if (record.cancellation_reason !== void 0 && !isString(record.cancellation_reason)) {
1336
+ if (record2.cancellation_reason !== void 0 && !isString(record2.cancellation_reason)) {
917
1337
  return null;
918
1338
  }
919
- if (record.cleanup_reason !== void 0 && !isString(record.cleanup_reason)) {
1339
+ if (record2.cleanup_reason !== void 0 && !isString(record2.cleanup_reason)) {
920
1340
  return null;
921
1341
  }
922
- return record;
1342
+ return record2;
923
1343
  };
924
1344
  var readTaskFile = async (filePath) => {
925
1345
  try {
@@ -938,19 +1358,19 @@ var TaskRegistryStore = class {
938
1358
  return;
939
1359
  }
940
1360
  const root = resolveStoragePaths().root;
941
- this.tasksDir = path5.join(root, TASKS_DIRNAME);
1361
+ this.tasksDir = path7.join(root, TASKS_DIRNAME);
942
1362
  }
943
1363
  async ensureDir() {
944
1364
  await fs5.mkdir(this.tasksDir, { recursive: true });
945
1365
  }
946
1366
  taskPath(taskId) {
947
- return path5.join(this.tasksDir, taskFileName(taskId));
1367
+ return path7.join(this.tasksDir, taskFileName(taskId));
948
1368
  }
949
1369
  async list() {
950
1370
  await this.ensureDir();
951
1371
  const entries = await fs5.readdir(this.tasksDir, { withFileTypes: true });
952
1372
  const tasks = (await Promise.all(
953
- entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(path5.join(this.tasksDir, entry.name)))
1373
+ entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(path7.join(this.tasksDir, entry.name)))
954
1374
  )).filter((task) => task !== null);
955
1375
  const keyBackfills = assignMissingShellKeys(tasks);
956
1376
  if (keyBackfills.length > 0) {
@@ -968,11 +1388,11 @@ var TaskRegistryStore = class {
968
1388
  const tasks = await this.list();
969
1389
  return tasks.find((task) => task.task_id === taskId) ?? null;
970
1390
  }
971
- async upsert(record) {
1391
+ async upsert(record2) {
972
1392
  await this.ensureDir();
973
1393
  await atomicWrite(
974
- this.taskPath(record.task_id),
975
- `${JSON.stringify(record, null, 2)}
1394
+ this.taskPath(record2.task_id),
1395
+ `${JSON.stringify(record2, null, 2)}
976
1396
  `
977
1397
  );
978
1398
  }
@@ -993,7 +1413,7 @@ var TaskRegistryStore = class {
993
1413
 
994
1414
  // src/tool-output-cache.ts
995
1415
  import { promises as fs6 } from "fs";
996
- import path6 from "path";
1416
+ import path8 from "path";
997
1417
  var DEFAULT_MAX_MATCHES = 50;
998
1418
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
999
1419
  var DEFAULT_MAX_READ_BYTES = 64 * 1024;
@@ -1102,13 +1522,13 @@ var ToolOutputCacheStoreImpl = class {
1102
1522
  DEFAULT_MAX_GREP_BYTES
1103
1523
  );
1104
1524
  }
1105
- async save(record) {
1106
- const refId = normalizeRefId(record.tool_call_id);
1525
+ async save(record2) {
1526
+ const refId = normalizeRefId(record2.tool_call_id);
1107
1527
  const filePath = this.resolvePath(refId);
1108
1528
  await fs6.mkdir(this.baseDir, { recursive: true });
1109
- await fs6.writeFile(filePath, record.content, "utf8");
1110
- const byteSize = Buffer.byteLength(record.content, "utf8");
1111
- const lineCount = record.content.split(/\r?\n/).length;
1529
+ await fs6.writeFile(filePath, record2.content, "utf8");
1530
+ const byteSize = Buffer.byteLength(record2.content, "utf8");
1531
+ const lineCount = record2.content.split(/\r?\n/).length;
1112
1532
  return { id: refId, byte_size: byteSize, line_count: lineCount };
1113
1533
  }
1114
1534
  async read(refId, options = {}) {
@@ -1276,10 +1696,12 @@ ${snippet}`;
1276
1696
  return output;
1277
1697
  }
1278
1698
  resolvePath(refId) {
1279
- return path6.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
1699
+ return path8.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
1280
1700
  }
1281
1701
  };
1282
1702
  export {
1703
+ IMAGE_MAX_BYTES,
1704
+ ImageArtifactStore,
1283
1705
  McpAuthStore,
1284
1706
  ProjectsPolicyStore,
1285
1707
  RunEventStoreFactoryImpl,
@@ -1289,5 +1711,6 @@ export {
1289
1711
  TaskRegistryStore,
1290
1712
  ToolOutputCacheStoreImpl,
1291
1713
  ensureStorageDirs,
1292
- resolveStoragePaths
1714
+ resolveStoragePaths,
1715
+ validateImagePng
1293
1716
  };