@codelia/storage 0.1.19 → 0.1.21

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
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  McpAuthStore: () => McpAuthStore,
34
+ ProjectsPolicyStore: () => ProjectsPolicyStore,
34
35
  RunEventStoreFactoryImpl: () => RunEventStoreFactoryImpl,
35
36
  SessionStateStoreImpl: () => SessionStateStoreImpl,
36
37
  SessionStoreWriterImpl: () => SessionStoreWriterImpl,
@@ -54,6 +55,7 @@ var XDG_DIR_NAME = "codelia";
54
55
  var CONFIG_FILENAME = "config.json";
55
56
  var AUTH_FILENAME = "auth.json";
56
57
  var MCP_AUTH_FILENAME = "mcp-auth.json";
58
+ var PROJECTS_FILENAME = "projects.json";
57
59
  var CACHE_DIRNAME = "cache";
58
60
  var TOOL_OUTPUT_CACHE_DIRNAME = "tool-output";
59
61
  var SESSIONS_DIRNAME = "sessions";
@@ -93,6 +95,7 @@ function buildHomeLayout(root) {
93
95
  configFile: import_node_path.default.join(configDir, CONFIG_FILENAME),
94
96
  authFile: import_node_path.default.join(configDir, AUTH_FILENAME),
95
97
  mcpAuthFile: import_node_path.default.join(configDir, MCP_AUTH_FILENAME),
98
+ projectsFile: import_node_path.default.join(configDir, PROJECTS_FILENAME),
96
99
  cacheDir: import_node_path.default.join(root, CACHE_DIRNAME),
97
100
  toolOutputCacheDir: import_node_path.default.join(
98
101
  root,
@@ -117,6 +120,7 @@ function buildXdgLayout() {
117
120
  configFile: import_node_path.default.join(configDir, CONFIG_FILENAME),
118
121
  authFile: import_node_path.default.join(configDir, AUTH_FILENAME),
119
122
  mcpAuthFile: import_node_path.default.join(configDir, MCP_AUTH_FILENAME),
123
+ projectsFile: import_node_path.default.join(configDir, PROJECTS_FILENAME),
120
124
  cacheDir,
121
125
  toolOutputCacheDir: import_node_path.default.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
122
126
  sessionsDir: import_node_path.default.join(stateDir, SESSIONS_DIRNAME),
@@ -186,9 +190,112 @@ var McpAuthStore = class {
186
190
  }
187
191
  };
188
192
 
189
- // src/session-store.ts
193
+ // src/projects-store.ts
190
194
  var import_node_fs2 = require("fs");
191
195
  var import_node_path2 = __toESM(require("path"), 1);
196
+ var import_shared_types = require("@codelia/shared-types");
197
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
198
+ var parseApprovalModeField = (fieldPath, value) => {
199
+ const parsed = (0, import_shared_types.parseApprovalMode)(value);
200
+ if (!parsed) {
201
+ throw new Error(`${fieldPath} is invalid`);
202
+ }
203
+ return parsed;
204
+ };
205
+ var normalizeProjectsPolicyFile = (value) => {
206
+ if (!isRecord2(value)) {
207
+ throw new Error("projects policy must be an object");
208
+ }
209
+ if (value.version !== 1) {
210
+ throw new Error("projects policy version must be 1");
211
+ }
212
+ const normalized = { version: 1 };
213
+ const defaultValue = value.default;
214
+ if (defaultValue !== void 0) {
215
+ if (!isRecord2(defaultValue)) {
216
+ throw new Error("projects policy default must be an object");
217
+ }
218
+ if (defaultValue.approval_mode !== void 0) {
219
+ normalized.default = {
220
+ approval_mode: parseApprovalModeField(
221
+ "projects policy default.approval_mode",
222
+ defaultValue.approval_mode
223
+ )
224
+ };
225
+ }
226
+ }
227
+ const projectsValue = value.projects;
228
+ if (projectsValue !== void 0) {
229
+ if (!isRecord2(projectsValue)) {
230
+ throw new Error("projects policy projects must be an object");
231
+ }
232
+ const entries = {};
233
+ for (const [key, projectValue] of Object.entries(projectsValue)) {
234
+ if (!isRecord2(projectValue)) {
235
+ throw new Error(`projects policy projects['${key}'] must be an object`);
236
+ }
237
+ if (projectValue.approval_mode !== void 0) {
238
+ entries[key] = {
239
+ approval_mode: parseApprovalModeField(
240
+ `projects policy projects['${key}'].approval_mode`,
241
+ projectValue.approval_mode
242
+ )
243
+ };
244
+ }
245
+ }
246
+ if (Object.keys(entries).length > 0) {
247
+ normalized.projects = entries;
248
+ }
249
+ }
250
+ return normalized;
251
+ };
252
+ var atomicWriteFile = async (filePath, content) => {
253
+ const dirPath = import_node_path2.default.dirname(filePath);
254
+ const fileName = import_node_path2.default.basename(filePath);
255
+ const tempPath = import_node_path2.default.join(
256
+ dirPath,
257
+ `.${fileName}.${process.pid}.${Date.now()}.tmp`
258
+ );
259
+ await import_node_fs2.promises.writeFile(tempPath, content, { mode: 384 });
260
+ await import_node_fs2.promises.rename(tempPath, filePath);
261
+ if (process.platform !== "win32") {
262
+ await import_node_fs2.promises.chmod(filePath, 384);
263
+ }
264
+ };
265
+ var ProjectsPolicyStore = class {
266
+ paths;
267
+ constructor(paths) {
268
+ this.paths = paths ?? resolveStoragePaths();
269
+ }
270
+ getFilePath() {
271
+ return this.paths.projectsFile;
272
+ }
273
+ async load() {
274
+ try {
275
+ const raw = await import_node_fs2.promises.readFile(this.paths.projectsFile, "utf8");
276
+ const parsed = JSON.parse(raw);
277
+ return normalizeProjectsPolicyFile(parsed);
278
+ } catch (error) {
279
+ if (error.code === "ENOENT") {
280
+ return null;
281
+ }
282
+ throw error;
283
+ }
284
+ }
285
+ async save(data) {
286
+ if (data.version !== 1) {
287
+ throw new Error("projects policy version must be 1");
288
+ }
289
+ await ensureStorageDirs(this.paths);
290
+ const content = `${JSON.stringify(data, null, 2)}
291
+ `;
292
+ await atomicWriteFile(this.paths.projectsFile, content);
293
+ }
294
+ };
295
+
296
+ // src/session-store.ts
297
+ var import_node_fs3 = require("fs");
298
+ var import_node_path3 = __toESM(require("path"), 1);
192
299
  var pad2 = (value) => String(value).padStart(2, "0");
193
300
  var resolveDateParts = (startedAt) => {
194
301
  const parsed = new Date(startedAt);
@@ -206,14 +313,14 @@ var SessionStoreWriterImpl = class {
206
313
  constructor(options) {
207
314
  const paths = options.paths ?? resolveStoragePaths();
208
315
  const parts = resolveDateParts(options.startedAt);
209
- const baseDir = import_node_path2.default.join(
316
+ const baseDir = import_node_path3.default.join(
210
317
  paths.sessionsDir,
211
318
  parts.year,
212
319
  parts.month,
213
320
  parts.day
214
321
  );
215
- this.filePath = import_node_path2.default.join(baseDir, `${options.runId}.jsonl`);
216
- this.ensureDir = import_node_fs2.promises.mkdir(baseDir, { recursive: true }).then(() => {
322
+ this.filePath = import_node_path3.default.join(baseDir, `${options.runId}.jsonl`);
323
+ this.ensureDir = import_node_fs3.promises.mkdir(baseDir, { recursive: true }).then(() => {
217
324
  });
218
325
  }
219
326
  append(record) {
@@ -226,7 +333,7 @@ var SessionStoreWriterImpl = class {
226
333
  }
227
334
  const write = this.writeChain.then(async () => {
228
335
  await this.ensureDir;
229
- await import_node_fs2.promises.appendFile(this.filePath, line, "utf8");
336
+ await import_node_fs3.promises.appendFile(this.filePath, line, "utf8");
230
337
  });
231
338
  this.writeChain = write.catch(() => {
232
339
  });
@@ -252,15 +359,15 @@ var StoragePathServiceImpl = class {
252
359
  };
253
360
 
254
361
  // src/session-state.ts
255
- var import_node_fs3 = require("fs");
256
- var import_node_path3 = __toESM(require("path"), 1);
362
+ var import_node_fs4 = require("fs");
363
+ var import_node_path4 = __toESM(require("path"), 1);
257
364
  var import_core = require("@codelia/core");
258
365
  var LEGACY_STATE_DIRNAME = "state";
259
366
  var MESSAGES_DIRNAME = "messages";
260
367
  var STATE_DB_FILENAME = "state.db";
261
- var resolveLegacyStateDir = (paths) => import_node_path3.default.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
262
- var resolveMessagesDir = (paths) => import_node_path3.default.join(paths.sessionsDir, MESSAGES_DIRNAME);
263
- var resolveStateDbPath = (paths) => import_node_path3.default.join(paths.sessionsDir, STATE_DB_FILENAME);
368
+ var resolveLegacyStateDir = (paths) => import_node_path4.default.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
369
+ var resolveMessagesDir = (paths) => import_node_path4.default.join(paths.sessionsDir, MESSAGES_DIRNAME);
370
+ var resolveStateDbPath = (paths) => import_node_path4.default.join(paths.sessionsDir, STATE_DB_FILENAME);
264
371
  var extractLastUserMessage = (messages) => {
265
372
  for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
266
373
  const message = messages[idx];
@@ -307,21 +414,21 @@ var deserializeMessages = (payload) => {
307
414
  }
308
415
  return messages;
309
416
  };
310
- var atomicWriteFile = async (filePath, payload) => {
311
- const dirname = import_node_path3.default.dirname(filePath);
312
- const basename = import_node_path3.default.basename(filePath);
313
- const tempFile = import_node_path3.default.join(
417
+ var atomicWriteFile2 = async (filePath, payload) => {
418
+ const dirname = import_node_path4.default.dirname(filePath);
419
+ const basename = import_node_path4.default.basename(filePath);
420
+ const tempFile = import_node_path4.default.join(
314
421
  dirname,
315
422
  `${basename}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
316
423
  );
317
424
  let wroteTemp = false;
318
425
  try {
319
- await import_node_fs3.promises.writeFile(tempFile, payload, "utf8");
426
+ await import_node_fs4.promises.writeFile(tempFile, payload, "utf8");
320
427
  wroteTemp = true;
321
- await import_node_fs3.promises.rename(tempFile, filePath);
428
+ await import_node_fs4.promises.rename(tempFile, filePath);
322
429
  } catch (error) {
323
430
  if (wroteTemp) {
324
- await import_node_fs3.promises.rm(tempFile, { force: true }).catch(() => {
431
+ await import_node_fs4.promises.rm(tempFile, { force: true }).catch(() => {
325
432
  });
326
433
  }
327
434
  throw error;
@@ -342,9 +449,9 @@ var SessionStateStoreImpl = class {
342
449
  this.messagesDir = resolveMessagesDir(paths);
343
450
  this.stateDbPath = resolveStateDbPath(paths);
344
451
  this.ensureDirs = Promise.all([
345
- import_node_fs3.promises.mkdir(paths.sessionsDir, { recursive: true }),
346
- import_node_fs3.promises.mkdir(this.legacyStateDir, { recursive: true }),
347
- import_node_fs3.promises.mkdir(this.messagesDir, { recursive: true })
452
+ import_node_fs4.promises.mkdir(paths.sessionsDir, { recursive: true }),
453
+ import_node_fs4.promises.mkdir(this.legacyStateDir, { recursive: true }),
454
+ import_node_fs4.promises.mkdir(this.messagesDir, { recursive: true })
348
455
  ]).then(() => {
349
456
  });
350
457
  this.onError = options.onError;
@@ -359,10 +466,10 @@ var SessionStateStoreImpl = class {
359
466
  return this.db;
360
467
  }
361
468
  resolveLegacyPath(sessionId) {
362
- return import_node_path3.default.join(this.legacyStateDir, `${sessionId}.json`);
469
+ return import_node_path4.default.join(this.legacyStateDir, `${sessionId}.json`);
363
470
  }
364
471
  resolveMessagePath(sessionId) {
365
- return import_node_path3.default.join(this.messagesDir, `${sessionId}.jsonl`);
472
+ return import_node_path4.default.join(this.messagesDir, `${sessionId}.jsonl`);
366
473
  }
367
474
  async openDatabase() {
368
475
  await this.ensureDirs;
@@ -450,7 +557,7 @@ var SessionStateStoreImpl = class {
450
557
  }
451
558
  async loadLegacy(sessionId) {
452
559
  try {
453
- const file = await import_node_fs3.promises.readFile(this.resolveLegacyPath(sessionId), "utf8");
560
+ const file = await import_node_fs4.promises.readFile(this.resolveLegacyPath(sessionId), "utf8");
454
561
  const parsed = JSON.parse(file);
455
562
  if (!parsed || typeof parsed !== "object") return null;
456
563
  if (!parsed.session_id || !parsed.updated_at) return null;
@@ -488,7 +595,7 @@ var SessionStateStoreImpl = class {
488
595
  if (!row) return null;
489
596
  let messages;
490
597
  try {
491
- const payload = await import_node_fs3.promises.readFile(
598
+ const payload = await import_node_fs4.promises.readFile(
492
599
  this.resolveMessagePath(sessionId),
493
600
  "utf8"
494
601
  );
@@ -529,7 +636,7 @@ var SessionStateStoreImpl = class {
529
636
  const messagePayload = serializeMessages(
530
637
  Array.isArray(state.messages) ? state.messages : []
531
638
  );
532
- await atomicWriteFile(
639
+ await atomicWriteFile2(
533
640
  this.resolveMessagePath(state.session_id),
534
641
  messagePayload
535
642
  );
@@ -602,7 +709,7 @@ var SessionStateStoreImpl = class {
602
709
  async listLegacySummaries() {
603
710
  let entries;
604
711
  try {
605
- entries = await import_node_fs3.promises.readdir(this.legacyStateDir, {
712
+ entries = await import_node_fs4.promises.readdir(this.legacyStateDir, {
606
713
  withFileTypes: true,
607
714
  encoding: "utf8"
608
715
  });
@@ -614,9 +721,9 @@ var SessionStateStoreImpl = class {
614
721
  for (const entry of entries) {
615
722
  if (!entry.isFile()) continue;
616
723
  if (!entry.name.endsWith(".json")) continue;
617
- const filePath = import_node_path3.default.join(this.legacyStateDir, entry.name);
724
+ const filePath = import_node_path4.default.join(this.legacyStateDir, entry.name);
618
725
  try {
619
- const contents = await import_node_fs3.promises.readFile(filePath, "utf8");
726
+ const contents = await import_node_fs4.promises.readFile(filePath, "utf8");
620
727
  const parsed = JSON.parse(contents);
621
728
  if (!parsed || typeof parsed !== "object") continue;
622
729
  if (!parsed.session_id || !parsed.updated_at) continue;
@@ -661,8 +768,8 @@ var SessionStateStoreImpl = class {
661
768
  };
662
769
 
663
770
  // src/tool-output-cache.ts
664
- var import_node_fs4 = require("fs");
665
- var import_node_path4 = __toESM(require("path"), 1);
771
+ var import_node_fs5 = require("fs");
772
+ var import_node_path5 = __toESM(require("path"), 1);
666
773
  var DEFAULT_MAX_MATCHES = 50;
667
774
  var normalizeRefId = (refId) => refId.replace(/[^a-zA-Z0-9_-]/g, "_");
668
775
  var formatLineNumber = (lineNumber) => String(lineNumber).padStart(5, " ");
@@ -676,15 +783,15 @@ var ToolOutputCacheStoreImpl = class {
676
783
  async save(record) {
677
784
  const refId = normalizeRefId(record.tool_call_id);
678
785
  const filePath = this.resolvePath(refId);
679
- await import_node_fs4.promises.mkdir(this.baseDir, { recursive: true });
680
- await import_node_fs4.promises.writeFile(filePath, record.content, "utf8");
786
+ await import_node_fs5.promises.mkdir(this.baseDir, { recursive: true });
787
+ await import_node_fs5.promises.writeFile(filePath, record.content, "utf8");
681
788
  const byteSize = Buffer.byteLength(record.content, "utf8");
682
789
  const lineCount = record.content.split(/\r?\n/).length;
683
790
  return { id: refId, byte_size: byteSize, line_count: lineCount };
684
791
  }
685
792
  async read(refId, options = {}) {
686
793
  const filePath = this.resolvePath(refId);
687
- const content = await import_node_fs4.promises.readFile(filePath, "utf8");
794
+ const content = await import_node_fs5.promises.readFile(filePath, "utf8");
688
795
  const lines = content.split(/\r?\n/);
689
796
  const offset = options.offset ?? 0;
690
797
  const limit = options.limit ?? lines.length;
@@ -696,7 +803,7 @@ var ToolOutputCacheStoreImpl = class {
696
803
  }
697
804
  async grep(refId, options) {
698
805
  const filePath = this.resolvePath(refId);
699
- const content = await import_node_fs4.promises.readFile(filePath, "utf8");
806
+ const content = await import_node_fs5.promises.readFile(filePath, "utf8");
700
807
  const lines = content.split(/\r?\n/);
701
808
  const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
702
809
  const before = Math.max(0, options.before ?? 0);
@@ -719,12 +826,13 @@ ${snippet}`);
719
826
  ... (truncated)` : results.join("\n\n");
720
827
  }
721
828
  resolvePath(refId) {
722
- return import_node_path4.default.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
829
+ return import_node_path5.default.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
723
830
  }
724
831
  };
725
832
  // Annotate the CommonJS export names for ESM import in node:
726
833
  0 && (module.exports = {
727
834
  McpAuthStore,
835
+ ProjectsPolicyStore,
728
836
  RunEventStoreFactoryImpl,
729
837
  SessionStateStoreImpl,
730
838
  SessionStoreWriterImpl,
package/dist/index.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { StoragePaths, ResolveStorageOptions, RunEventStoreFactory, RunEventStoreInit, SessionStore, StoragePathService, SessionStateStore, SessionState, SessionStateSummary, SessionRecord, ToolOutputCacheStore, ToolOutputCacheRecord, ToolOutputRef, ToolOutputCacheReadOptions, ToolOutputCacheSearchOptions } from '@codelia/core';
2
2
  export { ResolveStorageOptions, StorageLayout, StoragePathService, StoragePaths } from '@codelia/core';
3
+ import { ApprovalMode } from '@codelia/shared-types';
3
4
 
4
5
  type McpOAuthTokens = {
5
6
  access_token: string;
@@ -21,6 +22,23 @@ declare class McpAuthStore {
21
22
  save(auth: McpAuthFile): Promise<void>;
22
23
  }
23
24
 
25
+ type ProjectsPolicyFile = {
26
+ version: 1;
27
+ default?: {
28
+ approval_mode?: ApprovalMode;
29
+ };
30
+ projects?: Record<string, {
31
+ approval_mode?: ApprovalMode;
32
+ }>;
33
+ };
34
+ declare class ProjectsPolicyStore {
35
+ private readonly paths;
36
+ constructor(paths?: StoragePaths);
37
+ getFilePath(): string;
38
+ load(): Promise<ProjectsPolicyFile | null>;
39
+ save(data: ProjectsPolicyFile): Promise<void>;
40
+ }
41
+
24
42
  declare function resolveStoragePaths(options?: ResolveStorageOptions): StoragePaths;
25
43
  declare function ensureStorageDirs(paths: StoragePaths): Promise<void>;
26
44
 
@@ -88,4 +106,4 @@ declare class ToolOutputCacheStoreImpl implements ToolOutputCacheStore {
88
106
  private resolvePath;
89
107
  }
90
108
 
91
- export { type McpAuthFile, McpAuthStore, type McpOAuthTokens, RunEventStoreFactoryImpl, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, ToolOutputCacheStoreImpl, ensureStorageDirs, resolveStoragePaths };
109
+ export { type McpAuthFile, McpAuthStore, type McpOAuthTokens, type ProjectsPolicyFile, ProjectsPolicyStore, RunEventStoreFactoryImpl, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, ToolOutputCacheStoreImpl, ensureStorageDirs, resolveStoragePaths };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { StoragePaths, ResolveStorageOptions, RunEventStoreFactory, RunEventStoreInit, SessionStore, StoragePathService, SessionStateStore, SessionState, SessionStateSummary, SessionRecord, ToolOutputCacheStore, ToolOutputCacheRecord, ToolOutputRef, ToolOutputCacheReadOptions, ToolOutputCacheSearchOptions } from '@codelia/core';
2
2
  export { ResolveStorageOptions, StorageLayout, StoragePathService, StoragePaths } from '@codelia/core';
3
+ import { ApprovalMode } from '@codelia/shared-types';
3
4
 
4
5
  type McpOAuthTokens = {
5
6
  access_token: string;
@@ -21,6 +22,23 @@ declare class McpAuthStore {
21
22
  save(auth: McpAuthFile): Promise<void>;
22
23
  }
23
24
 
25
+ type ProjectsPolicyFile = {
26
+ version: 1;
27
+ default?: {
28
+ approval_mode?: ApprovalMode;
29
+ };
30
+ projects?: Record<string, {
31
+ approval_mode?: ApprovalMode;
32
+ }>;
33
+ };
34
+ declare class ProjectsPolicyStore {
35
+ private readonly paths;
36
+ constructor(paths?: StoragePaths);
37
+ getFilePath(): string;
38
+ load(): Promise<ProjectsPolicyFile | null>;
39
+ save(data: ProjectsPolicyFile): Promise<void>;
40
+ }
41
+
24
42
  declare function resolveStoragePaths(options?: ResolveStorageOptions): StoragePaths;
25
43
  declare function ensureStorageDirs(paths: StoragePaths): Promise<void>;
26
44
 
@@ -88,4 +106,4 @@ declare class ToolOutputCacheStoreImpl implements ToolOutputCacheStore {
88
106
  private resolvePath;
89
107
  }
90
108
 
91
- export { type McpAuthFile, McpAuthStore, type McpOAuthTokens, RunEventStoreFactoryImpl, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, ToolOutputCacheStoreImpl, ensureStorageDirs, resolveStoragePaths };
109
+ export { type McpAuthFile, McpAuthStore, type McpOAuthTokens, type ProjectsPolicyFile, ProjectsPolicyStore, RunEventStoreFactoryImpl, SessionStateStoreImpl, SessionStoreWriterImpl, StoragePathServiceImpl, ToolOutputCacheStoreImpl, ensureStorageDirs, resolveStoragePaths };
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ var XDG_DIR_NAME = "codelia";
11
11
  var CONFIG_FILENAME = "config.json";
12
12
  var AUTH_FILENAME = "auth.json";
13
13
  var MCP_AUTH_FILENAME = "mcp-auth.json";
14
+ var PROJECTS_FILENAME = "projects.json";
14
15
  var CACHE_DIRNAME = "cache";
15
16
  var TOOL_OUTPUT_CACHE_DIRNAME = "tool-output";
16
17
  var SESSIONS_DIRNAME = "sessions";
@@ -50,6 +51,7 @@ function buildHomeLayout(root) {
50
51
  configFile: path.join(configDir, CONFIG_FILENAME),
51
52
  authFile: path.join(configDir, AUTH_FILENAME),
52
53
  mcpAuthFile: path.join(configDir, MCP_AUTH_FILENAME),
54
+ projectsFile: path.join(configDir, PROJECTS_FILENAME),
53
55
  cacheDir: path.join(root, CACHE_DIRNAME),
54
56
  toolOutputCacheDir: path.join(
55
57
  root,
@@ -74,6 +76,7 @@ function buildXdgLayout() {
74
76
  configFile: path.join(configDir, CONFIG_FILENAME),
75
77
  authFile: path.join(configDir, AUTH_FILENAME),
76
78
  mcpAuthFile: path.join(configDir, MCP_AUTH_FILENAME),
79
+ projectsFile: path.join(configDir, PROJECTS_FILENAME),
77
80
  cacheDir,
78
81
  toolOutputCacheDir: path.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
79
82
  sessionsDir: path.join(stateDir, SESSIONS_DIRNAME),
@@ -143,9 +146,112 @@ var McpAuthStore = class {
143
146
  }
144
147
  };
145
148
 
146
- // src/session-store.ts
149
+ // src/projects-store.ts
147
150
  import { promises as fs2 } from "fs";
148
151
  import path2 from "path";
152
+ import { parseApprovalMode } from "@codelia/shared-types";
153
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
154
+ var parseApprovalModeField = (fieldPath, value) => {
155
+ const parsed = parseApprovalMode(value);
156
+ if (!parsed) {
157
+ throw new Error(`${fieldPath} is invalid`);
158
+ }
159
+ return parsed;
160
+ };
161
+ var normalizeProjectsPolicyFile = (value) => {
162
+ if (!isRecord2(value)) {
163
+ throw new Error("projects policy must be an object");
164
+ }
165
+ if (value.version !== 1) {
166
+ throw new Error("projects policy version must be 1");
167
+ }
168
+ const normalized = { version: 1 };
169
+ const defaultValue = value.default;
170
+ if (defaultValue !== void 0) {
171
+ if (!isRecord2(defaultValue)) {
172
+ throw new Error("projects policy default must be an object");
173
+ }
174
+ if (defaultValue.approval_mode !== void 0) {
175
+ normalized.default = {
176
+ approval_mode: parseApprovalModeField(
177
+ "projects policy default.approval_mode",
178
+ defaultValue.approval_mode
179
+ )
180
+ };
181
+ }
182
+ }
183
+ const projectsValue = value.projects;
184
+ if (projectsValue !== void 0) {
185
+ if (!isRecord2(projectsValue)) {
186
+ throw new Error("projects policy projects must be an object");
187
+ }
188
+ const entries = {};
189
+ for (const [key, projectValue] of Object.entries(projectsValue)) {
190
+ if (!isRecord2(projectValue)) {
191
+ throw new Error(`projects policy projects['${key}'] must be an object`);
192
+ }
193
+ if (projectValue.approval_mode !== void 0) {
194
+ entries[key] = {
195
+ approval_mode: parseApprovalModeField(
196
+ `projects policy projects['${key}'].approval_mode`,
197
+ projectValue.approval_mode
198
+ )
199
+ };
200
+ }
201
+ }
202
+ if (Object.keys(entries).length > 0) {
203
+ normalized.projects = entries;
204
+ }
205
+ }
206
+ return normalized;
207
+ };
208
+ var atomicWriteFile = async (filePath, content) => {
209
+ const dirPath = path2.dirname(filePath);
210
+ const fileName = path2.basename(filePath);
211
+ const tempPath = path2.join(
212
+ dirPath,
213
+ `.${fileName}.${process.pid}.${Date.now()}.tmp`
214
+ );
215
+ await fs2.writeFile(tempPath, content, { mode: 384 });
216
+ await fs2.rename(tempPath, filePath);
217
+ if (process.platform !== "win32") {
218
+ await fs2.chmod(filePath, 384);
219
+ }
220
+ };
221
+ var ProjectsPolicyStore = class {
222
+ paths;
223
+ constructor(paths) {
224
+ this.paths = paths ?? resolveStoragePaths();
225
+ }
226
+ getFilePath() {
227
+ return this.paths.projectsFile;
228
+ }
229
+ async load() {
230
+ try {
231
+ const raw = await fs2.readFile(this.paths.projectsFile, "utf8");
232
+ const parsed = JSON.parse(raw);
233
+ return normalizeProjectsPolicyFile(parsed);
234
+ } catch (error) {
235
+ if (error.code === "ENOENT") {
236
+ return null;
237
+ }
238
+ throw error;
239
+ }
240
+ }
241
+ async save(data) {
242
+ if (data.version !== 1) {
243
+ throw new Error("projects policy version must be 1");
244
+ }
245
+ await ensureStorageDirs(this.paths);
246
+ const content = `${JSON.stringify(data, null, 2)}
247
+ `;
248
+ await atomicWriteFile(this.paths.projectsFile, content);
249
+ }
250
+ };
251
+
252
+ // src/session-store.ts
253
+ import { promises as fs3 } from "fs";
254
+ import path3 from "path";
149
255
  var pad2 = (value) => String(value).padStart(2, "0");
150
256
  var resolveDateParts = (startedAt) => {
151
257
  const parsed = new Date(startedAt);
@@ -163,14 +269,14 @@ var SessionStoreWriterImpl = class {
163
269
  constructor(options) {
164
270
  const paths = options.paths ?? resolveStoragePaths();
165
271
  const parts = resolveDateParts(options.startedAt);
166
- const baseDir = path2.join(
272
+ const baseDir = path3.join(
167
273
  paths.sessionsDir,
168
274
  parts.year,
169
275
  parts.month,
170
276
  parts.day
171
277
  );
172
- this.filePath = path2.join(baseDir, `${options.runId}.jsonl`);
173
- this.ensureDir = fs2.mkdir(baseDir, { recursive: true }).then(() => {
278
+ this.filePath = path3.join(baseDir, `${options.runId}.jsonl`);
279
+ this.ensureDir = fs3.mkdir(baseDir, { recursive: true }).then(() => {
174
280
  });
175
281
  }
176
282
  append(record) {
@@ -183,7 +289,7 @@ var SessionStoreWriterImpl = class {
183
289
  }
184
290
  const write = this.writeChain.then(async () => {
185
291
  await this.ensureDir;
186
- await fs2.appendFile(this.filePath, line, "utf8");
292
+ await fs3.appendFile(this.filePath, line, "utf8");
187
293
  });
188
294
  this.writeChain = write.catch(() => {
189
295
  });
@@ -209,15 +315,15 @@ var StoragePathServiceImpl = class {
209
315
  };
210
316
 
211
317
  // src/session-state.ts
212
- import { promises as fs3 } from "fs";
213
- import path3 from "path";
318
+ import { promises as fs4 } from "fs";
319
+ import path4 from "path";
214
320
  import { stringifyContent } from "@codelia/core";
215
321
  var LEGACY_STATE_DIRNAME = "state";
216
322
  var MESSAGES_DIRNAME = "messages";
217
323
  var STATE_DB_FILENAME = "state.db";
218
- var resolveLegacyStateDir = (paths) => path3.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
219
- var resolveMessagesDir = (paths) => path3.join(paths.sessionsDir, MESSAGES_DIRNAME);
220
- var resolveStateDbPath = (paths) => path3.join(paths.sessionsDir, STATE_DB_FILENAME);
324
+ var resolveLegacyStateDir = (paths) => path4.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
325
+ var resolveMessagesDir = (paths) => path4.join(paths.sessionsDir, MESSAGES_DIRNAME);
326
+ var resolveStateDbPath = (paths) => path4.join(paths.sessionsDir, STATE_DB_FILENAME);
221
327
  var extractLastUserMessage = (messages) => {
222
328
  for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
223
329
  const message = messages[idx];
@@ -264,21 +370,21 @@ var deserializeMessages = (payload) => {
264
370
  }
265
371
  return messages;
266
372
  };
267
- var atomicWriteFile = async (filePath, payload) => {
268
- const dirname = path3.dirname(filePath);
269
- const basename = path3.basename(filePath);
270
- const tempFile = path3.join(
373
+ var atomicWriteFile2 = async (filePath, payload) => {
374
+ const dirname = path4.dirname(filePath);
375
+ const basename = path4.basename(filePath);
376
+ const tempFile = path4.join(
271
377
  dirname,
272
378
  `${basename}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
273
379
  );
274
380
  let wroteTemp = false;
275
381
  try {
276
- await fs3.writeFile(tempFile, payload, "utf8");
382
+ await fs4.writeFile(tempFile, payload, "utf8");
277
383
  wroteTemp = true;
278
- await fs3.rename(tempFile, filePath);
384
+ await fs4.rename(tempFile, filePath);
279
385
  } catch (error) {
280
386
  if (wroteTemp) {
281
- await fs3.rm(tempFile, { force: true }).catch(() => {
387
+ await fs4.rm(tempFile, { force: true }).catch(() => {
282
388
  });
283
389
  }
284
390
  throw error;
@@ -299,9 +405,9 @@ var SessionStateStoreImpl = class {
299
405
  this.messagesDir = resolveMessagesDir(paths);
300
406
  this.stateDbPath = resolveStateDbPath(paths);
301
407
  this.ensureDirs = Promise.all([
302
- fs3.mkdir(paths.sessionsDir, { recursive: true }),
303
- fs3.mkdir(this.legacyStateDir, { recursive: true }),
304
- fs3.mkdir(this.messagesDir, { recursive: true })
408
+ fs4.mkdir(paths.sessionsDir, { recursive: true }),
409
+ fs4.mkdir(this.legacyStateDir, { recursive: true }),
410
+ fs4.mkdir(this.messagesDir, { recursive: true })
305
411
  ]).then(() => {
306
412
  });
307
413
  this.onError = options.onError;
@@ -316,10 +422,10 @@ var SessionStateStoreImpl = class {
316
422
  return this.db;
317
423
  }
318
424
  resolveLegacyPath(sessionId) {
319
- return path3.join(this.legacyStateDir, `${sessionId}.json`);
425
+ return path4.join(this.legacyStateDir, `${sessionId}.json`);
320
426
  }
321
427
  resolveMessagePath(sessionId) {
322
- return path3.join(this.messagesDir, `${sessionId}.jsonl`);
428
+ return path4.join(this.messagesDir, `${sessionId}.jsonl`);
323
429
  }
324
430
  async openDatabase() {
325
431
  await this.ensureDirs;
@@ -407,7 +513,7 @@ var SessionStateStoreImpl = class {
407
513
  }
408
514
  async loadLegacy(sessionId) {
409
515
  try {
410
- const file = await fs3.readFile(this.resolveLegacyPath(sessionId), "utf8");
516
+ const file = await fs4.readFile(this.resolveLegacyPath(sessionId), "utf8");
411
517
  const parsed = JSON.parse(file);
412
518
  if (!parsed || typeof parsed !== "object") return null;
413
519
  if (!parsed.session_id || !parsed.updated_at) return null;
@@ -445,7 +551,7 @@ var SessionStateStoreImpl = class {
445
551
  if (!row) return null;
446
552
  let messages;
447
553
  try {
448
- const payload = await fs3.readFile(
554
+ const payload = await fs4.readFile(
449
555
  this.resolveMessagePath(sessionId),
450
556
  "utf8"
451
557
  );
@@ -486,7 +592,7 @@ var SessionStateStoreImpl = class {
486
592
  const messagePayload = serializeMessages(
487
593
  Array.isArray(state.messages) ? state.messages : []
488
594
  );
489
- await atomicWriteFile(
595
+ await atomicWriteFile2(
490
596
  this.resolveMessagePath(state.session_id),
491
597
  messagePayload
492
598
  );
@@ -559,7 +665,7 @@ var SessionStateStoreImpl = class {
559
665
  async listLegacySummaries() {
560
666
  let entries;
561
667
  try {
562
- entries = await fs3.readdir(this.legacyStateDir, {
668
+ entries = await fs4.readdir(this.legacyStateDir, {
563
669
  withFileTypes: true,
564
670
  encoding: "utf8"
565
671
  });
@@ -571,9 +677,9 @@ var SessionStateStoreImpl = class {
571
677
  for (const entry of entries) {
572
678
  if (!entry.isFile()) continue;
573
679
  if (!entry.name.endsWith(".json")) continue;
574
- const filePath = path3.join(this.legacyStateDir, entry.name);
680
+ const filePath = path4.join(this.legacyStateDir, entry.name);
575
681
  try {
576
- const contents = await fs3.readFile(filePath, "utf8");
682
+ const contents = await fs4.readFile(filePath, "utf8");
577
683
  const parsed = JSON.parse(contents);
578
684
  if (!parsed || typeof parsed !== "object") continue;
579
685
  if (!parsed.session_id || !parsed.updated_at) continue;
@@ -618,8 +724,8 @@ var SessionStateStoreImpl = class {
618
724
  };
619
725
 
620
726
  // src/tool-output-cache.ts
621
- import { promises as fs4 } from "fs";
622
- import path4 from "path";
727
+ import { promises as fs5 } from "fs";
728
+ import path5 from "path";
623
729
  var DEFAULT_MAX_MATCHES = 50;
624
730
  var normalizeRefId = (refId) => refId.replace(/[^a-zA-Z0-9_-]/g, "_");
625
731
  var formatLineNumber = (lineNumber) => String(lineNumber).padStart(5, " ");
@@ -633,15 +739,15 @@ var ToolOutputCacheStoreImpl = class {
633
739
  async save(record) {
634
740
  const refId = normalizeRefId(record.tool_call_id);
635
741
  const filePath = this.resolvePath(refId);
636
- await fs4.mkdir(this.baseDir, { recursive: true });
637
- await fs4.writeFile(filePath, record.content, "utf8");
742
+ await fs5.mkdir(this.baseDir, { recursive: true });
743
+ await fs5.writeFile(filePath, record.content, "utf8");
638
744
  const byteSize = Buffer.byteLength(record.content, "utf8");
639
745
  const lineCount = record.content.split(/\r?\n/).length;
640
746
  return { id: refId, byte_size: byteSize, line_count: lineCount };
641
747
  }
642
748
  async read(refId, options = {}) {
643
749
  const filePath = this.resolvePath(refId);
644
- const content = await fs4.readFile(filePath, "utf8");
750
+ const content = await fs5.readFile(filePath, "utf8");
645
751
  const lines = content.split(/\r?\n/);
646
752
  const offset = options.offset ?? 0;
647
753
  const limit = options.limit ?? lines.length;
@@ -653,7 +759,7 @@ var ToolOutputCacheStoreImpl = class {
653
759
  }
654
760
  async grep(refId, options) {
655
761
  const filePath = this.resolvePath(refId);
656
- const content = await fs4.readFile(filePath, "utf8");
762
+ const content = await fs5.readFile(filePath, "utf8");
657
763
  const lines = content.split(/\r?\n/);
658
764
  const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
659
765
  const before = Math.max(0, options.before ?? 0);
@@ -676,11 +782,12 @@ ${snippet}`);
676
782
  ... (truncated)` : results.join("\n\n");
677
783
  }
678
784
  resolvePath(refId) {
679
- return path4.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
785
+ return path5.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
680
786
  }
681
787
  };
682
788
  export {
683
789
  McpAuthStore,
790
+ ProjectsPolicyStore,
684
791
  RunEventStoreFactoryImpl,
685
792
  SessionStateStoreImpl,
686
793
  SessionStoreWriterImpl,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codelia/storage",
3
- "version": "0.1.19",
3
+ "version": "0.1.21",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=20 <25"
@@ -23,7 +23,8 @@
23
23
  "typecheck": "tsc --noEmit"
24
24
  },
25
25
  "dependencies": {
26
- "@codelia/core": "0.1.19",
26
+ "@codelia/core": "0.1.21",
27
+ "@codelia/shared-types": "0.1.21",
27
28
  "better-sqlite3": "^12.6.2"
28
29
  },
29
30
  "publishConfig": {