@codelia/storage 0.1.85 → 0.1.89

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,8 +1,42 @@
1
+ // src/atomic-file.ts
2
+ import { randomUUID } from "crypto";
3
+ import { promises as fs } from "fs";
4
+ import path from "path";
5
+ var writeFileAtomic = async (targetPath, data, options = {}) => {
6
+ const mode = options.mode ?? 384;
7
+ const dir = path.dirname(targetPath);
8
+ const base = path.basename(targetPath);
9
+ const temporary = path.join(dir, `.${base}.${randomUUID()}.tmp`);
10
+ let handle;
11
+ try {
12
+ handle = await fs.open(temporary, "wx", mode);
13
+ await handle.writeFile(data, "utf8");
14
+ await handle.sync();
15
+ await handle.close();
16
+ handle = void 0;
17
+ try {
18
+ await fs.chmod(temporary, mode);
19
+ } catch {
20
+ }
21
+ await fs.rename(temporary, targetPath);
22
+ try {
23
+ await fs.chmod(targetPath, mode);
24
+ } catch {
25
+ }
26
+ } catch (error) {
27
+ if (handle) {
28
+ await handle.close().catch(() => void 0);
29
+ }
30
+ await fs.unlink(temporary).catch(() => void 0);
31
+ throw error;
32
+ }
33
+ };
34
+
1
35
  // src/attachments.ts
2
- import { createHash as createHash2, randomUUID } from "crypto";
36
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
3
37
  import { constants as constants2 } from "fs";
4
38
  import { lstat, mkdir, open as open2, rename, rm, writeFile } from "fs/promises";
5
- import path from "path";
39
+ import path2 from "path";
6
40
 
7
41
  // src/image-files.ts
8
42
  import { createHash } from "crypto";
@@ -44,7 +78,7 @@ var SHA256 = /^[0-9a-f]{64}$/;
44
78
  var MAX_BYTES = 32 * 1024 * 1024;
45
79
  var BLOCK_BYTES = 64 * 1024;
46
80
  var digest = (bytes) => createHash2("sha256").update(bytes).digest("hex");
47
- var createAttachmentId = () => `codelia-attachment-${randomUUID()}`;
81
+ var createAttachmentId = () => `codelia-attachment-${randomUUID2()}`;
48
82
  var isAttachmentId = (id2) => ID.test(id2);
49
83
  var FileAttachmentStore = class {
50
84
  constructor(root, images) {
@@ -56,9 +90,9 @@ var FileAttachmentStore = class {
56
90
  resolveImage = (ref) => this.images.resolve(ref);
57
91
  async commit(sessionId, entries2) {
58
92
  if (!entries2.length) return;
59
- const batch = randomUUID();
60
- const marker = path.join(this.root, "committed", batch);
61
- await mkdir(path.join(this.root, "committed"), {
93
+ const batch = randomUUID2();
94
+ const marker = path2.join(this.root, "committed", batch);
95
+ await mkdir(path2.join(this.root, "committed"), {
62
96
  recursive: true,
63
97
  mode: 448
64
98
  });
@@ -70,7 +104,7 @@ var FileAttachmentStore = class {
70
104
  if (!isAttachmentId(ref.attachment_id) || bytes.length !== ref.byte_size || bytes.length > MAX_BYTES || digest(bytes) !== ref.sha256) {
71
105
  throw new Error("Invalid attachment original");
72
106
  }
73
- const dir = path.join(this.root, ref.attachment_id);
107
+ const dir = path2.join(this.root, ref.attachment_id);
74
108
  await mkdir(dir, { mode: 448 });
75
109
  created.push(dir);
76
110
  const metadata = { ...record2, sessionId, batch };
@@ -87,13 +121,13 @@ var FileAttachmentStore = class {
87
121
  digest(bytes.subarray(offset, offset + BLOCK_BYTES))
88
122
  );
89
123
  }
90
- await writeFile(path.join(dir, "original"), bytes, {
124
+ await writeFile(path2.join(dir, "original"), bytes, {
91
125
  flag: "wx",
92
126
  mode: 384
93
127
  });
94
128
  }
95
129
  await writeFile(
96
- path.join(dir, "metadata.json"),
130
+ path2.join(dir, "metadata.json"),
97
131
  JSON.stringify(metadata),
98
132
  { flag: "wx", mode: 384 }
99
133
  );
@@ -111,122 +145,2239 @@ var FileAttachmentStore = class {
111
145
  throw error;
112
146
  }
113
147
  }
114
- async lookup(attachmentId, sessionId) {
115
- const metadata = await this.metadata(attachmentId, sessionId);
116
- if (!metadata) return null;
117
- const { ref, imageRef } = metadata;
118
- if (imageRef) {
119
- await this.readImage(metadata);
120
- } else {
121
- const bytes = await readImageFileBounded(
122
- path.join(this.root, attachmentId, "original"),
123
- ref.byte_size
148
+ async lookup(attachmentId, sessionId) {
149
+ const metadata = await this.metadata(attachmentId, sessionId);
150
+ if (!metadata) return null;
151
+ const { ref, imageRef } = metadata;
152
+ if (imageRef) {
153
+ await this.readImage(metadata);
154
+ } else {
155
+ const bytes = await readImageFileBounded(
156
+ path2.join(this.root, attachmentId, "original"),
157
+ ref.byte_size
158
+ );
159
+ if (bytes.length !== ref.byte_size || digest(bytes) !== ref.sha256)
160
+ throw new Error("Attachment original is corrupt");
161
+ }
162
+ return { ref, ...imageRef ? { imageRef } : {} };
163
+ }
164
+ async read(attachmentId, sessionId, offset, length) {
165
+ const metadata = await this.metadata(attachmentId, sessionId);
166
+ if (!metadata) throw new Error("Attachment unavailable in this session");
167
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || length > 256 * 1024)
168
+ throw new Error("Invalid attachment byte range");
169
+ const end = Math.min(offset + length, metadata.ref.byte_size);
170
+ if (metadata.imageRef)
171
+ return (await this.readImage(metadata)).subarray(offset, end);
172
+ const file = await open2(
173
+ path2.join(this.root, attachmentId, "original"),
174
+ constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0) | (constants2.O_NONBLOCK ?? 0)
175
+ );
176
+ try {
177
+ const stat = await file.stat();
178
+ if (!stat.isFile() || stat.size !== metadata.ref.byte_size)
179
+ throw new Error("Attachment original is corrupt");
180
+ if (offset >= end) return Buffer.alloc(0);
181
+ const firstBlock = Math.floor(offset / BLOCK_BYTES);
182
+ const lastBlock = Math.ceil(end / BLOCK_BYTES);
183
+ const start = firstBlock * BLOCK_BYTES;
184
+ const bytes = Buffer.alloc(
185
+ Math.min(lastBlock * BLOCK_BYTES, stat.size) - start
186
+ );
187
+ let count = 0;
188
+ while (count < bytes.length) {
189
+ const result = await file.read(
190
+ bytes,
191
+ count,
192
+ bytes.length - count,
193
+ start + count
194
+ );
195
+ if (!result.bytesRead)
196
+ throw new Error("Attachment original is corrupt");
197
+ count += result.bytesRead;
198
+ }
199
+ for (let block = firstBlock; block < lastBlock; block++) {
200
+ const beg = (block - firstBlock) * BLOCK_BYTES;
201
+ if (metadata.blocks?.[block] !== digest(bytes.subarray(beg, beg + BLOCK_BYTES))) {
202
+ throw new Error("Attachment original is corrupt");
203
+ }
204
+ }
205
+ return bytes.subarray(offset - start, end - start);
206
+ } finally {
207
+ await file.close();
208
+ }
209
+ }
210
+ async metadata(attachmentId, sessionId) {
211
+ if (!isAttachmentId(attachmentId)) return null;
212
+ const dir = path2.join(this.root, attachmentId);
213
+ try {
214
+ if (!(await lstat(dir)).isDirectory()) return null;
215
+ const metadata = JSON.parse(
216
+ (await readImageFileBounded(path2.join(dir, "metadata.json"), 64 * 1024)).toString()
217
+ );
218
+ const { ref, imageRef, blocks } = metadata;
219
+ if (metadata.sessionId !== sessionId || !UUID.test(metadata.batch) || ref?.attachment_id !== attachmentId)
220
+ return null;
221
+ if (!Number.isSafeInteger(ref.byte_size) || ref.byte_size < 0 || ref.byte_size > MAX_BYTES || !SHA256.test(ref.sha256) || typeof ref.media_type !== "string" || typeof ref.display_name !== "string")
222
+ throw new Error("Invalid attachment metadata");
223
+ if (!imageRef && (!Array.isArray(blocks) || blocks.length !== Math.ceil(ref.byte_size / BLOCK_BYTES)))
224
+ throw new Error("Invalid attachment block index");
225
+ const marker = path2.join(this.root, "committed", metadata.batch);
226
+ return (await lstat(marker)).isFile() ? metadata : null;
227
+ } catch (error) {
228
+ if (error.code === "ENOENT") return null;
229
+ throw error;
230
+ }
231
+ }
232
+ async readImage({
233
+ ref,
234
+ imageRef,
235
+ sessionId
236
+ }) {
237
+ if (!imageRef || imageRef.sha256 !== ref.sha256 || imageRef.byte_size !== ref.byte_size || imageRef.media_type !== ref.media_type || imageRef.width !== ref.width || imageRef.height !== ref.height)
238
+ throw new Error("Invalid image attachment reference");
239
+ const { metadata, bytes } = await this.images.read(
240
+ imageRef.artifact_id,
241
+ sessionId
242
+ );
243
+ if (metadata.kind !== "attachment" || metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size || metadata.media_type !== ref.media_type || metadata.width !== ref.width || metadata.height !== ref.height)
244
+ throw new Error("Image attachment original is corrupt");
245
+ return bytes;
246
+ }
247
+ };
248
+
249
+ // src/auth-lock.ts
250
+ import { randomUUID as randomUUID3 } from "crypto";
251
+ import { promises as fs3 } from "fs";
252
+ import path4 from "path";
253
+ import { setTimeout as delay } from "timers/promises";
254
+
255
+ // src/sqlite.ts
256
+ var openSqlite = async (filename) => {
257
+ if (process.versions.bun) {
258
+ const bunSqliteSpecifier = "bun:sqlite";
259
+ const { Database } = await import(bunSqliteSpecifier);
260
+ const db2 = new Database(filename, { create: true });
261
+ return {
262
+ close: () => db2.close(),
263
+ exec: (sql) => {
264
+ db2.exec(sql);
265
+ },
266
+ run: (sql, params = []) => {
267
+ db2.query(sql).run(...params);
268
+ },
269
+ get: (sql, params = []) => {
270
+ const row = db2.query(sql).get(...params);
271
+ return row ?? void 0;
272
+ },
273
+ all: (sql, params = []) => db2.query(sql).all(...params)
274
+ };
275
+ }
276
+ const betterSqliteSpecifier = "better-sqlite3";
277
+ const betterSqliteModule = await import(betterSqliteSpecifier);
278
+ const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
279
+ const db = new BetterSqlite3(filename);
280
+ return {
281
+ close: () => db.close(),
282
+ exec: (sql) => {
283
+ db.exec(sql);
284
+ },
285
+ run: (sql, params = []) => {
286
+ db.prepare(sql).run(...params);
287
+ },
288
+ get: (sql, params = []) => {
289
+ const row = db.prepare(sql).get(...params);
290
+ return row ?? void 0;
291
+ },
292
+ all: (sql, params = []) => db.prepare(sql).all(...params)
293
+ };
294
+ };
295
+
296
+ // src/windows-acl.ts
297
+ import { execFile, execFileSync } from "child_process";
298
+ import { promises as fs2, lstatSync } from "fs";
299
+ import path3 from "path";
300
+ import { promisify } from "util";
301
+ var execFileAsync = promisify(execFile);
302
+ var resolveWindowsSystem32Dir = (env = process.env) => {
303
+ const root = (env.SystemRoot ?? env.WINDIR ?? "").trim() || "C:\\Windows";
304
+ if (!/^[A-Za-z]:\\/u.test(root) || root.includes("..")) {
305
+ throw new Error("unsafe_windows_credentials_acl: invalid_system_root");
306
+ }
307
+ return path3.win32.join(root, "System32");
308
+ };
309
+ var execOptions = {
310
+ windowsHide: true,
311
+ timeout: 5e3,
312
+ maxBuffer: 32 * 1024
313
+ };
314
+ var defaultRunner = async (exe, args, options) => execFileAsync(exe, [...args], { ...options, ...execOptions });
315
+ var aclScript = `
316
+ $ErrorActionPreference = 'Stop'
317
+ $target = $env:CODELIA_ACL_TARGET
318
+ $operation = $env:CODELIA_ACL_OPERATION
319
+ $legacy = $operation -eq 'legacy_file'
320
+ $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
321
+ $system = [System.Security.Principal.SecurityIdentifier]::new('S-1-5-18')
322
+ $administrators = 'S-1-5-32-544'
323
+ $sections = [System.Security.AccessControl.AccessControlSections]'Owner, Access'
324
+ $inherit = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
325
+ $inheritAces = [System.Security.AccessControl.AceFlags]'ContainerInherit, ObjectInherit'
326
+ $full = [System.Security.AccessControl.FileSystemRights]::FullControl
327
+ # Include generic read and execute if Windows left the generic bits unmapped.
328
+ $legacyReadMask = (
329
+ [int][System.Security.AccessControl.FileSystemRights]::ReadAndExecute -bor
330
+ [int][System.Security.AccessControl.FileSystemRights]::Synchronize -bor
331
+ [int]::MinValue -bor 0x20000000
332
+ )
333
+
334
+ function Get-TargetType([string]$file, [bool]$directory) {
335
+ try {
336
+ $attributes = [System.IO.File]::GetAttributes($file)
337
+ } catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] {
338
+ return 'missing'
339
+ }
340
+ if ($attributes -band [System.IO.FileAttributes]::ReparsePoint) { return 'reparse_point' }
341
+ if ([bool]($attributes -band [System.IO.FileAttributes]::Directory) -ne $directory) {
342
+ return 'unexpected_target_type'
343
+ }
344
+ return 'ok'
345
+ }
346
+
347
+ function Test-CredentialAcl($acl, [bool]$directory) {
348
+ $descriptor = [System.Security.AccessControl.RawSecurityDescriptor]::new(
349
+ $acl.GetSecurityDescriptorBinaryForm(), 0)
350
+ if ($descriptor.Owner.Value -ne $user.Value) { return 'owner_mismatch' }
351
+ if ($null -eq $descriptor.DiscretionaryAcl) { return 'null_dacl' }
352
+ if ($directory -and -not $acl.AreAccessRulesProtected) { return 'unprotected_dacl' }
353
+ $hasUser = $false
354
+ foreach ($ace in $descriptor.DiscretionaryAcl) {
355
+ if ($legacy -and ($ace.AceType -eq [System.Security.AccessControl.AceType]::AccessDenied -or
356
+ $ace.AceFlags.HasFlag([System.Security.AccessControl.AceFlags]::InheritOnly))) { continue }
357
+ if ($ace.AceType -ne [System.Security.AccessControl.AceType]::AccessAllowed) {
358
+ return 'unexpected_ace_type'
359
+ }
360
+ $sid = $ace.SecurityIdentifier.Value
361
+ if ($legacy) {
362
+ # The old config root may have inherited Administrators and read grants.
363
+ if ($sid -ne $user.Value -and $sid -ne $system.Value -and $sid -ne $administrators -and
364
+ ($ace.AccessMask -band (-bnot $legacyReadMask))) { return 'legacy_write_grant' }
365
+ continue
366
+ }
367
+ if ($sid -ne $user.Value -and $sid -ne $system.Value) { return 'unexpected_principals' }
368
+ if ($directory -and ($ace.AccessMask -ne [int]$full -or $ace.AceFlags -ne $inheritAces)) {
369
+ return 'unexpected_directory_ace'
370
+ }
371
+ if ($sid -eq $user.Value) { $hasUser = $true }
372
+ }
373
+ if (-not $legacy -and -not $hasUser) { return 'missing_user_grant' }
374
+ return 'ok'
375
+ }
376
+
377
+ if ($operation -eq 'ensure_directory') {
378
+ $targetType = Get-TargetType $target $true
379
+ if ($targetType -ne 'ok') { $targetType; exit }
380
+ $acl = [System.IO.Directory]::GetAccessControl($target, $sections)
381
+ $result = Test-CredentialAcl $acl $true
382
+ if ($result -eq 'ok' -or $result -eq 'owner_mismatch') { $result; exit }
383
+
384
+ $privateAcl = [System.Security.AccessControl.DirectorySecurity]::new()
385
+ $privateAcl.SetAccessRuleProtection($true, $false)
386
+ $propagate = [System.Security.AccessControl.PropagationFlags]::None
387
+ $allow = [System.Security.AccessControl.AccessControlType]::Allow
388
+ $privateAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new(
389
+ $user, $full, $inherit, $propagate, $allow))
390
+ if ($user.Value -ne $system.Value) {
391
+ $privateAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new(
392
+ $system, $full, $inherit, $propagate, $allow))
393
+ }
394
+ [System.IO.Directory]::SetAccessControl($target, $privateAcl)
395
+ $targetType = Get-TargetType $target $true
396
+ if ($targetType -ne 'ok') { $targetType; exit }
397
+ Test-CredentialAcl ([System.IO.Directory]::GetAccessControl($target, $sections)) $true
398
+ exit
399
+ }
400
+
401
+ if ($operation -eq 'file') {
402
+ $parent = [System.IO.Path]::GetDirectoryName($target)
403
+ $parentType = Get-TargetType $parent $true
404
+ if ($parentType -ne 'ok') { $parentType; exit }
405
+ $parentAcl = Test-CredentialAcl ([System.IO.Directory]::GetAccessControl($parent, $sections)) $true
406
+ if ($parentAcl -ne 'ok') { $parentAcl; exit }
407
+ }
408
+ try {
409
+ $targetType = Get-TargetType $target $false
410
+ if ($targetType -ne 'ok') { $targetType; exit }
411
+ Test-CredentialAcl ([System.IO.File]::GetAccessControl($target, $sections)) $false
412
+ } catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] {
413
+ 'missing'
414
+ }
415
+ `;
416
+ var encodedAclScript = Buffer.from(aclScript, "utf16le").toString("base64");
417
+ function aclCommand(target, operation, env) {
418
+ const system32 = resolveWindowsSystem32Dir(env);
419
+ return {
420
+ exe: path3.win32.join(
421
+ system32,
422
+ "WindowsPowerShell",
423
+ "v1.0",
424
+ "powershell.exe"
425
+ ),
426
+ args: [
427
+ "-NoProfile",
428
+ "-NonInteractive",
429
+ "-EncodedCommand",
430
+ encodedAclScript
431
+ ],
432
+ options: {
433
+ cwd: system32,
434
+ env: {
435
+ ...env,
436
+ CODELIA_ACL_TARGET: path3.win32.resolve(target),
437
+ CODELIA_ACL_OPERATION: operation
438
+ }
439
+ }
440
+ };
441
+ }
442
+ var aclFailures = /* @__PURE__ */ new Set([
443
+ "missing",
444
+ "owner_mismatch",
445
+ "reparse_point",
446
+ "unexpected_target_type",
447
+ "null_dacl",
448
+ "unprotected_dacl",
449
+ "unexpected_ace_type",
450
+ "unexpected_principals",
451
+ "legacy_write_grant",
452
+ "unexpected_directory_ace",
453
+ "missing_user_grant"
454
+ ]);
455
+ function verifyAclResult(stdout, operation) {
456
+ const result = stdout.trim();
457
+ if (result === "ok") return true;
458
+ if (operation !== "ensure_directory" && result === "missing") return false;
459
+ const reason = aclFailures.has(result) ? result : "invalid_probe_result";
460
+ throw new Error(`unsafe_windows_credentials_acl: ${reason}`);
461
+ }
462
+ async function runAclCommand(target, operation, runner, env) {
463
+ const { exe, args, options } = aclCommand(target, operation, env);
464
+ let stdout;
465
+ try {
466
+ ({ stdout } = await runner(exe, args, options));
467
+ } catch {
468
+ throw new Error("unsafe_windows_credentials_acl: acl_probe_failed");
469
+ }
470
+ return verifyAclResult(stdout, operation);
471
+ }
472
+ var enforceWindowsOwnerOnlyDacl = async (dirPath, runner = defaultRunner, env = process.env) => {
473
+ await runAclCommand(dirPath, "ensure_directory", runner, env);
474
+ };
475
+ var isMissing = (error) => error?.code === "ENOENT";
476
+ var verifyWindowsCredentialFileAcl = async (filePath, legacy = false) => {
477
+ if (process.platform !== "win32") return true;
478
+ try {
479
+ await fs2.lstat(filePath);
480
+ } catch (error) {
481
+ if (isMissing(error)) return false;
482
+ throw error;
483
+ }
484
+ return runAclCommand(
485
+ filePath,
486
+ legacy ? "legacy_file" : "file",
487
+ defaultRunner,
488
+ process.env
489
+ );
490
+ };
491
+ var verifyWindowsCredentialFileAclSync = (filePath, legacy = false) => {
492
+ if (process.platform !== "win32") return true;
493
+ try {
494
+ lstatSync(filePath);
495
+ } catch (error) {
496
+ if (isMissing(error)) return false;
497
+ throw error;
498
+ }
499
+ const operation = legacy ? "legacy_file" : "file";
500
+ const { exe, args, options } = aclCommand(filePath, operation, process.env);
501
+ let stdout;
502
+ try {
503
+ stdout = execFileSync(exe, args, {
504
+ ...options,
505
+ ...execOptions,
506
+ encoding: "utf8",
507
+ stdio: ["ignore", "pipe", "pipe"]
508
+ });
509
+ } catch {
510
+ throw new Error("unsafe_windows_credentials_acl: acl_probe_failed");
511
+ }
512
+ return verifyAclResult(stdout, operation);
513
+ };
514
+ var ensureCredentialsDirectory = async (credentialsDir, options) => {
515
+ const platform = options?.platform ?? process.platform;
516
+ await fs2.mkdir(credentialsDir, { recursive: true, mode: 448 });
517
+ if (platform === "win32") {
518
+ await enforceWindowsOwnerOnlyDacl(credentialsDir, options?.windowsRunner);
519
+ return;
520
+ }
521
+ const info = await fs2.lstat(credentialsDir);
522
+ if (!info.isDirectory() || info.uid !== process.geteuid?.()) {
523
+ throw new Error("unsafe_credentials_directory");
524
+ }
525
+ if ((info.mode & 511) !== 448) await fs2.chmod(credentialsDir, 448);
526
+ };
527
+
528
+ // src/auth-lock.ts
529
+ var DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 3e4;
530
+ var DEFAULT_AUTH_LOCK_TIMEOUT_MS = 35e3;
531
+ var DEFAULT_POLL_MS = 25;
532
+ var inProcessQueues = /* @__PURE__ */ new Map();
533
+ var authLockPathFor = (dir) => path4.join(dir, ".auth-store-lock.sqlite");
534
+ var isMissing2 = (error) => error?.code === "ENOENT";
535
+ var lstatIfPresent = (file) => fs3.lstat(file).catch((error) => {
536
+ if (!isMissing2(error)) throw error;
537
+ return void 0;
538
+ });
539
+ var verifyLockFile = async (file) => {
540
+ const info = await lstatIfPresent(file);
541
+ if (!info) return;
542
+ const uid = process.geteuid?.();
543
+ if (!info.isFile() || info.size === 0 || uid !== void 0 && (info.uid !== uid || (info.mode & 18) !== 0)) {
544
+ throw new Error("unsafe_auth_store_lock");
545
+ }
546
+ };
547
+ var initializeLockFile = async (lockPath) => {
548
+ if (await lstatIfPresent(lockPath)) return;
549
+ const temporary = `${lockPath}.${randomUUID3()}.tmp`;
550
+ try {
551
+ const file = await fs3.open(temporary, "wx", 384);
552
+ await file.close();
553
+ const db = await openSqlite(temporary);
554
+ try {
555
+ db.exec("PRAGMA user_version = 1");
556
+ } finally {
557
+ db.close();
558
+ }
559
+ try {
560
+ await fs3.link(temporary, lockPath);
561
+ } catch (error) {
562
+ if (error.code !== "EEXIST") throw error;
563
+ }
564
+ } finally {
565
+ await fs3.unlink(temporary).catch(() => void 0);
566
+ }
567
+ };
568
+ var isSqliteBusy = (error) => {
569
+ const code = error?.code;
570
+ if (code === "SQLITE_BUSY" || code === "SQLITE_LOCKED") return true;
571
+ const message = error instanceof Error ? error.message : String(error);
572
+ return /database is locked|SQLITE_BUSY/i.test(message);
573
+ };
574
+ var openAuthLock = async (lockPath, timeoutMs, pollMs) => {
575
+ await ensureCredentialsDirectory(path4.dirname(lockPath));
576
+ await initializeLockFile(lockPath);
577
+ await verifyLockFile(lockPath);
578
+ if (process.platform === "win32") {
579
+ if (!await verifyWindowsCredentialFileAcl(lockPath)) {
580
+ throw new Error("unsafe_auth_store_lock");
581
+ }
582
+ await Promise.all(
583
+ ["-journal", "-wal", "-shm"].map(
584
+ (suffix) => verifyWindowsCredentialFileAcl(lockPath + suffix)
585
+ )
586
+ );
587
+ }
588
+ const db = await openSqlite(lockPath);
589
+ const deadline = performance.now() + timeoutMs;
590
+ try {
591
+ db.exec("PRAGMA busy_timeout = 0");
592
+ for (; ; ) {
593
+ try {
594
+ db.exec("BEGIN IMMEDIATE");
595
+ return db;
596
+ } catch (error) {
597
+ if (!isSqliteBusy(error) || performance.now() >= deadline) {
598
+ throw error;
599
+ }
600
+ await delay(pollMs);
601
+ }
602
+ }
603
+ } catch (error) {
604
+ db.close();
605
+ throw error;
606
+ }
607
+ };
608
+ var enqueueInProcess = async (key, fn) => {
609
+ const previous = inProcessQueues.get(key) ?? Promise.resolve();
610
+ const next = previous.then(fn, fn);
611
+ const settled = next.then(
612
+ () => void 0,
613
+ () => void 0
614
+ );
615
+ inProcessQueues.set(key, settled);
616
+ try {
617
+ return await next;
618
+ } finally {
619
+ if (inProcessQueues.get(key) === settled) inProcessQueues.delete(key);
620
+ }
621
+ };
622
+ var withAuthStoreLock = (lockPath, fn, options = {}) => {
623
+ const resolved = path4.resolve(lockPath);
624
+ const timeoutMs = options.timeoutMs ?? DEFAULT_AUTH_LOCK_TIMEOUT_MS;
625
+ const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
626
+ return enqueueInProcess(resolved, async () => {
627
+ const db = await openAuthLock(resolved, timeoutMs, pollMs);
628
+ try {
629
+ return await fn();
630
+ } finally {
631
+ try {
632
+ db.exec("ROLLBACK");
633
+ } catch {
634
+ }
635
+ db.close();
636
+ }
637
+ });
638
+ };
639
+
640
+ // src/macos-keychain.ts
641
+ import { execFile as execFile2, execFileSync as execFileSync2, spawn } from "child_process";
642
+ import { createHash as createHash3 } from "crypto";
643
+ import { accessSync, constants as constants3, realpathSync } from "fs";
644
+ import os from "os";
645
+ import path5 from "path";
646
+ var CODELIA_AUTH_KEYCHAIN_SERVICE = "codelia.auth";
647
+ var CODELIA_MCP_AUTH_KEYCHAIN_SERVICE = "codelia.mcp-auth";
648
+ var DEFAULT_SECURITY_PATH = "/usr/bin/security";
649
+ var DEFAULT_ASYNC_TIMEOUT_MS = 5e3;
650
+ var DEFAULT_SYNC_TIMEOUT_MS = 2e3;
651
+ var AUTHORIZATION_TIMEOUT_MS = 12e4;
652
+ var MAX_SECURITY_BUFFER = 8 * 1024 * 1024;
653
+ var SECURITY_INTERACTIVE_MAX_LINE_BYTES = 4096;
654
+ var MAX_STDERR_CAPTURE_BYTES = 16384;
655
+ var MAX_CHUNKS = 64;
656
+ var SWEEP_CONSECUTIVE_MISS_LIMIT = 2;
657
+ var MAX_SNAPSHOT_ATTEMPTS = 3;
658
+ var CHUNK_RAW_BYTES = 1800;
659
+ var MAX_KEYCHAIN_PAYLOAD_BYTES = MAX_CHUNKS * CHUNK_RAW_BYTES;
660
+ var CHUNK_PREFIX = "cb1:";
661
+ var GEN_POINTER_PREFIX = "cb2:";
662
+ var SAFE_TOKEN_RE = /^[A-Za-z0-9._:#-]+$/;
663
+ var KeychainError = class extends Error {
664
+ code;
665
+ constructor(code, message) {
666
+ super(message);
667
+ this.name = "KeychainError";
668
+ this.code = code;
669
+ }
670
+ };
671
+ var canonicalDirForHash = (configDir) => {
672
+ const resolved = path5.resolve(configDir);
673
+ try {
674
+ return realpathSync(resolved);
675
+ } catch {
676
+ return resolved;
677
+ }
678
+ };
679
+ var keychainAccountForConfigDir = (configDir) => {
680
+ const digest2 = createHash3("sha256").update(canonicalDirForHash(configDir)).digest("hex").slice(0, 16);
681
+ return `codelia-${digest2}`;
682
+ };
683
+ var validateKeychainToken = (label2, value) => {
684
+ if (!value || !SAFE_TOKEN_RE.test(value)) {
685
+ throw new KeychainError(
686
+ "keychain_error",
687
+ `Invalid Keychain ${label2} identifier`
688
+ );
689
+ }
690
+ };
691
+ var chunkServiceName = (service, index) => index === 0 ? service : `${service}#${index}`;
692
+ var genChunkServiceName = (service, gen, index) => `${service}#g:${gen}:${index}`;
693
+ var encodePayloadChunks = (value) => {
694
+ const raw = Buffer.from(value, "utf8");
695
+ const total = Math.max(1, Math.ceil(raw.length / CHUNK_RAW_BYTES));
696
+ if (total > MAX_CHUNKS) {
697
+ throw new KeychainError(
698
+ "keychain_error",
699
+ `Keychain payload exceeds maximum size (${MAX_KEYCHAIN_PAYLOAD_BYTES} bytes)`
700
+ );
701
+ }
702
+ const chunks = [];
703
+ for (let i = 0; i < total; i += 1) {
704
+ const slice = raw.subarray(
705
+ i * CHUNK_RAW_BYTES,
706
+ Math.min(raw.length, (i + 1) * CHUNK_RAW_BYTES)
707
+ );
708
+ chunks.push(`${CHUNK_PREFIX}${total}:${slice.toString("base64")}`);
709
+ }
710
+ return chunks;
711
+ };
712
+ var FIXED_GEN_SLOTS = ["a", "b"];
713
+ var parseGenPointer = (raw) => {
714
+ if (!raw.startsWith(GEN_POINTER_PREFIX)) return null;
715
+ const parts = raw.slice(GEN_POINTER_PREFIX.length).split(":");
716
+ if (parts.length !== 2) {
717
+ throw new KeychainError(
718
+ "keychain_error",
719
+ "Corrupt Keychain generation pointer"
720
+ );
721
+ }
722
+ const [gen, totalStr] = parts;
723
+ const countAndDigest = /^([1-9][0-9]*)(?:\.([a-f0-9]{64}))?$/.exec(totalStr);
724
+ const total = Number(countAndDigest?.[1]);
725
+ if (!/^(?:a|b|[0-9a-f]{8,16})$/.test(gen) || !Number.isInteger(total) || total < 1 || total > MAX_CHUNKS) {
726
+ throw new KeychainError(
727
+ "keychain_error",
728
+ "Corrupt Keychain generation pointer metadata"
729
+ );
730
+ }
731
+ return { gen, total, digest: countAndDigest?.[2] };
732
+ };
733
+ var parseChunkEnvelope = (raw) => {
734
+ if (!raw.startsWith(CHUNK_PREFIX)) return null;
735
+ const rest = raw.slice(CHUNK_PREFIX.length);
736
+ const sep = rest.indexOf(":");
737
+ if (sep <= 0) {
738
+ throw new KeychainError(
739
+ "keychain_error",
740
+ "Corrupt Keychain chunk envelope"
741
+ );
742
+ }
743
+ const total = Number.parseInt(rest.slice(0, sep), 10);
744
+ const base64 = rest.slice(sep + 1);
745
+ if (!Number.isInteger(total) || total < 1 || total > MAX_CHUNKS || !/^[A-Za-z0-9+/=]*$/.test(base64)) {
746
+ throw new KeychainError(
747
+ "keychain_error",
748
+ "Corrupt Keychain chunk metadata"
749
+ );
750
+ }
751
+ return { total, base64 };
752
+ };
753
+ var extractValidatedChunkBase64 = (rawChunk, expectedTotal, index, service) => {
754
+ if (rawChunk === null) {
755
+ throw new KeychainError(
756
+ "keychain_error",
757
+ `Missing Keychain chunk ${index + 1}/${expectedTotal} for ${service}`
758
+ );
759
+ }
760
+ const parsed = parseChunkEnvelope(rawChunk);
761
+ if (!parsed || parsed.total !== expectedTotal) {
762
+ throw new KeychainError(
763
+ "keychain_error",
764
+ `Inconsistent Keychain chunk ${index + 1}/${expectedTotal} for ${service}`
765
+ );
766
+ }
767
+ return parsed.base64;
768
+ };
769
+ var decodeBase64Chunks = (parts) => Buffer.from(parts.join(""), "base64").toString("utf8");
770
+ var payloadDigest = (value) => createHash3("sha256").update(value, "utf8").digest("hex");
771
+ var decodeLegacyOrSingleValue = (trimmed) => {
772
+ if (trimmed.startsWith("{")) return trimmed;
773
+ if (/^[0-9a-fA-F]+$/.test(trimmed) && trimmed.length % 2 === 0) {
774
+ const decoded = Buffer.from(trimmed, "hex").toString("utf8");
775
+ if (decoded.startsWith("{")) return decoded;
776
+ }
777
+ throw new KeychainError(
778
+ "keychain_error",
779
+ "Keychain item contains unrecognized credential format"
780
+ );
781
+ };
782
+ function* readChunkedSnapshot(service, root) {
783
+ if (root === null) return { value: null };
784
+ const pointer = parseGenPointer(root);
785
+ const first = pointer ? null : parseChunkEnvelope(root);
786
+ if (!pointer && !first) return { value: decodeLegacyOrSingleValue(root) };
787
+ if (first?.total === 1) return { value: decodeBase64Chunks([first.base64]) };
788
+ const total = pointer?.total ?? first?.total ?? 0;
789
+ const parts = first ? [first.base64] : [];
790
+ let result;
791
+ try {
792
+ for (let i = parts.length; i < total; i += 1) {
793
+ const rawChunk = yield pointer ? genChunkServiceName(service, pointer.gen, i) : chunkServiceName(service, i);
794
+ parts.push(extractValidatedChunkBase64(rawChunk, total, i, service));
795
+ }
796
+ const value = decodeBase64Chunks(parts);
797
+ if (pointer?.digest && pointer.digest !== payloadDigest(value)) {
798
+ throw new KeychainError(
799
+ "keychain_error",
800
+ "Inconsistent Keychain payload"
801
+ );
802
+ }
803
+ result = { value };
804
+ } catch (error) {
805
+ result = { error };
806
+ }
807
+ const currentRoot = yield service;
808
+ if (currentRoot !== root) return { nextRoot: currentRoot };
809
+ if ("error" in result) throw result.error;
810
+ return result;
811
+ }
812
+ var isNotFoundOutput = (code, stderr) => code === 44 || /could not be found in the keychain|SecKeychainSearchCopyNext: The specified item could not be found/i.test(
813
+ stderr
814
+ );
815
+ var classifySecurityFailure = (code, stderr, timedOut = false) => {
816
+ if (timedOut) {
817
+ return new KeychainError(
818
+ "keychain_error",
819
+ "macOS Keychain operation timed out. Run `codelia auth authorize-keychain` from a local terminal, then retry."
820
+ );
821
+ }
822
+ if (code === 36 || /User interaction is not allowed|errSecInteractionNotAllowed|keychain is locked/i.test(
823
+ stderr
824
+ )) {
825
+ return new KeychainError(
826
+ "keychain_locked",
827
+ "macOS login Keychain is locked; run `security unlock-keychain ~/Library/Keychains/login.keychain-db`"
828
+ );
829
+ }
830
+ if (code === 128 || /User canceled the operation|errSecUserCanceled|errSecAuthFailed|The user name or passphrase you entered is not correct/i.test(
831
+ stderr
832
+ )) {
833
+ return new KeychainError(
834
+ "keychain_access_denied",
835
+ "macOS Keychain denied access; run `codelia auth authorize-keychain` from a local terminal"
836
+ );
837
+ }
838
+ return new KeychainError("keychain_error", "macOS Keychain operation failed");
839
+ };
840
+ var securityEnv = () => ({
841
+ HOME: os.homedir(),
842
+ PATH: "/usr/bin:/bin",
843
+ ...process.env.USER ? { USER: process.env.USER } : {},
844
+ ...process.env.LOGNAME ? { LOGNAME: process.env.LOGNAME } : {}
845
+ });
846
+ var MacOsKeychainClient = class {
847
+ securityBinary;
848
+ hasCustomBinary;
849
+ constructor(options) {
850
+ const custom = options?.securityPath ?? options?.helperPath;
851
+ this.securityBinary = custom ?? DEFAULT_SECURITY_PATH;
852
+ this.hasCustomBinary = Boolean(custom);
853
+ }
854
+ resolveBinary() {
855
+ if (!this.hasCustomBinary && process.platform !== "darwin") {
856
+ return null;
857
+ }
858
+ if (!this.hasCustomBinary && process.env.CODELIA_TEST_KEYCHAIN_DISABLED === "1") {
859
+ throw new KeychainError(
860
+ "keychain_unavailable",
861
+ "macOS Keychain is disabled for tests"
862
+ );
863
+ }
864
+ try {
865
+ accessSync(this.securityBinary, constants3.X_OK);
866
+ return this.securityBinary;
867
+ } catch {
868
+ return null;
869
+ }
870
+ }
871
+ requireBinary() {
872
+ const binary = this.resolveBinary();
873
+ if (!binary) {
874
+ throw new KeychainError(
875
+ "keychain_unavailable",
876
+ process.platform !== "darwin" ? "unsupported_platform" : "macOS /usr/bin/security is unavailable"
877
+ );
878
+ }
879
+ return binary;
880
+ }
881
+ runArgsAsync(args, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
882
+ const binary = this.requireBinary();
883
+ return new Promise((resolve, reject) => {
884
+ execFile2(
885
+ binary,
886
+ [...args],
887
+ {
888
+ cwd: "/",
889
+ env: securityEnv(),
890
+ timeout: timeoutMs,
891
+ killSignal: "SIGKILL",
892
+ maxBuffer: MAX_SECURITY_BUFFER,
893
+ encoding: "utf8"
894
+ },
895
+ (error, stdout, stderr) => {
896
+ if (!error) {
897
+ resolve({ code: 0, stdout, stderr });
898
+ return;
899
+ }
900
+ const timedOut = Boolean(error.killed && error.code === null);
901
+ const exitCode = typeof error.code === "number" ? error.code : null;
902
+ if (timedOut) {
903
+ reject(classifySecurityFailure(exitCode, stderr ?? "", true));
904
+ return;
905
+ }
906
+ resolve({
907
+ code: exitCode ?? 1,
908
+ stdout: stdout ?? "",
909
+ stderr: stderr ?? error.message
910
+ });
911
+ }
912
+ );
913
+ });
914
+ }
915
+ runInteractiveBatchAsync(commands, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
916
+ const binary = this.requireBinary();
917
+ const payload = `${commands.join("\n")}
918
+ `;
919
+ for (const line of commands) {
920
+ if (Buffer.byteLength(line, "utf8") + 1 >= SECURITY_INTERACTIVE_MAX_LINE_BYTES) {
921
+ throw new KeychainError(
922
+ "keychain_error",
923
+ "Keychain batch command exceeds 4096-byte security -i line limit"
924
+ );
925
+ }
926
+ }
927
+ return new Promise((resolve, reject) => {
928
+ const child = spawn(binary, ["-i"], {
929
+ cwd: "/",
930
+ env: securityEnv(),
931
+ stdio: ["pipe", "pipe", "pipe"]
932
+ });
933
+ let stderr = "";
934
+ let timedOut = false;
935
+ const timer = setTimeout(() => {
936
+ timedOut = true;
937
+ child.kill("SIGKILL");
938
+ }, timeoutMs);
939
+ child.stdout.on("data", () => void 0);
940
+ child.stderr.on("data", (chunk) => {
941
+ if (stderr.length < MAX_STDERR_CAPTURE_BYTES) {
942
+ stderr += chunk.toString("utf8");
943
+ }
944
+ });
945
+ child.once("error", () => {
946
+ clearTimeout(timer);
947
+ reject(
948
+ new KeychainError(
949
+ "keychain_unavailable",
950
+ "Failed to launch macOS /usr/bin/security"
951
+ )
952
+ );
953
+ });
954
+ child.once("close", (code) => {
955
+ clearTimeout(timer);
956
+ if (timedOut) {
957
+ reject(classifySecurityFailure(code, stderr, true));
958
+ return;
959
+ }
960
+ if (code !== 0) {
961
+ reject(classifySecurityFailure(code, stderr, false));
962
+ return;
963
+ }
964
+ resolve();
965
+ });
966
+ child.stdin.on("error", () => void 0);
967
+ child.stdin.end(payload);
968
+ });
969
+ }
970
+ findRawAsync(service, account, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
971
+ validateKeychainToken("service", service);
972
+ validateKeychainToken("account", account);
973
+ return this.runArgsAsync(
974
+ ["find-generic-password", "-w", "-a", account, "-s", service],
975
+ timeoutMs
976
+ ).then(({ code, stdout, stderr }) => {
977
+ if (code === 0) return stdout.replace(/\r?\n$/, "");
978
+ if (isNotFoundOutput(code, stderr)) return null;
979
+ throw classifySecurityFailure(code, stderr);
980
+ });
981
+ }
982
+ findRawSync(service, account, timeoutMs = DEFAULT_SYNC_TIMEOUT_MS) {
983
+ validateKeychainToken("service", service);
984
+ validateKeychainToken("account", account);
985
+ const binary = this.requireBinary();
986
+ try {
987
+ const stdout = execFileSync2(
988
+ binary,
989
+ ["find-generic-password", "-w", "-a", account, "-s", service],
990
+ {
991
+ cwd: "/",
992
+ env: securityEnv(),
993
+ stdio: ["ignore", "pipe", "pipe"],
994
+ timeout: timeoutMs,
995
+ killSignal: "SIGKILL",
996
+ maxBuffer: MAX_SECURITY_BUFFER,
997
+ encoding: "utf8"
998
+ }
999
+ );
1000
+ return stdout.replace(/\r?\n$/, "");
1001
+ } catch (error) {
1002
+ const err = error;
1003
+ const status = typeof err.status === "number" ? err.status : null;
1004
+ const stderr = typeof err.stderr === "string" ? err.stderr : Buffer.isBuffer(err.stderr) ? err.stderr.toString("utf8") : "";
1005
+ const timedOut = err.code === "ETIMEDOUT" || status === null && Boolean(err.signal);
1006
+ if (!timedOut && isNotFoundOutput(status, stderr)) {
1007
+ return null;
1008
+ }
1009
+ throw classifySecurityFailure(status, stderr, timedOut);
1010
+ }
1011
+ }
1012
+ async probe() {
1013
+ if (!this.hasCustomBinary && process.platform !== "darwin") {
1014
+ return {
1015
+ available: false,
1016
+ reason: "unsupported_platform",
1017
+ message: "OS Keychain backend is currently supported on macOS only"
1018
+ };
1019
+ }
1020
+ try {
1021
+ const binary = this.resolveBinary();
1022
+ if (!binary) {
1023
+ return {
1024
+ available: false,
1025
+ reason: "keychain_unavailable",
1026
+ message: "macOS /usr/bin/security is unavailable"
1027
+ };
1028
+ }
1029
+ const { code, stderr } = await this.runArgsAsync(["show-keychain-info"]);
1030
+ if (code === 0) return { available: true };
1031
+ const classified = classifySecurityFailure(code, stderr);
1032
+ return {
1033
+ available: false,
1034
+ reason: classified.code === "keychain_locked" ? "keychain_locked" : "keychain_unavailable",
1035
+ message: classified.message
1036
+ };
1037
+ } catch (error) {
1038
+ const isLocked = error instanceof KeychainError && error.code === "keychain_locked";
1039
+ return {
1040
+ available: false,
1041
+ reason: isLocked ? "keychain_locked" : "keychain_unavailable",
1042
+ message: error instanceof Error ? error.message : String(error)
1043
+ };
1044
+ }
1045
+ }
1046
+ async readFullAsync(service, account, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
1047
+ const find = (name) => this.findRawAsync(name, account, timeoutMs);
1048
+ let root = await find(service);
1049
+ for (let attempt = 0; attempt < MAX_SNAPSHOT_ATTEMPTS; attempt += 1) {
1050
+ const snapshot = readChunkedSnapshot(service, root);
1051
+ let step = snapshot.next();
1052
+ while (!step.done) step = snapshot.next(await find(step.value));
1053
+ if ("value" in step.value) return step.value.value;
1054
+ root = step.value.nextRoot;
1055
+ }
1056
+ throw new KeychainError(
1057
+ "keychain_error",
1058
+ "Keychain changed during read; retry"
1059
+ );
1060
+ }
1061
+ async get(service, account) {
1062
+ return this.readFullAsync(service, account, DEFAULT_ASYNC_TIMEOUT_MS);
1063
+ }
1064
+ getSync(service, account, timeoutMs = DEFAULT_SYNC_TIMEOUT_MS) {
1065
+ const deadline = performance.now() + timeoutMs;
1066
+ const find = (name) => {
1067
+ const remaining = Math.ceil(deadline - performance.now());
1068
+ if (remaining <= 0) throw classifySecurityFailure(null, "", true);
1069
+ return this.findRawSync(name, account, remaining);
1070
+ };
1071
+ let root = find(service);
1072
+ for (let attempt = 0; attempt < MAX_SNAPSHOT_ATTEMPTS; attempt += 1) {
1073
+ const snapshot = readChunkedSnapshot(service, root);
1074
+ let step = snapshot.next();
1075
+ while (!step.done) step = snapshot.next(find(step.value));
1076
+ if ("value" in step.value) return step.value.value;
1077
+ root = step.value.nextRoot;
1078
+ }
1079
+ throw new KeychainError(
1080
+ "keychain_error",
1081
+ "Keychain changed during read; retry"
1082
+ );
1083
+ }
1084
+ async sweepGenSlotBestEffort(service, account, gen, startIndex = 0) {
1085
+ let consecutiveMisses = 0;
1086
+ for (let i = startIndex; i < MAX_CHUNKS; i += 1) {
1087
+ const deleted = await this.deleteSingleItem(
1088
+ genChunkServiceName(service, gen, i),
1089
+ account
1090
+ ).catch(() => false);
1091
+ if (deleted) {
1092
+ consecutiveMisses = 0;
1093
+ } else {
1094
+ consecutiveMisses += 1;
1095
+ if (consecutiveMisses >= SWEEP_CONSECUTIVE_MISS_LIMIT) break;
1096
+ }
1097
+ }
1098
+ }
1099
+ /**
1100
+ * Exhaustively delete every possible chunk index (`0..MAX_CHUNKS-1`) in a
1101
+ * fixed generation slot and propagate any non-not-found delete error.
1102
+ */
1103
+ async deleteAllSlotChunksStrict(service, account, gen) {
1104
+ let deletedAny = false;
1105
+ for (let i = 0; i < MAX_CHUNKS; i += 1) {
1106
+ const deleted = await this.deleteSingleItem(
1107
+ genChunkServiceName(service, gen, i),
1108
+ account
1109
+ );
1110
+ if (deleted) deletedAny = true;
1111
+ }
1112
+ return deletedAny;
1113
+ }
1114
+ async cleanupOldChunks(service, account, previousRoot, keepGen) {
1115
+ try {
1116
+ if (previousRoot) {
1117
+ let prevPtr = null;
1118
+ try {
1119
+ prevPtr = parseGenPointer(previousRoot);
1120
+ } catch {
1121
+ prevPtr = null;
1122
+ }
1123
+ if (prevPtr && prevPtr.gen !== keepGen) {
1124
+ for (let i = 0; i < prevPtr.total; i += 1) {
1125
+ await this.deleteSingleItem(
1126
+ genChunkServiceName(service, prevPtr.gen, i),
1127
+ account
1128
+ ).catch(() => false);
1129
+ }
1130
+ }
1131
+ let prevCb1 = null;
1132
+ try {
1133
+ prevCb1 = parseChunkEnvelope(previousRoot);
1134
+ } catch {
1135
+ prevCb1 = null;
1136
+ }
1137
+ if (prevCb1 && prevCb1.total > 1) {
1138
+ for (let i = 1; i < prevCb1.total; i += 1) {
1139
+ await this.deleteSingleItem(
1140
+ chunkServiceName(service, i),
1141
+ account
1142
+ ).catch(() => false);
1143
+ }
1144
+ }
1145
+ }
1146
+ for (const slot of FIXED_GEN_SLOTS) {
1147
+ if (slot !== keepGen) {
1148
+ await this.sweepGenSlotBestEffort(service, account, slot, 0);
1149
+ }
1150
+ }
1151
+ } catch {
1152
+ }
1153
+ }
1154
+ async writeSingleChunk(service, account, encoded, previousRoot) {
1155
+ await this.runInteractiveBatchAsync([
1156
+ `add-generic-password -U -a ${account} -s ${service} -w ${encoded}`
1157
+ ]);
1158
+ const verified = await this.findRawAsync(service, account);
1159
+ if (verified !== encoded) {
1160
+ throw new KeychainError(
1161
+ "keychain_error",
1162
+ "macOS Keychain write verification failed"
1163
+ );
1164
+ }
1165
+ await this.cleanupOldChunks(service, account, previousRoot);
1166
+ }
1167
+ /**
1168
+ * Multi-chunk write: alternates between fixed A/B slots (`a` and `b`) so
1169
+ * existing credentials stay untouched until every staged chunk verifies via
1170
+ * read-back AND crashed writes remain deterministically discoverable on logout.
1171
+ */
1172
+ async writeMultiChunk(service, account, chunks, previousRoot, digest2) {
1173
+ const activeGen = previousRoot ? parseGenPointer(previousRoot)?.gen : void 0;
1174
+ const gen = activeGen === "a" ? "b" : "a";
1175
+ const stageCommands = chunks.map(
1176
+ (encoded, index) => `add-generic-password -U -a ${account} -s ${genChunkServiceName(service, gen, index)} -w ${encoded}`
1177
+ );
1178
+ const rollbackStaged = async () => {
1179
+ for (let i = 0; i < chunks.length; i += 1) {
1180
+ await this.deleteSingleItem(
1181
+ genChunkServiceName(service, gen, i),
1182
+ account
1183
+ ).catch(() => false);
1184
+ }
1185
+ };
1186
+ try {
1187
+ await this.runInteractiveBatchAsync(stageCommands);
1188
+ for (let i = 0; i < chunks.length; i += 1) {
1189
+ const verified = await this.findRawAsync(
1190
+ genChunkServiceName(service, gen, i),
1191
+ account
1192
+ );
1193
+ if (verified !== chunks[i]) {
1194
+ throw new KeychainError(
1195
+ "keychain_error",
1196
+ `macOS Keychain staged chunk ${i + 1}/${chunks.length} failed verification`
1197
+ );
1198
+ }
1199
+ }
1200
+ } catch (error) {
1201
+ await rollbackStaged();
1202
+ throw error;
1203
+ }
1204
+ const pointerValue = `${GEN_POINTER_PREFIX}${gen}:${chunks.length}.${digest2}`;
1205
+ await this.runInteractiveBatchAsync([
1206
+ `add-generic-password -U -a ${account} -s ${service} -w ${pointerValue}`
1207
+ ]);
1208
+ const verifiedPointer = await this.findRawAsync(service, account);
1209
+ if (verifiedPointer !== pointerValue) {
1210
+ await rollbackStaged();
1211
+ throw new KeychainError(
1212
+ "keychain_error",
1213
+ "macOS Keychain pointer verification failed"
1214
+ );
1215
+ }
1216
+ await this.sweepGenSlotBestEffort(service, account, gen, chunks.length);
1217
+ await this.cleanupOldChunks(service, account, previousRoot, gen);
1218
+ }
1219
+ async set(service, account, value) {
1220
+ validateKeychainToken("service", service);
1221
+ validateKeychainToken("account", account);
1222
+ const chunks = encodePayloadChunks(value);
1223
+ const previousRoot = await this.findRawAsync(service, account);
1224
+ if (chunks.length === 1) {
1225
+ await this.writeSingleChunk(service, account, chunks[0], previousRoot);
1226
+ return;
1227
+ }
1228
+ await this.writeMultiChunk(
1229
+ service,
1230
+ account,
1231
+ chunks,
1232
+ previousRoot,
1233
+ payloadDigest(value)
1234
+ );
1235
+ }
1236
+ async deleteSingleItem(service, account) {
1237
+ validateKeychainToken("service", service);
1238
+ validateKeychainToken("account", account);
1239
+ const { code, stderr } = await this.runArgsAsync([
1240
+ "delete-generic-password",
1241
+ "-a",
1242
+ account,
1243
+ "-s",
1244
+ service
1245
+ ]);
1246
+ if (code === 0) return true;
1247
+ if (isNotFoundOutput(code, stderr)) return false;
1248
+ throw classifySecurityFailure(code, stderr);
1249
+ }
1250
+ async delete(service, account) {
1251
+ validateKeychainToken("service", service);
1252
+ validateKeychainToken("account", account);
1253
+ const existing = await this.findRawAsync(service, account);
1254
+ let deletedAny = false;
1255
+ if (existing) {
1256
+ let prevCb1 = null;
1257
+ try {
1258
+ prevCb1 = parseChunkEnvelope(existing);
1259
+ } catch {
1260
+ prevCb1 = null;
1261
+ }
1262
+ if (prevCb1 && prevCb1.total > 1) {
1263
+ for (let i = 1; i < prevCb1.total; i += 1) {
1264
+ if (await this.deleteSingleItem(chunkServiceName(service, i), account)) {
1265
+ deletedAny = true;
1266
+ }
1267
+ }
1268
+ }
1269
+ let prevPtr = null;
1270
+ try {
1271
+ prevPtr = parseGenPointer(existing);
1272
+ } catch {
1273
+ prevPtr = null;
1274
+ }
1275
+ if (prevPtr && !FIXED_GEN_SLOTS.includes(
1276
+ prevPtr.gen
1277
+ )) {
1278
+ for (let i = 0; i < prevPtr.total; i += 1) {
1279
+ if (await this.deleteSingleItem(
1280
+ genChunkServiceName(service, prevPtr.gen, i),
1281
+ account
1282
+ )) {
1283
+ deletedAny = true;
1284
+ }
1285
+ }
1286
+ }
1287
+ }
1288
+ const deletedPrimary = await this.deleteSingleItem(service, account);
1289
+ if (deletedPrimary) deletedAny = true;
1290
+ for (const slot of FIXED_GEN_SLOTS) {
1291
+ if (await this.deleteAllSlotChunksStrict(service, account, slot)) {
1292
+ deletedAny = true;
1293
+ }
1294
+ }
1295
+ return deletedAny;
1296
+ }
1297
+ /** Let macOS prompt the user to authorize reading each existing item. */
1298
+ async authorize(service, account) {
1299
+ const fullValue = await this.readFullAsync(
1300
+ service,
1301
+ account,
1302
+ AUTHORIZATION_TIMEOUT_MS
1303
+ );
1304
+ return fullValue !== null;
1305
+ }
1306
+ };
1307
+
1308
+ // src/auth-schema.ts
1309
+ var AUTH_VERSION_V1 = 1;
1310
+ var AUTH_VERSION_V2 = 2;
1311
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1312
+ var normalizeApiKey = (value) => {
1313
+ if (!isRecord(value) || typeof value.api_key !== "string") return null;
1314
+ return {
1315
+ api_key: value.api_key,
1316
+ ...typeof value.api_base === "string" && value.api_base.length > 0 ? { api_base: value.api_base } : {}
1317
+ };
1318
+ };
1319
+ var normalizeOAuth = (value) => {
1320
+ if (!isRecord(value) || typeof value.access_token !== "string" || typeof value.refresh_token !== "string" || typeof value.expires_at !== "number" || !Number.isFinite(value.expires_at)) {
1321
+ return null;
1322
+ }
1323
+ return {
1324
+ access_token: value.access_token,
1325
+ refresh_token: value.refresh_token,
1326
+ expires_at: value.expires_at,
1327
+ ...typeof value.account_id === "string" && value.account_id.length > 0 ? { account_id: value.account_id } : {}
1328
+ };
1329
+ };
1330
+ var normalizeProviderEntryV1 = (value) => {
1331
+ if (!isRecord(value)) {
1332
+ throw new Error("auth.json contains invalid provider entry");
1333
+ }
1334
+ if (value.method === "api_key") {
1335
+ const apiKey = normalizeApiKey(value);
1336
+ if (!apiKey) {
1337
+ throw new Error("auth.json contains invalid api_key entry");
1338
+ }
1339
+ return {
1340
+ chat_method: "api_key",
1341
+ credentials: { api_key: apiKey }
1342
+ };
1343
+ }
1344
+ if (value.method === "oauth") {
1345
+ const oauth = normalizeOAuth(value.oauth);
1346
+ if (!oauth) {
1347
+ throw new Error("auth.json contains invalid oauth entry");
1348
+ }
1349
+ return {
1350
+ chat_method: "oauth",
1351
+ credentials: { oauth }
1352
+ };
1353
+ }
1354
+ throw new Error("auth.json contains unsupported auth method");
1355
+ };
1356
+ var normalizeProviderEntryV2 = (value) => {
1357
+ if (!isRecord(value) || !isRecord(value.credentials)) {
1358
+ throw new Error("auth.json v2 contains invalid provider entry");
1359
+ }
1360
+ const chatMethod = value.chat_method;
1361
+ if (chatMethod !== void 0 && chatMethod !== "api_key" && chatMethod !== "oauth") {
1362
+ throw new Error("auth.json v2 contains invalid chat_method");
1363
+ }
1364
+ const credentials = {};
1365
+ if (value.credentials.api_key !== void 0) {
1366
+ const apiKey = normalizeApiKey(value.credentials.api_key);
1367
+ if (!apiKey) {
1368
+ throw new Error("auth.json v2 contains invalid api_key credential");
1369
+ }
1370
+ credentials.api_key = apiKey;
1371
+ }
1372
+ if (value.credentials.oauth !== void 0) {
1373
+ const oauth = normalizeOAuth(value.credentials.oauth);
1374
+ if (!oauth) {
1375
+ throw new Error("auth.json v2 contains invalid oauth credential");
1376
+ }
1377
+ credentials.oauth = oauth;
1378
+ }
1379
+ return {
1380
+ ...chatMethod ? { chat_method: chatMethod } : {},
1381
+ credentials
1382
+ };
1383
+ };
1384
+ var parseAuthDocument = (text) => {
1385
+ const parsed = JSON.parse(text);
1386
+ if (!isRecord(parsed)) {
1387
+ throw new Error("auth.json has unsupported format");
1388
+ }
1389
+ if (parsed.version === AUTH_VERSION_V1) {
1390
+ const rawProviders = isRecord(parsed.providers) ? parsed.providers : {};
1391
+ const providers = {};
1392
+ for (const [name, entry] of Object.entries(rawProviders)) {
1393
+ providers[name] = normalizeProviderEntryV1(entry);
1394
+ }
1395
+ return {
1396
+ normalized: { version: AUTH_VERSION_V2, providers },
1397
+ sourceVersion: 1
1398
+ };
1399
+ }
1400
+ if (parsed.version === AUTH_VERSION_V2) {
1401
+ const rawProviders = isRecord(parsed.providers) ? parsed.providers : {};
1402
+ const providers = {};
1403
+ for (const [name, entry] of Object.entries(rawProviders)) {
1404
+ providers[name] = normalizeProviderEntryV2(entry);
1405
+ }
1406
+ return {
1407
+ normalized: { version: AUTH_VERSION_V2, providers },
1408
+ sourceVersion: 2
1409
+ };
1410
+ }
1411
+ throw new Error("auth.json has unsupported version");
1412
+ };
1413
+ var providerAuthStoreAdapter = {
1414
+ name: "auth",
1415
+ service: CODELIA_AUTH_KEYCHAIN_SERVICE,
1416
+ filePath: (paths) => paths.authFile,
1417
+ legacyFilePath: (paths) => paths.legacyAuthFile,
1418
+ empty: () => ({ version: AUTH_VERSION_V2, providers: {} }),
1419
+ isNonEmpty: (doc) => Object.keys(doc.providers).length > 0,
1420
+ parse: (text) => parseAuthDocument(text)
1421
+ };
1422
+
1423
+ // src/credential-backend.ts
1424
+ import { promises as fs5, readFileSync as readFileSync2 } from "fs";
1425
+ import path7 from "path";
1426
+
1427
+ // src/credential-migration.ts
1428
+ import { promises as fs4, readFileSync } from "fs";
1429
+ var CredentialConflictError = class extends Error {
1430
+ code = "credential_storage_conflict";
1431
+ store;
1432
+ constructor(store, detail) {
1433
+ super(
1434
+ detail ?? `Credential storage conflict detected for '${store}': both source and destination contain different credentials. Resolve the conflict before continuing.`
1435
+ );
1436
+ this.name = "CredentialConflictError";
1437
+ this.store = store;
1438
+ }
1439
+ };
1440
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1441
+ var canonicalizeValue = (value) => {
1442
+ if (Array.isArray(value)) {
1443
+ return value.map(canonicalizeValue);
1444
+ }
1445
+ if (isRecord2(value)) {
1446
+ const sorted = {};
1447
+ for (const key of Object.keys(value).sort()) {
1448
+ const entry = value[key];
1449
+ if (entry !== void 0) {
1450
+ sorted[key] = canonicalizeValue(entry);
1451
+ }
1452
+ }
1453
+ return sorted;
1454
+ }
1455
+ return value;
1456
+ };
1457
+ var canonicalJsonStringify = (value) => JSON.stringify(canonicalizeValue(value));
1458
+ var canonicalJsonEqual = (left, right) => canonicalJsonStringify(left) === canonicalJsonStringify(right);
1459
+ var parseAuthStorageState = (text) => {
1460
+ const parsed = JSON.parse(text);
1461
+ if (!isRecord2(parsed) || parsed.version !== 1) {
1462
+ throw new Error("storage-state.json has unsupported version");
1463
+ }
1464
+ const active = parsed.active_backend;
1465
+ if (active !== "file" && active !== "keyring") {
1466
+ throw new Error("storage-state.json has invalid active_backend");
1467
+ }
1468
+ if (parsed.mcp_reauth_required !== void 0 && (!Array.isArray(parsed.mcp_reauth_required) || !parsed.mcp_reauth_required.every((item) => typeof item === "string"))) {
1469
+ throw new Error("storage-state.json has invalid mcp_reauth_required");
1470
+ }
1471
+ const mcpReauth = parsed.mcp_reauth_required;
1472
+ if (parsed.status === "steady") {
1473
+ return {
1474
+ version: 1,
1475
+ status: "steady",
1476
+ active_backend: active,
1477
+ ...mcpReauth?.length ? { mcp_reauth_required: mcpReauth } : {}
1478
+ };
1479
+ }
1480
+ if (parsed.status === "migrating") {
1481
+ const target = parsed.target_backend;
1482
+ const stores = isRecord2(parsed.stores) ? parsed.stores : null;
1483
+ const authStatus = stores?.auth;
1484
+ const mcpStatus = stores?.mcp_auth;
1485
+ if (target !== "file" && target !== "keyring" || authStatus !== "pending" && authStatus !== "verified" || mcpStatus !== "pending" && mcpStatus !== "verified") {
1486
+ throw new Error("storage-state.json has invalid migrating state");
1487
+ }
1488
+ let cleanupPending;
1489
+ if (parsed.cleanup_pending !== void 0) {
1490
+ if (!isRecord2(parsed.cleanup_pending)) {
1491
+ throw new Error("storage-state.json has invalid cleanup_pending");
1492
+ }
1493
+ const sourceBackend = parsed.cleanup_pending.source_backend;
1494
+ const authFlag = parsed.cleanup_pending.auth;
1495
+ const mcpFlag = parsed.cleanup_pending.mcp_auth;
1496
+ if (sourceBackend !== "file" && sourceBackend !== "legacy_file" && sourceBackend !== "keyring" || typeof authFlag !== "boolean" || typeof mcpFlag !== "boolean") {
1497
+ throw new Error("storage-state.json has invalid cleanup_pending");
1498
+ }
1499
+ cleanupPending = {
1500
+ source_backend: sourceBackend,
1501
+ auth: authFlag,
1502
+ mcp_auth: mcpFlag
1503
+ };
1504
+ }
1505
+ return {
1506
+ version: 1,
1507
+ status: "migrating",
1508
+ active_backend: active,
1509
+ target_backend: target,
1510
+ stores: { auth: authStatus, mcp_auth: mcpStatus },
1511
+ ...cleanupPending ? { cleanup_pending: cleanupPending } : {},
1512
+ ...mcpReauth?.length ? { mcp_reauth_required: mcpReauth } : {}
1513
+ };
1514
+ }
1515
+ throw new Error("storage-state.json has invalid status");
1516
+ };
1517
+ var readAuthStorageState = async (stateFile) => {
1518
+ if (!await verifyWindowsCredentialFileAcl(stateFile)) return null;
1519
+ let text;
1520
+ try {
1521
+ text = await fs4.readFile(stateFile, "utf8");
1522
+ } catch (error) {
1523
+ if (error?.code === "ENOENT") return null;
1524
+ throw error;
1525
+ }
1526
+ return parseAuthStorageState(text);
1527
+ };
1528
+ var readAuthStorageStateSync = (stateFile) => {
1529
+ if (!verifyWindowsCredentialFileAclSync(stateFile)) return null;
1530
+ let text;
1531
+ try {
1532
+ text = readFileSync(stateFile, "utf8");
1533
+ } catch (error) {
1534
+ if (error?.code === "ENOENT") return null;
1535
+ throw error;
1536
+ }
1537
+ return parseAuthStorageState(text);
1538
+ };
1539
+ var writeAuthStorageState = async (stateFile, state) => {
1540
+ await writeFileAtomic(stateFile, JSON.stringify(state, null, 2), {
1541
+ mode: 384
1542
+ });
1543
+ };
1544
+ var runTwoPhaseMigration = async (options) => {
1545
+ const [authSrc, authDst, mcpSrc, mcpDst] = await Promise.all([
1546
+ options.authSlot.readSource(),
1547
+ options.authSlot.readDest(),
1548
+ options.mcpSlot.readSource(),
1549
+ options.mcpSlot.readDest()
1550
+ ]);
1551
+ const evaluate = (name, src, dst) => {
1552
+ if (!src.present) return "none";
1553
+ if (src.nonEmpty && dst.nonEmpty) {
1554
+ if (canonicalJsonEqual(src.normalized, dst.normalized)) {
1555
+ return "recover";
1556
+ }
1557
+ throw new CredentialConflictError(name);
1558
+ }
1559
+ if (!src.nonEmpty && dst.nonEmpty) {
1560
+ return "recover";
1561
+ }
1562
+ if (dst.present && canonicalJsonEqual(src.normalized, dst.normalized)) {
1563
+ return "recover";
1564
+ }
1565
+ return "copy";
1566
+ };
1567
+ const authAction = evaluate("auth", authSrc, authDst);
1568
+ const mcpAction = evaluate("mcp_auth", mcpSrc, mcpDst);
1569
+ const mcpReauthSet = /* @__PURE__ */ new Set([
1570
+ ...options.existingMcpReauth ?? [],
1571
+ ...mcpSrc.extraWarnings ?? []
1572
+ ]);
1573
+ const mcpReauthRequired = [...mcpReauthSet].sort();
1574
+ if (authAction === "none" && mcpAction === "none") {
1575
+ if (options.fromBackend !== options.toBackend || options.commitSteadyIfEmpty) {
1576
+ await writeAuthStorageState(options.stateFile, {
1577
+ version: 1,
1578
+ status: "steady",
1579
+ active_backend: options.toBackend,
1580
+ ...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
1581
+ });
1582
+ }
1583
+ return { migrated: false, mcpReauthRequired };
1584
+ }
1585
+ const migratingState = {
1586
+ version: 1,
1587
+ status: "migrating",
1588
+ active_backend: options.fromBackend,
1589
+ target_backend: options.toBackend,
1590
+ stores: {
1591
+ auth: authAction === "copy" ? "pending" : "verified",
1592
+ mcp_auth: mcpAction === "copy" ? "pending" : "verified"
1593
+ },
1594
+ ...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
1595
+ };
1596
+ await writeAuthStorageState(options.stateFile, migratingState);
1597
+ if (authAction === "copy") {
1598
+ await options.authSlot.writeDest(authSrc.normalized);
1599
+ const verified = await options.authSlot.verifyDest(authSrc.normalized);
1600
+ if (!verified) {
1601
+ throw new Error("auth migration read-back verification failed");
1602
+ }
1603
+ migratingState.stores.auth = "verified";
1604
+ await writeAuthStorageState(options.stateFile, migratingState);
1605
+ }
1606
+ if (mcpAction === "copy") {
1607
+ await options.mcpSlot.writeDest(mcpSrc.normalized);
1608
+ const verified = await options.mcpSlot.verifyDest(mcpSrc.normalized);
1609
+ if (!verified) {
1610
+ throw new Error("mcp-auth migration read-back verification failed");
1611
+ }
1612
+ migratingState.stores.mcp_auth = "verified";
1613
+ await writeAuthStorageState(options.stateFile, migratingState);
1614
+ }
1615
+ if (authSrc.present || mcpSrc.present) {
1616
+ migratingState.cleanup_pending = {
1617
+ source_backend: options.cleanupSourceKind ?? options.fromBackend,
1618
+ auth: authSrc.present,
1619
+ mcp_auth: mcpSrc.present
1620
+ };
1621
+ await writeAuthStorageState(options.stateFile, migratingState);
1622
+ }
1623
+ if (authSrc.present) {
1624
+ await options.authSlot.cleanupSource();
1625
+ }
1626
+ if (mcpSrc.present) {
1627
+ await options.mcpSlot.cleanupSource();
1628
+ }
1629
+ await writeAuthStorageState(options.stateFile, {
1630
+ version: 1,
1631
+ status: "steady",
1632
+ active_backend: options.toBackend,
1633
+ ...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
1634
+ });
1635
+ return { migrated: true, mcpReauthRequired };
1636
+ };
1637
+
1638
+ // src/paths.ts
1639
+ import { mkdir as mkdir2 } from "fs/promises";
1640
+ import os2 from "os";
1641
+ import path6 from "path";
1642
+ var DEFAULT_ROOT_DIR = ".codelia";
1643
+ var LAYOUT_ENV = "CODELIA_LAYOUT";
1644
+ var XDG_DIR_NAME = "codelia";
1645
+ var CONFIG_FILENAME = "config.json";
1646
+ var CREDENTIALS_DIRNAME = "credentials";
1647
+ var AUTH_FILENAME = "auth.json";
1648
+ var MCP_AUTH_FILENAME = "mcp-auth.json";
1649
+ var AUTH_STATE_FILENAME = "storage-state.json";
1650
+ var PROJECTS_FILENAME = "projects.json";
1651
+ var CACHE_DIRNAME = "cache";
1652
+ var TOOL_OUTPUT_CACHE_DIRNAME = "tool-output";
1653
+ var SESSIONS_DIRNAME = "sessions";
1654
+ var LOGS_DIRNAME = "logs";
1655
+ function resolveStoragePaths(options = {}) {
1656
+ if (options.rootOverride) {
1657
+ return buildHomeLayout(options.rootOverride);
1658
+ }
1659
+ const layoutValue = options.layout ?? process.env[LAYOUT_ENV];
1660
+ const layout = normalizeLayout(layoutValue);
1661
+ if (layout === "xdg") {
1662
+ return buildXdgLayout();
1663
+ }
1664
+ return buildHomeLayout(defaultHomeRoot());
1665
+ }
1666
+ async function ensureStorageDirs(paths) {
1667
+ await Promise.all([
1668
+ mkdir2(paths.configDir, { recursive: true }),
1669
+ mkdir2(paths.cacheDir, { recursive: true }),
1670
+ mkdir2(paths.toolOutputCacheDir, { recursive: true }),
1671
+ mkdir2(paths.sessionsDir, { recursive: true }),
1672
+ mkdir2(paths.logsDir, { recursive: true })
1673
+ ]);
1674
+ }
1675
+ function resolveDefaultHomeConfigDir(home = os2.homedir(), layoutValue = process.env[LAYOUT_ENV]) {
1676
+ const layout = normalizeLayout(layoutValue);
1677
+ return layout === "xdg" ? path6.join(home, ".config", XDG_DIR_NAME) : path6.join(home, DEFAULT_ROOT_DIR);
1678
+ }
1679
+ function normalizeLayout(value) {
1680
+ if (value && value.toLowerCase() === "xdg") return "xdg";
1681
+ return "home";
1682
+ }
1683
+ function defaultHomeRoot() {
1684
+ return path6.join(os2.homedir(), DEFAULT_ROOT_DIR);
1685
+ }
1686
+ function buildHomeLayout(root) {
1687
+ const configDir = root;
1688
+ const credentialsDir = path6.join(configDir, CREDENTIALS_DIRNAME);
1689
+ return {
1690
+ root,
1691
+ configDir,
1692
+ configFile: path6.join(configDir, CONFIG_FILENAME),
1693
+ credentialsDir,
1694
+ authFile: path6.join(credentialsDir, AUTH_FILENAME),
1695
+ mcpAuthFile: path6.join(credentialsDir, MCP_AUTH_FILENAME),
1696
+ legacyAuthFile: path6.join(configDir, AUTH_FILENAME),
1697
+ legacyMcpAuthFile: path6.join(configDir, MCP_AUTH_FILENAME),
1698
+ authStateFile: path6.join(credentialsDir, AUTH_STATE_FILENAME),
1699
+ projectsFile: path6.join(configDir, PROJECTS_FILENAME),
1700
+ cacheDir: path6.join(root, CACHE_DIRNAME),
1701
+ toolOutputCacheDir: path6.join(
1702
+ root,
1703
+ CACHE_DIRNAME,
1704
+ TOOL_OUTPUT_CACHE_DIRNAME
1705
+ ),
1706
+ sessionsDir: path6.join(root, SESSIONS_DIRNAME),
1707
+ logsDir: path6.join(root, LOGS_DIRNAME)
1708
+ };
1709
+ }
1710
+ function buildXdgLayout() {
1711
+ const home = os2.homedir();
1712
+ const configRoot = process.env.XDG_CONFIG_HOME ?? path6.join(home, ".config");
1713
+ const cacheRoot = process.env.XDG_CACHE_HOME ?? path6.join(home, ".cache");
1714
+ const stateRoot = process.env.XDG_STATE_HOME ?? path6.join(home, ".local", "state");
1715
+ const configDir = path6.join(configRoot, XDG_DIR_NAME);
1716
+ const credentialsDir = path6.join(configDir, CREDENTIALS_DIRNAME);
1717
+ const cacheDir = path6.join(cacheRoot, XDG_DIR_NAME);
1718
+ const stateDir = path6.join(stateRoot, XDG_DIR_NAME);
1719
+ return {
1720
+ root: stateDir,
1721
+ configDir,
1722
+ configFile: path6.join(configDir, CONFIG_FILENAME),
1723
+ credentialsDir,
1724
+ authFile: path6.join(credentialsDir, AUTH_FILENAME),
1725
+ mcpAuthFile: path6.join(credentialsDir, MCP_AUTH_FILENAME),
1726
+ legacyAuthFile: path6.join(configDir, AUTH_FILENAME),
1727
+ legacyMcpAuthFile: path6.join(configDir, MCP_AUTH_FILENAME),
1728
+ authStateFile: path6.join(credentialsDir, AUTH_STATE_FILENAME),
1729
+ projectsFile: path6.join(configDir, PROJECTS_FILENAME),
1730
+ cacheDir,
1731
+ toolOutputCacheDir: path6.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
1732
+ sessionsDir: path6.join(stateDir, SESSIONS_DIRNAME),
1733
+ logsDir: path6.join(stateDir, LOGS_DIRNAME)
1734
+ };
1735
+ }
1736
+
1737
+ // src/credential-backend.ts
1738
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1739
+ var probeUnavailableError = (probe, message = probe.message) => new KeychainError(
1740
+ probe.reason === "keychain_locked" ? "keychain_locked" : "keychain_unavailable",
1741
+ message
1742
+ );
1743
+ var buildSteadyState = (activeBackend, mcpReauthRequired) => ({
1744
+ version: 1,
1745
+ status: "steady",
1746
+ active_backend: activeBackend,
1747
+ ...mcpReauthRequired?.length ? { mcp_reauth_required: [...mcpReauthRequired] } : {}
1748
+ });
1749
+ var isKeyringOwnedOrTargeting = (state) => state?.active_backend === "keyring" || state?.status === "migrating" && state.target_backend === "keyring";
1750
+ var isKeyringInvolved = (state) => isKeyringOwnedOrTargeting(state) || state?.status === "migrating" && state.cleanup_pending?.source_backend === "keyring";
1751
+ var parseStorageModeValue = (value) => {
1752
+ if (value === "auto" || value === "keyring" || value === "file") {
1753
+ return value;
1754
+ }
1755
+ return void 0;
1756
+ };
1757
+ var resolveConfiguredAuthStorageMode = (paths, overrideMode) => {
1758
+ if (overrideMode) return overrideMode;
1759
+ const envRaw = process.env.CODELIA_AUTH_STORAGE?.trim();
1760
+ if (envRaw) {
1761
+ const parsed = parseStorageModeValue(envRaw);
1762
+ if (!parsed) {
1763
+ throw new Error(
1764
+ `Invalid CODELIA_AUTH_STORAGE="${envRaw}" (expected "auto", "keyring", or "file")`
1765
+ );
1766
+ }
1767
+ return parsed;
1768
+ }
1769
+ const globalConfigPath = process.env.CODELIA_CONFIG_PATH?.trim() ? path7.resolve(process.env.CODELIA_CONFIG_PATH.trim()) : paths.configFile;
1770
+ try {
1771
+ const raw = readFileSync2(globalConfigPath, "utf8");
1772
+ const parsed = JSON.parse(raw);
1773
+ if (isRecord3(parsed) && isRecord3(parsed.auth)) {
1774
+ const mode = parsed.auth.storage;
1775
+ if (mode !== void 0) {
1776
+ const valid = parseStorageModeValue(mode);
1777
+ if (!valid) {
1778
+ throw new Error(
1779
+ `Invalid global auth.storage="${String(mode)}" (expected "auto", "keyring", or "file")`
1780
+ );
1781
+ }
1782
+ return valid;
1783
+ }
1784
+ }
1785
+ } catch (error) {
1786
+ if (error?.code !== "ENOENT") {
1787
+ if (error instanceof Error && error.message.startsWith("Invalid global auth.storage")) {
1788
+ throw error;
1789
+ }
1790
+ }
1791
+ }
1792
+ return "auto";
1793
+ };
1794
+ var readTextIfPresent = async (filePath, legacy = false) => {
1795
+ if (!await verifyWindowsCredentialFileAcl(filePath, legacy)) return null;
1796
+ try {
1797
+ return await fs5.readFile(filePath, "utf8");
1798
+ } catch (error) {
1799
+ if (error?.code === "ENOENT") return null;
1800
+ throw error;
1801
+ }
1802
+ };
1803
+ var readFileSlot = async (filePath, adapter, legacy = false) => {
1804
+ const text = await readTextIfPresent(filePath, legacy);
1805
+ if (text === null) {
1806
+ return { present: false, normalized: adapter.empty(), nonEmpty: false };
1807
+ }
1808
+ const parsed = adapter.parse(text);
1809
+ return {
1810
+ present: true,
1811
+ normalized: parsed.normalized,
1812
+ nonEmpty: adapter.isNonEmpty(parsed.normalized),
1813
+ sourceVersion: parsed.sourceVersion,
1814
+ extraWarnings: parsed.extraWarnings
1815
+ };
1816
+ };
1817
+ var readKeychainSlot = async (keychain, service, account, adapter) => {
1818
+ const text = await keychain.get(service, account);
1819
+ if (text === null) {
1820
+ return { present: false, normalized: adapter.empty(), nonEmpty: false };
1821
+ }
1822
+ const parsed = adapter.parse(text);
1823
+ return {
1824
+ present: true,
1825
+ normalized: parsed.normalized,
1826
+ nonEmpty: adapter.isNonEmpty(parsed.normalized)
1827
+ };
1828
+ };
1829
+ var unlinkIfPresent = async (filePath) => {
1830
+ try {
1831
+ await fs5.unlink(filePath);
1832
+ } catch (error) {
1833
+ if (error?.code === "ENOENT") return;
1834
+ throw error;
1835
+ }
1836
+ };
1837
+ var makeKeychainTargetSlot = (keychain, account, adapter, sourcePath) => ({
1838
+ name: adapter.name,
1839
+ readSource: () => readFileSlot(sourcePath, adapter),
1840
+ readDest: () => readKeychainSlot(keychain, adapter.service, account, adapter),
1841
+ writeDest: async (normalized) => {
1842
+ await keychain.set(adapter.service, account, JSON.stringify(normalized));
1843
+ },
1844
+ verifyDest: async (expected) => {
1845
+ const back = await readKeychainSlot(
1846
+ keychain,
1847
+ adapter.service,
1848
+ account,
1849
+ adapter
1850
+ );
1851
+ return back.present && canonicalJsonEqual(back.normalized, expected);
1852
+ },
1853
+ cleanupSource: () => unlinkIfPresent(sourcePath)
1854
+ });
1855
+ var makeFileDestHandlers = (paths, adapter) => {
1856
+ const destPath = adapter.filePath(paths);
1857
+ return {
1858
+ readDest: () => readFileSlot(destPath, adapter),
1859
+ writeDest: async (normalized) => {
1860
+ await ensureStorageDirs(paths);
1861
+ await writeFileAtomic(destPath, JSON.stringify(normalized, null, 2), {
1862
+ mode: 384
1863
+ });
1864
+ },
1865
+ verifyDest: async (expected) => {
1866
+ const back = await readFileSlot(destPath, adapter);
1867
+ return back.present && canonicalJsonEqual(back.normalized, expected);
1868
+ }
1869
+ };
1870
+ };
1871
+ var makeFileFromKeychainSlot = (paths, keychain, account, adapter) => ({
1872
+ name: adapter.name,
1873
+ readSource: () => readKeychainSlot(keychain, adapter.service, account, adapter),
1874
+ ...makeFileDestHandlers(paths, adapter),
1875
+ cleanupSource: async () => {
1876
+ await keychain.delete(adapter.service, account);
1877
+ }
1878
+ });
1879
+ var makeFileFromLegacySlot = (paths, adapter) => {
1880
+ const sourcePath = adapter.legacyFilePath(paths);
1881
+ return {
1882
+ name: adapter.name,
1883
+ readSource: () => readFileSlot(sourcePath, adapter, true),
1884
+ ...makeFileDestHandlers(paths, adapter),
1885
+ cleanupSource: () => unlinkIfPresent(sourcePath)
1886
+ };
1887
+ };
1888
+ var completePendingCleanupUnlocked = async (options) => {
1889
+ const pending = options.state.cleanup_pending;
1890
+ if (!pending) return options.state;
1891
+ if (pending.source_backend === "keyring" && options.state.target_backend === "file") {
1892
+ const probe = await options.keychain.probe();
1893
+ if (!probe.available) {
1894
+ throw probeUnavailableError(
1895
+ probe,
1896
+ `Cannot finish cleanup of previous Keychain credentials after migration while Keychain is unavailable (${probe.reason}): ${probe.message}`
1897
+ );
1898
+ }
1899
+ if (pending.auth) {
1900
+ await options.keychain.delete(
1901
+ options.authAdapter.service,
1902
+ options.account
1903
+ );
1904
+ }
1905
+ if (pending.mcp_auth) {
1906
+ await options.keychain.delete(
1907
+ options.mcpAdapter.service,
1908
+ options.account
1909
+ );
1910
+ }
1911
+ } else if (pending.source_backend === "legacy_file") {
1912
+ if (pending.auth) {
1913
+ await unlinkIfPresent(options.authAdapter.legacyFilePath(options.paths));
1914
+ }
1915
+ if (pending.mcp_auth) {
1916
+ await unlinkIfPresent(options.mcpAdapter.legacyFilePath(options.paths));
1917
+ }
1918
+ } else {
1919
+ const isLegacyCleanup = options.state.target_backend !== "keyring";
1920
+ const cleanupAuthPath = isLegacyCleanup ? options.authAdapter.legacyFilePath(options.paths) : options.authAdapter.filePath(options.paths);
1921
+ const cleanupMcpPath = isLegacyCleanup ? options.mcpAdapter.legacyFilePath(options.paths) : options.mcpAdapter.filePath(options.paths);
1922
+ if (pending.auth) {
1923
+ await unlinkIfPresent(cleanupAuthPath);
1924
+ }
1925
+ if (pending.mcp_auth) {
1926
+ await unlinkIfPresent(cleanupMcpPath);
1927
+ }
1928
+ }
1929
+ const committed = buildSteadyState(
1930
+ options.state.target_backend,
1931
+ options.state.mcp_reauth_required
1932
+ );
1933
+ await writeAuthStorageState(options.paths.authStateFile, committed);
1934
+ return committed;
1935
+ };
1936
+ var coordinateCredentialBackendUnlocked = async (options) => {
1937
+ const { paths, authAdapter, mcpAdapter } = options;
1938
+ const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
1939
+ const configured = resolveConfiguredAuthStorageMode(
1940
+ paths,
1941
+ options.storageMode
1942
+ );
1943
+ const account = keychainAccountForConfigDir(paths.configDir);
1944
+ await ensureStorageDirs(paths);
1945
+ let state = await readAuthStorageState(
1946
+ paths.authStateFile
1947
+ );
1948
+ if (state?.status === "migrating" && state.cleanup_pending) {
1949
+ state = await completePendingCleanupUnlocked({
1950
+ paths,
1951
+ state,
1952
+ keychain,
1953
+ account,
1954
+ authAdapter,
1955
+ mcpAdapter
1956
+ });
1957
+ }
1958
+ const migrateLegacyToCredentials = async () => {
1959
+ const [legacyAuth, legacyMcp] = await Promise.all([
1960
+ readTextIfPresent(authAdapter.legacyFilePath(paths), true),
1961
+ readTextIfPresent(mcpAdapter.legacyFilePath(paths), true)
1962
+ ]);
1963
+ if (legacyAuth === null && legacyMcp === null) return;
1964
+ await runTwoPhaseMigration({
1965
+ stateFile: paths.authStateFile,
1966
+ fromBackend: state?.active_backend ?? "file",
1967
+ toBackend: state?.active_backend ?? "file",
1968
+ cleanupSourceKind: "legacy_file",
1969
+ authSlot: makeFileFromLegacySlot(paths, authAdapter),
1970
+ mcpSlot: makeFileFromLegacySlot(paths, mcpAdapter),
1971
+ existingMcpReauth: state?.mcp_reauth_required
1972
+ });
1973
+ state = await readAuthStorageState(paths.authStateFile);
1974
+ };
1975
+ const keyringOwnedOrInFlight = isKeyringOwnedOrTargeting(state);
1976
+ if (configured === "file") {
1977
+ await migrateLegacyToCredentials();
1978
+ if (keyringOwnedOrInFlight) {
1979
+ const probe2 = await keychain.probe();
1980
+ if (!probe2.available) {
1981
+ throw probeUnavailableError(
1982
+ probe2,
1983
+ `Cannot switch auth.storage to "file" while Keychain is unavailable: ${probe2.message}`
1984
+ );
1985
+ }
1986
+ await runTwoPhaseMigration({
1987
+ stateFile: paths.authStateFile,
1988
+ fromBackend: "keyring",
1989
+ toBackend: "file",
1990
+ authSlot: makeFileFromKeychainSlot(
1991
+ paths,
1992
+ keychain,
1993
+ account,
1994
+ authAdapter
1995
+ ),
1996
+ mcpSlot: makeFileFromKeychainSlot(paths, keychain, account, mcpAdapter),
1997
+ existingMcpReauth: state?.mcp_reauth_required,
1998
+ commitSteadyIfEmpty: true
1999
+ });
2000
+ state = await readAuthStorageState(paths.authStateFile);
2001
+ } else if (!state || state.status === "migrating") {
2002
+ await writeAuthStorageState(
2003
+ paths.authStateFile,
2004
+ buildSteadyState("file", state?.mcp_reauth_required)
2005
+ );
2006
+ }
2007
+ return {
2008
+ configured,
2009
+ active: "file",
2010
+ state: "steady"
2011
+ };
2012
+ }
2013
+ const probe = await keychain.probe();
2014
+ if (!probe.available) {
2015
+ if (configured === "keyring") {
2016
+ throw probeUnavailableError(probe);
2017
+ }
2018
+ if (keyringOwnedOrInFlight) {
2019
+ throw probeUnavailableError(
2020
+ probe,
2021
+ `Credentials are managed in macOS Keychain. ${probe.message}`
2022
+ );
2023
+ }
2024
+ await migrateLegacyToCredentials();
2025
+ return {
2026
+ configured,
2027
+ active: "file",
2028
+ state: "steady",
2029
+ fallbackReason: probe.reason
2030
+ };
2031
+ }
2032
+ await migrateLegacyToCredentials();
2033
+ const [credAuthText, credMcpText] = await Promise.all([
2034
+ readTextIfPresent(authAdapter.filePath(paths)),
2035
+ readTextIfPresent(mcpAdapter.filePath(paths))
2036
+ ]);
2037
+ if (credAuthText !== null || credMcpText !== null || state?.status === "migrating") {
2038
+ await runTwoPhaseMigration({
2039
+ stateFile: paths.authStateFile,
2040
+ fromBackend: "file",
2041
+ toBackend: "keyring",
2042
+ authSlot: makeKeychainTargetSlot(
2043
+ keychain,
2044
+ account,
2045
+ authAdapter,
2046
+ authAdapter.filePath(paths)
2047
+ ),
2048
+ mcpSlot: makeKeychainTargetSlot(
2049
+ keychain,
2050
+ account,
2051
+ mcpAdapter,
2052
+ mcpAdapter.filePath(paths)
2053
+ ),
2054
+ existingMcpReauth: state?.mcp_reauth_required,
2055
+ commitSteadyIfEmpty: true
2056
+ });
2057
+ state = await readAuthStorageState(paths.authStateFile);
2058
+ } else if (state?.active_backend !== "keyring") {
2059
+ await writeAuthStorageState(
2060
+ paths.authStateFile,
2061
+ buildSteadyState("keyring", state?.mcp_reauth_required)
2062
+ );
2063
+ }
2064
+ return {
2065
+ configured,
2066
+ active: "keyring",
2067
+ state: "steady"
2068
+ };
2069
+ };
2070
+ var coordinateCredentialBackend = (options) => {
2071
+ const paths = options.paths ?? resolveStoragePaths();
2072
+ return withAuthStoreLock(
2073
+ authLockPathFor(paths.credentialsDir),
2074
+ () => coordinateCredentialBackendUnlocked({
2075
+ ...options,
2076
+ paths
2077
+ }),
2078
+ options.lock
2079
+ );
2080
+ };
2081
+ var clearStoreAcrossAllLocationsUnlocked = async (options) => {
2082
+ const { paths, adapter } = options;
2083
+ const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
2084
+ const account = keychainAccountForConfigDir(paths.configDir);
2085
+ await ensureStorageDirs(paths);
2086
+ await unlinkIfPresent(adapter.filePath(paths));
2087
+ await unlinkIfPresent(adapter.legacyFilePath(paths));
2088
+ const probe = await keychain.probe();
2089
+ if (probe.available) {
2090
+ await keychain.delete(adapter.service, account);
2091
+ } else {
2092
+ const storedState = await readAuthStorageState(paths.authStateFile).catch(
2093
+ () => null
2094
+ );
2095
+ if (isKeyringInvolved(storedState)) {
2096
+ throw probeUnavailableError(
2097
+ probe,
2098
+ `Cannot clear Keychain credentials while Keychain is unavailable (${probe.reason}): ${probe.message}`
124
2099
  );
125
- if (bytes.length !== ref.byte_size || digest(bytes) !== ref.sha256)
126
- throw new Error("Attachment original is corrupt");
127
2100
  }
128
- return { ref, ...imageRef ? { imageRef } : {} };
129
2101
  }
130
- async read(attachmentId, sessionId, offset, length) {
131
- const metadata = await this.metadata(attachmentId, sessionId);
132
- if (!metadata) throw new Error("Attachment unavailable in this session");
133
- if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || length > 256 * 1024)
134
- throw new Error("Invalid attachment byte range");
135
- const end = Math.min(offset + length, metadata.ref.byte_size);
136
- if (metadata.imageRef)
137
- return (await this.readImage(metadata)).subarray(offset, end);
138
- const file = await open2(
139
- path.join(this.root, attachmentId, "original"),
140
- constants2.O_RDONLY | (constants2.O_NOFOLLOW ?? 0) | (constants2.O_NONBLOCK ?? 0)
2102
+ };
2103
+ var resolveDefaultTargetBackend = async (configured, keychain) => {
2104
+ if (configured === "file") return "file";
2105
+ if (configured === "keyring") return "keyring";
2106
+ return (await keychain.probe()).available ? "keyring" : "file";
2107
+ };
2108
+ var resolveKeepKeyringStore = async (ctx, adapter) => {
2109
+ const probe = await ctx.keychain.probe();
2110
+ if (!probe.available) {
2111
+ throw probeUnavailableError(
2112
+ probe,
2113
+ `Cannot keep Keychain credentials while Keychain is unavailable: ${probe.message}`
141
2114
  );
142
- try {
143
- const stat = await file.stat();
144
- if (!stat.isFile() || stat.size !== metadata.ref.byte_size)
145
- throw new Error("Attachment original is corrupt");
146
- if (offset >= end) return Buffer.alloc(0);
147
- const firstBlock = Math.floor(offset / BLOCK_BYTES);
148
- const lastBlock = Math.ceil(end / BLOCK_BYTES);
149
- const start = firstBlock * BLOCK_BYTES;
150
- const bytes = Buffer.alloc(
151
- Math.min(lastBlock * BLOCK_BYTES, stat.size) - start
2115
+ }
2116
+ const slot = await readKeychainSlot(
2117
+ ctx.keychain,
2118
+ adapter.service,
2119
+ ctx.account,
2120
+ adapter
2121
+ );
2122
+ const fileSlot = await readFileSlot(
2123
+ adapter.filePath(ctx.paths),
2124
+ adapter
2125
+ ).catch(() => ({ present: true, nonEmpty: true }));
2126
+ const legacySlot = await readFileSlot(
2127
+ adapter.legacyFilePath(ctx.paths),
2128
+ adapter,
2129
+ true
2130
+ ).catch(() => ({ present: true, nonEmpty: true }));
2131
+ if (!slot.present && !fileSlot.present && !legacySlot.present) {
2132
+ return;
2133
+ }
2134
+ if (!slot.present || !slot.nonEmpty && (fileSlot.nonEmpty || legacySlot.nonEmpty)) {
2135
+ throw new Error(
2136
+ `Cannot keep Keychain store for '${adapter.name}': Keychain has no saved credentials`
2137
+ );
2138
+ }
2139
+ await unlinkIfPresent(adapter.filePath(ctx.paths));
2140
+ await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
2141
+ };
2142
+ var resolveKeepFileStore = async (ctx, adapter) => {
2143
+ const slot = await readFileSlot(adapter.filePath(ctx.paths), adapter);
2144
+ if (!slot.present) {
2145
+ throw new Error(
2146
+ `Cannot keep file store for '${adapter.name}': ${adapter.filePath(ctx.paths)} does not exist`
2147
+ );
2148
+ }
2149
+ await writeFileAtomic(
2150
+ adapter.filePath(ctx.paths),
2151
+ JSON.stringify(slot.normalized, null, 2),
2152
+ { mode: 384 }
2153
+ );
2154
+ await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
2155
+ const probe = await ctx.keychain.probe();
2156
+ if (probe.available) {
2157
+ await ctx.keychain.delete(adapter.service, ctx.account);
2158
+ } else if (ctx.existingState?.active_backend === "keyring") {
2159
+ throw probeUnavailableError(
2160
+ probe,
2161
+ `Cannot remove superseded Keychain entry while Keychain is unavailable: ${probe.message}`
2162
+ );
2163
+ }
2164
+ };
2165
+ var resolveKeepLegacyStore = async (ctx, adapter) => {
2166
+ const legacy = await readFileSlot(
2167
+ adapter.legacyFilePath(ctx.paths),
2168
+ adapter,
2169
+ true
2170
+ );
2171
+ if (!legacy.present) {
2172
+ throw new Error(
2173
+ `Cannot keep legacy store for '${adapter.name}': ${adapter.legacyFilePath(ctx.paths)} does not exist`
2174
+ );
2175
+ }
2176
+ const targetBackend = await resolveDefaultTargetBackend(
2177
+ ctx.configured,
2178
+ ctx.keychain
2179
+ );
2180
+ if (targetBackend === "keyring") {
2181
+ const probe2 = await ctx.keychain.probe();
2182
+ if (!probe2.available) {
2183
+ throw probeUnavailableError(
2184
+ probe2,
2185
+ `Cannot promote legacy store to Keychain while Keychain is unavailable: ${probe2.message}`
152
2186
  );
153
- let count = 0;
154
- while (count < bytes.length) {
155
- const result = await file.read(
156
- bytes,
157
- count,
158
- bytes.length - count,
159
- start + count
160
- );
161
- if (!result.bytesRead)
162
- throw new Error("Attachment original is corrupt");
163
- count += result.bytesRead;
164
- }
165
- for (let block = firstBlock; block < lastBlock; block++) {
166
- const beg = (block - firstBlock) * BLOCK_BYTES;
167
- if (metadata.blocks?.[block] !== digest(bytes.subarray(beg, beg + BLOCK_BYTES))) {
168
- throw new Error("Attachment original is corrupt");
169
- }
170
- }
171
- return bytes.subarray(offset - start, end - start);
172
- } finally {
173
- await file.close();
174
2187
  }
175
- }
176
- async metadata(attachmentId, sessionId) {
177
- if (!isAttachmentId(attachmentId)) return null;
178
- const dir = path.join(this.root, attachmentId);
179
- try {
180
- if (!(await lstat(dir)).isDirectory()) return null;
181
- const metadata = JSON.parse(
182
- (await readImageFileBounded(path.join(dir, "metadata.json"), 64 * 1024)).toString()
2188
+ await ctx.keychain.set(
2189
+ adapter.service,
2190
+ ctx.account,
2191
+ JSON.stringify(legacy.normalized)
2192
+ );
2193
+ const verify = await readKeychainSlot(
2194
+ ctx.keychain,
2195
+ adapter.service,
2196
+ ctx.account,
2197
+ adapter
2198
+ );
2199
+ if (!verify.present || !canonicalJsonEqual(verify.normalized, legacy.normalized)) {
2200
+ throw new Error(
2201
+ `Failed to verify promoted '${adapter.name}' in Keychain`
183
2202
  );
184
- const { ref, imageRef, blocks } = metadata;
185
- if (metadata.sessionId !== sessionId || !UUID.test(metadata.batch) || ref?.attachment_id !== attachmentId)
186
- return null;
187
- if (!Number.isSafeInteger(ref.byte_size) || ref.byte_size < 0 || ref.byte_size > MAX_BYTES || !SHA256.test(ref.sha256) || typeof ref.media_type !== "string" || typeof ref.display_name !== "string")
188
- throw new Error("Invalid attachment metadata");
189
- if (!imageRef && (!Array.isArray(blocks) || blocks.length !== Math.ceil(ref.byte_size / BLOCK_BYTES)))
190
- throw new Error("Invalid attachment block index");
191
- const marker = path.join(this.root, "committed", metadata.batch);
192
- return (await lstat(marker)).isFile() ? metadata : null;
193
- } catch (error) {
194
- if (error.code === "ENOENT") return null;
195
- throw error;
196
2203
  }
2204
+ await unlinkIfPresent(adapter.filePath(ctx.paths));
2205
+ await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
2206
+ return;
197
2207
  }
198
- async readImage({
199
- ref,
200
- imageRef,
201
- sessionId
202
- }) {
203
- if (!imageRef || imageRef.sha256 !== ref.sha256 || imageRef.byte_size !== ref.byte_size || imageRef.media_type !== ref.media_type || imageRef.width !== ref.width || imageRef.height !== ref.height)
204
- throw new Error("Invalid image attachment reference");
205
- const { metadata, bytes } = await this.images.read(
206
- imageRef.artifact_id,
207
- sessionId
208
- );
209
- if (metadata.kind !== "attachment" || metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size || metadata.media_type !== ref.media_type || metadata.width !== ref.width || metadata.height !== ref.height)
210
- throw new Error("Image attachment original is corrupt");
211
- return bytes;
2208
+ await writeFileAtomic(
2209
+ adapter.filePath(ctx.paths),
2210
+ JSON.stringify(legacy.normalized, null, 2),
2211
+ { mode: 384 }
2212
+ );
2213
+ await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
2214
+ const probe = await ctx.keychain.probe();
2215
+ if (probe.available) {
2216
+ await ctx.keychain.delete(adapter.service, ctx.account);
2217
+ }
2218
+ };
2219
+ var resolveCredentialConflict = async (options) => {
2220
+ const paths = options.paths ?? resolveStoragePaths();
2221
+ const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
2222
+ const account = keychainAccountForConfigDir(paths.configDir);
2223
+ const targets = options.stores?.length ? [...new Set(options.stores)] : ["auth", "mcp_auth"];
2224
+ return withAuthStoreLock(
2225
+ authLockPathFor(paths.credentialsDir),
2226
+ async () => {
2227
+ await ensureStorageDirs(paths);
2228
+ const configured = resolveConfiguredAuthStorageMode(
2229
+ paths,
2230
+ options.storageMode
2231
+ );
2232
+ const existingState = await readAuthStorageState(
2233
+ paths.authStateFile
2234
+ ).catch(() => null);
2235
+ const ctx = {
2236
+ paths,
2237
+ keychain,
2238
+ account,
2239
+ configured,
2240
+ existingState
2241
+ };
2242
+ const resolveOne = async (adapter) => {
2243
+ switch (options.strategy) {
2244
+ case "clear_all":
2245
+ await clearStoreAcrossAllLocationsUnlocked({
2246
+ paths,
2247
+ adapter,
2248
+ keychain
2249
+ });
2250
+ return;
2251
+ case "keep_keyring":
2252
+ await resolveKeepKeyringStore(ctx, adapter);
2253
+ return;
2254
+ case "keep_file":
2255
+ await resolveKeepFileStore(ctx, adapter);
2256
+ return;
2257
+ case "keep_legacy":
2258
+ await resolveKeepLegacyStore(ctx, adapter);
2259
+ return;
2260
+ }
2261
+ };
2262
+ for (const storeName of targets) {
2263
+ if (storeName === "auth") {
2264
+ await resolveOne(options.authAdapter);
2265
+ } else {
2266
+ await resolveOne(options.mcpAdapter);
2267
+ }
2268
+ }
2269
+ const targetActive = options.strategy === "keep_keyring" ? "keyring" : options.strategy === "keep_file" ? "file" : await resolveDefaultTargetBackend(configured, keychain);
2270
+ await writeAuthStorageState(
2271
+ paths.authStateFile,
2272
+ buildSteadyState(targetActive, existingState?.mcp_reauth_required)
2273
+ );
2274
+ return { active: targetActive, resolvedStores: targets };
2275
+ },
2276
+ options.lock
2277
+ );
2278
+ };
2279
+ var inspectCredentialStorageStatus = async (options) => {
2280
+ const paths = options.paths ?? resolveStoragePaths();
2281
+ const keychain = options.keychain ?? new MacOsKeychainClient({
2282
+ credentialsDir: paths.credentialsDir
2283
+ });
2284
+ const configured = resolveConfiguredAuthStorageMode(
2285
+ paths,
2286
+ options.storageMode
2287
+ );
2288
+ const account = keychainAccountForConfigDir(paths.configDir);
2289
+ let stateCorrupt = false;
2290
+ let storedState = null;
2291
+ try {
2292
+ storedState = await readAuthStorageState(paths.authStateFile);
2293
+ } catch {
2294
+ stateCorrupt = true;
2295
+ }
2296
+ const mcpReauthRequired = storedState?.mcp_reauth_required ?? [];
2297
+ const keyringOwned = isKeyringInvolved(storedState);
2298
+ const shouldProbeKeychain = configured !== "file" || keyringOwned;
2299
+ const probe = shouldProbeKeychain ? await keychain.probe() : {
2300
+ available: false,
2301
+ reason: "keychain_unavailable",
2302
+ message: "file mode selected"
2303
+ };
2304
+ const inspectStore = async (adapter) => {
2305
+ let issue;
2306
+ const inspectKeychain = async () => {
2307
+ if (!probe.available) {
2308
+ if (keyringOwned || configured === "keyring") {
2309
+ issue = probe.reason === "keychain_locked" ? "keychain_locked" : "keychain_unavailable";
2310
+ }
2311
+ return null;
2312
+ }
2313
+ try {
2314
+ return await readKeychainSlot(
2315
+ keychain,
2316
+ adapter.service,
2317
+ account,
2318
+ adapter
2319
+ );
2320
+ } catch (error) {
2321
+ if (!(error instanceof KeychainError)) throw error;
2322
+ issue = error.code === "keychain_locked" || error.code === "keychain_access_denied" ? error.code : "keychain_unavailable";
2323
+ return null;
2324
+ }
2325
+ };
2326
+ const [current, legacy, native] = await Promise.all([
2327
+ readFileSlot(adapter.filePath(paths), adapter),
2328
+ readFileSlot(adapter.legacyFilePath(paths), adapter, true),
2329
+ inspectKeychain()
2330
+ ]);
2331
+ const file = current.nonEmpty ? current : legacy;
2332
+ const conflict = current.nonEmpty && legacy.nonEmpty && !canonicalJsonEqual(current.normalized, legacy.normalized) || file.nonEmpty && native?.nonEmpty && !canonicalJsonEqual(file.normalized, native.normalized);
2333
+ return { file, native, conflict, issue };
2334
+ };
2335
+ const [auth, mcp] = await Promise.all([
2336
+ inspectStore(options.authAdapter).catch(() => null),
2337
+ inspectStore(options.mcpAdapter).catch(() => null)
2338
+ ]);
2339
+ const keychainIssue = auth?.issue ?? mcp?.issue;
2340
+ const unreadableStores = [];
2341
+ if (!auth) unreadableStores.push("auth");
2342
+ if (!mcp) unreadableStores.push("mcp_auth");
2343
+ if (stateCorrupt) unreadableStores.push("storage_state");
2344
+ const conflictStores = [];
2345
+ if (auth?.conflict) conflictStores.push("auth");
2346
+ if (mcp?.conflict) conflictStores.push("mcp_auth");
2347
+ const state = stateCorrupt || conflictStores.length > 0 ? "conflict" : storedState?.status ?? "steady";
2348
+ const active = storedState?.active_backend ?? (auth?.file.nonEmpty || mcp?.file.nonEmpty ? "file" : probe.available || configured === "keyring" ? "keyring" : "file");
2349
+ const fallbackReason = configured === "auto" && active === "file" && !probe.available ? probe.reason : void 0;
2350
+ if (state === "steady" && auth && !auth.issue) {
2351
+ const snapshot = active === "file" ? auth.file : auth.native;
2352
+ if (snapshot?.nonEmpty) options.onReadableAuth?.(snapshot.normalized);
212
2353
  }
2354
+ return {
2355
+ configured,
2356
+ active,
2357
+ state,
2358
+ ...fallbackReason ? { fallbackReason } : {},
2359
+ mcpReauthRequired,
2360
+ conflictStores,
2361
+ unreadableStores,
2362
+ ...keychainIssue ? { keychainIssue } : {}
2363
+ };
213
2364
  };
214
2365
 
215
2366
  // src/image-artifacts.ts
216
- import { randomUUID as randomUUID3 } from "crypto";
217
- import { lstat as lstat3, mkdir as mkdir3, rename as rename3, rm as rm3, writeFile as writeFile3 } from "fs/promises";
218
- import path3 from "path";
2367
+ import { randomUUID as randomUUID5 } from "crypto";
2368
+ import { lstat as lstat3, mkdir as mkdir4, rename as rename3, rm as rm3, writeFile as writeFile3 } from "fs/promises";
2369
+ import path9 from "path";
219
2370
 
220
2371
  // src/image-attachment.ts
221
2372
  import { imageSize } from "image-size";
222
2373
 
223
2374
  // src/image-png.ts
224
- import { promisify } from "util";
2375
+ import { promisify as promisify2 } from "util";
225
2376
  import { inflate } from "zlib";
226
2377
  var IMAGE_MAX_BYTES = 32 * 1024 * 1024;
227
2378
  var IMAGE_MAX_SIDE = 12288;
228
2379
  var IMAGE_MAX_PIXELS = 2e7;
229
- var inflateAsync = promisify(inflate);
2380
+ var inflateAsync = promisify2(inflate);
230
2381
  var crcTable = Uint32Array.from({ length: 256 }, (_, n) => {
231
2382
  let c = n;
232
2383
  for (let i = 0; i < 8; i++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
@@ -398,15 +2549,15 @@ function parseImageMetadata(value) {
398
2549
  }
399
2550
 
400
2551
  // src/image-model-view.ts
401
- import { randomUUID as randomUUID2 } from "crypto";
402
- import { lstat as lstat2, mkdir as mkdir2, rename as rename2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
403
- import path2 from "path";
2552
+ import { randomUUID as randomUUID4 } from "crypto";
2553
+ import { lstat as lstat2, mkdir as mkdir3, rename as rename2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
2554
+ import path8 from "path";
404
2555
  import {
405
2556
  isImageModelView
406
2557
  } from "@codelia/shared-types";
407
2558
  import { imageSize as imageSize2 } from "image-size";
408
2559
  var VERSION = "jpeg-q90-444-v1";
409
- var directory = (root) => path2.join(root, VERSION);
2560
+ var directory = (root) => path8.join(root, VERSION);
410
2561
  var errorCode = (error) => error && typeof error === "object" && "code" in error ? error.code : void 0;
411
2562
  async function readModelView(root, original, expected) {
412
2563
  if (expected !== void 0 && !isImageModelView(expected))
@@ -415,7 +2566,7 @@ async function readModelView(root, original, expected) {
415
2566
  if (!(await lstat2(dir)).isDirectory())
416
2567
  throw new Error("Invalid model view directory");
417
2568
  const record2 = JSON.parse(
418
- (await readImageFileBounded(path2.join(dir, "metadata.json"), 4096)).toString()
2569
+ (await readImageFileBounded(path8.join(dir, "metadata.json"), 4096)).toString()
419
2570
  );
420
2571
  if (!record2 || record2.original_sha256 !== original.sha256 || !isImageModelView(record2.view))
421
2572
  throw new Error("Invalid model view metadata");
@@ -423,7 +2574,7 @@ async function readModelView(root, original, expected) {
423
2574
  if (expected && (view.sha256 !== expected.sha256 || view.byte_size !== expected.byte_size))
424
2575
  throw new Error("Image model view reference mismatch");
425
2576
  const bytes = await readImageFileBounded(
426
- path2.join(dir, "view.jpg"),
2577
+ path8.join(dir, "view.jpg"),
427
2578
  32 * 1024 * 1024
428
2579
  );
429
2580
  const dims = imageSize2(bytes);
@@ -458,15 +2609,15 @@ async function prepareModelView(root, original, bytes) {
458
2609
  sha256: imageHash(jpeg),
459
2610
  byte_size: jpeg.length
460
2611
  };
461
- const temporary = path2.join(root, `.model-view-${randomUUID2()}`);
462
- await mkdir2(temporary, { mode: 448 });
2612
+ const temporary = path8.join(root, `.model-view-${randomUUID4()}`);
2613
+ await mkdir3(temporary, { mode: 448 });
463
2614
  try {
464
- await writeFile2(path2.join(temporary, "view.jpg"), jpeg, {
2615
+ await writeFile2(path8.join(temporary, "view.jpg"), jpeg, {
465
2616
  flag: "wx",
466
2617
  mode: 384
467
2618
  });
468
2619
  await writeFile2(
469
- path2.join(temporary, "metadata.json"),
2620
+ path8.join(temporary, "metadata.json"),
470
2621
  JSON.stringify({ original_sha256: original.sha256, view }),
471
2622
  { flag: "wx", mode: 384 }
472
2623
  );
@@ -495,7 +2646,7 @@ var ImageArtifactStore = class {
495
2646
  const dimensions = mediaType === "image/png" ? await validateImagePng(bytes) : validateImageAttachment(bytes, "image/jpeg");
496
2647
  if (mediaType === "image/jpeg" && (bytes.at(-2) !== 255 || bytes.at(-1) !== 217))
497
2648
  throw new Error("Invalid generated JPEG: missing end marker");
498
- const artifact_id = `codelia-image-${randomUUID3()}`;
2649
+ const artifact_id = `codelia-image-${randomUUID5()}`;
499
2650
  const metadata = parseImageMetadata({
500
2651
  ...provenance,
501
2652
  ...dimensions,
@@ -511,7 +2662,7 @@ var ImageArtifactStore = class {
511
2662
  return metadata;
512
2663
  }
513
2664
  async saveAttachment(bytes, mediaType, {
514
- artifactId = `codelia-image-${randomUUID3()}`,
2665
+ artifactId = `codelia-image-${randomUUID5()}`,
515
2666
  ownerSessionId
516
2667
  } = {}) {
517
2668
  if (!ID2.test(artifactId)) throw new Error("Invalid image artifact id");
@@ -545,15 +2696,15 @@ var ImageArtifactStore = class {
545
2696
  const { metadata } = await this.read(ref.artifact_id, sessionId);
546
2697
  if (metadata.kind !== "attachment" || metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size)
547
2698
  throw new Error("Image attachment rollback reference mismatch");
548
- await rm3(path3.join(this.root, ref.artifact_id), { recursive: true });
2699
+ await rm3(path9.join(this.root, ref.artifact_id), { recursive: true });
549
2700
  }
550
2701
  async persist(bytes, metadata, ownerSessionId) {
551
- await mkdir3(this.root, { recursive: true, mode: 448 });
552
- const temporary = path3.join(this.root, `.pending-${randomUUID3()}`);
553
- await mkdir3(temporary, { mode: 448 });
2702
+ await mkdir4(this.root, { recursive: true, mode: 448 });
2703
+ const temporary = path9.join(this.root, `.pending-${randomUUID5()}`);
2704
+ await mkdir4(temporary, { mode: 448 });
554
2705
  try {
555
2706
  await writeFile3(
556
- path3.join(temporary, imageOriginalFilename(metadata.media_type)),
2707
+ path9.join(temporary, imageOriginalFilename(metadata.media_type)),
557
2708
  bytes,
558
2709
  {
559
2710
  flag: "wx",
@@ -561,14 +2712,14 @@ var ImageArtifactStore = class {
561
2712
  }
562
2713
  );
563
2714
  await writeFile3(
564
- path3.join(temporary, "metadata.json"),
2715
+ path9.join(temporary, "metadata.json"),
565
2716
  JSON.stringify({
566
2717
  ...metadata,
567
2718
  ...ownerSessionId !== void 0 ? { owner_session_id: ownerSessionId } : {}
568
2719
  }),
569
2720
  { flag: "wx", mode: 384 }
570
2721
  );
571
- await rename3(temporary, path3.join(this.root, metadata.artifact_id));
2722
+ await rename3(temporary, path9.join(this.root, metadata.artifact_id));
572
2723
  } catch (error) {
573
2724
  await rm3(temporary, { recursive: true, force: true });
574
2725
  throw error;
@@ -577,18 +2728,18 @@ var ImageArtifactStore = class {
577
2728
  async read(artifactId, sessionId = this.getSessionId?.() ?? null) {
578
2729
  if (!ID2.test(artifactId)) throw new Error("Invalid image artifact id");
579
2730
  try {
580
- const dir = path3.join(this.root, artifactId);
2731
+ const dir = path9.join(this.root, artifactId);
581
2732
  if (!(await lstat3(dir)).isDirectory())
582
2733
  throw new Error("Invalid artifact directory");
583
2734
  const rawMetadata = JSON.parse(
584
- (await readImageFileBounded(path3.join(dir, "metadata.json"), 16384)).toString()
2735
+ (await readImageFileBounded(path9.join(dir, "metadata.json"), 16384)).toString()
585
2736
  );
586
2737
  const metadata = parseImageMetadata(rawMetadata);
587
2738
  const owner = rawMetadata.owner_session_id;
588
2739
  if (owner !== void 0 && (metadata.kind !== "attachment" || typeof owner !== "string" || !owner || owner !== sessionId))
589
2740
  throw new Error("Image artifact owned by another session");
590
2741
  const bytes = await readImageFileBounded(
591
- path3.join(dir, imageOriginalFilename(metadata.media_type)),
2742
+ path9.join(dir, imageOriginalFilename(metadata.media_type)),
592
2743
  IMAGE_MAX_BYTES
593
2744
  );
594
2745
  const dims = metadata.kind === "attachment" ? validateImageAttachment(bytes, metadata.media_type) : metadata.media_type === "image/png" ? await validateImagePng(bytes) : validateImageAttachment(bytes, "image/jpeg");
@@ -617,7 +2768,7 @@ var ImageArtifactStore = class {
617
2768
  };
618
2769
  if (original) return ref;
619
2770
  const model_view = await prepareModelView(
620
- path3.join(this.root, artifactId),
2771
+ path9.join(this.root, artifactId),
621
2772
  metadata,
622
2773
  bytes
623
2774
  );
@@ -628,7 +2779,7 @@ var ImageArtifactStore = class {
628
2779
  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)
629
2780
  throw new Error("Image artifact reference mismatch");
630
2781
  const input = ref.model_view !== void 0 ? await readModelView(
631
- path3.join(this.root, ref.artifact_id),
2782
+ path9.join(this.root, ref.artifact_id),
632
2783
  metadata,
633
2784
  ref.model_view
634
2785
  ) : { bytes, view: metadata };
@@ -643,98 +2794,84 @@ var ImageArtifactStore = class {
643
2794
  };
644
2795
 
645
2796
  // src/mcp-auth-store.ts
646
- import { promises as fs } from "fs";
647
-
648
- // src/paths.ts
649
- import { mkdir as mkdir4 } from "fs/promises";
650
- import os from "os";
651
- import path4 from "path";
652
- var DEFAULT_ROOT_DIR = ".codelia";
653
- var LAYOUT_ENV = "CODELIA_LAYOUT";
654
- var XDG_DIR_NAME = "codelia";
655
- var CONFIG_FILENAME = "config.json";
656
- var AUTH_FILENAME = "auth.json";
657
- var MCP_AUTH_FILENAME = "mcp-auth.json";
658
- var PROJECTS_FILENAME = "projects.json";
659
- var CACHE_DIRNAME = "cache";
660
- var TOOL_OUTPUT_CACHE_DIRNAME = "tool-output";
661
- var SESSIONS_DIRNAME = "sessions";
662
- var LOGS_DIRNAME = "logs";
663
- function resolveStoragePaths(options = {}) {
664
- if (options.rootOverride) {
665
- return buildHomeLayout(options.rootOverride);
2797
+ import { promises as fs6 } from "fs";
2798
+ var MCP_AUTH_VERSION = 2;
2799
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2800
+ var pickString = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
2801
+ var pickNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
2802
+ var canonicalizeMcpUri = (raw) => {
2803
+ const parsed = new URL(raw.trim());
2804
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
2805
+ throw new Error(`Unsupported MCP URI scheme: ${parsed.protocol}`);
666
2806
  }
667
- const layoutValue = options.layout ?? process.env[LAYOUT_ENV];
668
- const layout = normalizeLayout(layoutValue);
669
- if (layout === "xdg") {
670
- return buildXdgLayout();
2807
+ parsed.hash = "";
2808
+ parsed.hostname = parsed.hostname.toLowerCase();
2809
+ if (parsed.protocol === "http:" && parsed.port === "80" || parsed.protocol === "https:" && parsed.port === "443") {
2810
+ parsed.port = "";
671
2811
  }
672
- return buildHomeLayout(defaultHomeRoot());
673
- }
674
- async function ensureStorageDirs(paths) {
675
- await Promise.all([
676
- mkdir4(paths.configDir, { recursive: true }),
677
- mkdir4(paths.cacheDir, { recursive: true }),
678
- mkdir4(paths.toolOutputCacheDir, { recursive: true }),
679
- mkdir4(paths.sessionsDir, { recursive: true }),
680
- mkdir4(paths.logsDir, { recursive: true })
681
- ]);
682
- }
683
- function normalizeLayout(value) {
684
- if (value && value.toLowerCase() === "xdg") return "xdg";
685
- return "home";
686
- }
687
- function defaultHomeRoot() {
688
- return path4.join(os.homedir(), DEFAULT_ROOT_DIR);
689
- }
690
- function buildHomeLayout(root) {
691
- const configDir = root;
692
- return {
693
- root,
694
- configDir,
695
- configFile: path4.join(configDir, CONFIG_FILENAME),
696
- authFile: path4.join(configDir, AUTH_FILENAME),
697
- mcpAuthFile: path4.join(configDir, MCP_AUTH_FILENAME),
698
- projectsFile: path4.join(configDir, PROJECTS_FILENAME),
699
- cacheDir: path4.join(root, CACHE_DIRNAME),
700
- toolOutputCacheDir: path4.join(
701
- root,
702
- CACHE_DIRNAME,
703
- TOOL_OUTPUT_CACHE_DIRNAME
704
- ),
705
- sessionsDir: path4.join(root, SESSIONS_DIRNAME),
706
- logsDir: path4.join(root, LOGS_DIRNAME)
707
- };
708
- }
709
- function buildXdgLayout() {
710
- const home = os.homedir();
711
- const configRoot = process.env.XDG_CONFIG_HOME ?? path4.join(home, ".config");
712
- const cacheRoot = process.env.XDG_CACHE_HOME ?? path4.join(home, ".cache");
713
- const stateRoot = process.env.XDG_STATE_HOME ?? path4.join(home, ".local", "state");
714
- const configDir = path4.join(configRoot, XDG_DIR_NAME);
715
- const cacheDir = path4.join(cacheRoot, XDG_DIR_NAME);
716
- const stateDir = path4.join(stateRoot, XDG_DIR_NAME);
2812
+ return parsed.toString();
2813
+ };
2814
+ var deriveMcpIssuer = (options) => {
2815
+ if (options.issuer?.trim()) return options.issuer;
2816
+ const endpoint = options.tokenUrl ?? options.authorizationUrl;
2817
+ if (!endpoint?.trim()) return void 0;
2818
+ try {
2819
+ return new URL(canonicalizeMcpUri(endpoint)).origin;
2820
+ } catch {
2821
+ return void 0;
2822
+ }
2823
+ };
2824
+ var buildMcpAuthBinding = (options) => {
2825
+ const resource_uri = canonicalizeMcpUri(options.resourceUri);
2826
+ const issuer = deriveMcpIssuer({
2827
+ issuer: options.issuer,
2828
+ tokenUrl: options.tokenEndpoint
2829
+ });
2830
+ const token_endpoint = options.tokenEndpoint?.trim() ? canonicalizeMcpUri(options.tokenEndpoint) : void 0;
2831
+ const client_id = pickString(options.clientId);
717
2832
  return {
718
- root: stateDir,
719
- configDir,
720
- configFile: path4.join(configDir, CONFIG_FILENAME),
721
- authFile: path4.join(configDir, AUTH_FILENAME),
722
- mcpAuthFile: path4.join(configDir, MCP_AUTH_FILENAME),
723
- projectsFile: path4.join(configDir, PROJECTS_FILENAME),
724
- cacheDir,
725
- toolOutputCacheDir: path4.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
726
- sessionsDir: path4.join(stateDir, SESSIONS_DIRNAME),
727
- logsDir: path4.join(stateDir, LOGS_DIRNAME)
2833
+ resource_uri,
2834
+ ...issuer ? { issuer } : {},
2835
+ ...token_endpoint ? { token_endpoint } : {},
2836
+ ...client_id ? { client_id } : {}
728
2837
  };
729
- }
730
-
731
- // src/mcp-auth-store.ts
732
- var MCP_AUTH_VERSION = 1;
733
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
734
- var pickString = (value) => typeof value === "string" ? value : void 0;
735
- var pickNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
2838
+ };
2839
+ var mcpAuthBindingMatches = (stored, resolved) => {
2840
+ let storedResource;
2841
+ let resolvedResource;
2842
+ try {
2843
+ storedResource = canonicalizeMcpUri(stored.resource_uri);
2844
+ resolvedResource = canonicalizeMcpUri(resolved.resource_uri);
2845
+ } catch {
2846
+ return false;
2847
+ }
2848
+ if (storedResource !== resolvedResource) return false;
2849
+ if (stored.issuer) {
2850
+ const normStored = deriveMcpIssuer({ issuer: stored.issuer });
2851
+ const normResolved = resolved.issuer ? deriveMcpIssuer({ issuer: resolved.issuer }) : resolved.token_endpoint ? deriveMcpIssuer({ tokenUrl: resolved.token_endpoint }) : void 0;
2852
+ if (!normStored || !normResolved || normStored !== normResolved) {
2853
+ return false;
2854
+ }
2855
+ }
2856
+ if (stored.token_endpoint) {
2857
+ if (!resolved.token_endpoint) return false;
2858
+ try {
2859
+ if (canonicalizeMcpUri(stored.token_endpoint) !== canonicalizeMcpUri(resolved.token_endpoint)) {
2860
+ return false;
2861
+ }
2862
+ } catch {
2863
+ return false;
2864
+ }
2865
+ }
2866
+ if (stored.client_id) {
2867
+ if (!resolved.client_id || stored.client_id !== resolved.client_id) {
2868
+ return false;
2869
+ }
2870
+ }
2871
+ return true;
2872
+ };
736
2873
  var normalizeTokens = (value) => {
737
- if (!isRecord(value)) return null;
2874
+ if (!isRecord4(value)) return null;
738
2875
  const accessToken = pickString(value.access_token);
739
2876
  if (!accessToken) return null;
740
2877
  return {
@@ -747,59 +2884,245 @@ var normalizeTokens = (value) => {
747
2884
  ...pickString(value.client_secret) ? { client_secret: pickString(value.client_secret) } : {}
748
2885
  };
749
2886
  };
2887
+ var normalizeBinding = (value) => {
2888
+ if (!isRecord4(value)) return null;
2889
+ const rawResource = pickString(value.resource_uri);
2890
+ if (!rawResource) return null;
2891
+ try {
2892
+ return buildMcpAuthBinding({
2893
+ resourceUri: rawResource,
2894
+ issuer: pickString(value.issuer),
2895
+ tokenEndpoint: pickString(value.token_endpoint),
2896
+ clientId: pickString(value.client_id)
2897
+ });
2898
+ } catch {
2899
+ return null;
2900
+ }
2901
+ };
2902
+ var parseMcpAuthDocument = (text) => {
2903
+ const parsed = JSON.parse(text);
2904
+ if (!isRecord4(parsed)) {
2905
+ throw new Error("mcp-auth.json has unsupported format");
2906
+ }
2907
+ if (parsed.version === 1) {
2908
+ const serversRaw2 = isRecord4(parsed.servers) ? parsed.servers : {};
2909
+ const droppedLegacyServers = Object.entries(serversRaw2).filter(([, entry]) => normalizeTokens(entry) !== null).map(([id2]) => id2).sort();
2910
+ return {
2911
+ normalized: { version: MCP_AUTH_VERSION, servers: {} },
2912
+ sourceVersion: 1,
2913
+ droppedLegacyServers
2914
+ };
2915
+ }
2916
+ if (parsed.version !== MCP_AUTH_VERSION) {
2917
+ throw new Error("mcp-auth.json has unsupported version");
2918
+ }
2919
+ if (parsed.servers !== void 0 && !isRecord4(parsed.servers)) {
2920
+ throw new Error("mcp-auth.json v2 has invalid servers map");
2921
+ }
2922
+ const serversRaw = isRecord4(parsed.servers) ? parsed.servers : {};
2923
+ const servers = {};
2924
+ for (const [id2, entry] of Object.entries(serversRaw)) {
2925
+ if (!isRecord4(entry)) {
2926
+ throw new Error(`mcp-auth.json v2 has invalid entry for '${id2}'`);
2927
+ }
2928
+ const binding = normalizeBinding(entry.binding);
2929
+ if (!binding) {
2930
+ throw new Error(`mcp-auth.json v2 has invalid binding for '${id2}'`);
2931
+ }
2932
+ const tokens = normalizeTokens(entry.tokens);
2933
+ if (!tokens) {
2934
+ throw new Error(`mcp-auth.json v2 has invalid tokens for '${id2}'`);
2935
+ }
2936
+ servers[id2] = { binding, tokens };
2937
+ }
2938
+ return {
2939
+ normalized: { version: MCP_AUTH_VERSION, servers },
2940
+ sourceVersion: 2,
2941
+ droppedLegacyServers: []
2942
+ };
2943
+ };
2944
+ var mcpAuthStoreAdapter = {
2945
+ name: "mcp_auth",
2946
+ service: CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
2947
+ filePath: (paths) => paths.mcpAuthFile,
2948
+ legacyFilePath: (paths) => paths.legacyMcpAuthFile,
2949
+ empty: () => ({ version: MCP_AUTH_VERSION, servers: {} }),
2950
+ isNonEmpty: (doc) => Object.keys(doc.servers).length > 0,
2951
+ parse: (text) => {
2952
+ const parsed = parseMcpAuthDocument(text);
2953
+ return {
2954
+ normalized: parsed.normalized,
2955
+ sourceVersion: parsed.sourceVersion,
2956
+ extraWarnings: parsed.droppedLegacyServers
2957
+ };
2958
+ }
2959
+ };
2960
+ var readTextIfPresent2 = async (filePath) => {
2961
+ if (!await verifyWindowsCredentialFileAcl(filePath)) return null;
2962
+ try {
2963
+ return await fs6.readFile(filePath, "utf8");
2964
+ } catch (error) {
2965
+ if (error?.code === "ENOENT") return null;
2966
+ throw error;
2967
+ }
2968
+ };
750
2969
  var McpAuthStore = class {
751
2970
  paths;
752
- constructor(paths) {
2971
+ lockOptions;
2972
+ storageMode;
2973
+ keychain;
2974
+ constructor(paths, options) {
753
2975
  this.paths = paths ?? resolveStoragePaths();
2976
+ this.lockOptions = options?.lock;
2977
+ this.storageMode = options?.storageMode;
2978
+ this.keychain = options?.keychain ?? new MacOsKeychainClient({ credentialsDir: this.paths.credentialsDir });
2979
+ }
2980
+ lockPath() {
2981
+ return authLockPathFor(this.paths.credentialsDir);
2982
+ }
2983
+ keychainAccount() {
2984
+ return keychainAccountForConfigDir(this.paths.configDir);
2985
+ }
2986
+ resolveBackendUnlocked() {
2987
+ return coordinateCredentialBackendUnlocked({
2988
+ paths: this.paths,
2989
+ storageMode: this.storageMode,
2990
+ keychain: this.keychain,
2991
+ authAdapter: providerAuthStoreAdapter,
2992
+ mcpAdapter: mcpAuthStoreAdapter
2993
+ });
754
2994
  }
755
- async load() {
756
- try {
757
- const text = await fs.readFile(this.paths.mcpAuthFile, "utf8");
758
- const parsed = JSON.parse(text);
759
- if (!isRecord(parsed) || parsed.version !== MCP_AUTH_VERSION) {
760
- throw new Error("mcp-auth.json has unsupported version");
761
- }
762
- const serversRaw = isRecord(parsed.servers) ? parsed.servers : {};
763
- const servers = {};
764
- for (const [id2, entry] of Object.entries(serversRaw)) {
765
- const normalized = normalizeTokens(entry);
766
- if (normalized) {
767
- servers[id2] = normalized;
768
- }
769
- }
770
- return {
771
- version: MCP_AUTH_VERSION,
772
- servers
773
- };
774
- } catch (error) {
775
- const err = error;
776
- if (err?.code === "ENOENT") {
2995
+ async recordDroppedLegacyServers(dropped) {
2996
+ if (!dropped.length) return;
2997
+ await ensureStorageDirs(this.paths);
2998
+ const existing = await readAuthStorageState(this.paths.authStateFile).catch(
2999
+ () => null
3000
+ );
3001
+ const merged = [
3002
+ .../* @__PURE__ */ new Set([...existing?.mcp_reauth_required ?? [], ...dropped])
3003
+ ].sort();
3004
+ await writeAuthStorageState(this.paths.authStateFile, {
3005
+ version: 1,
3006
+ status: "steady",
3007
+ active_backend: existing?.active_backend ?? "file",
3008
+ mcp_reauth_required: merged
3009
+ });
3010
+ }
3011
+ async readFromBackend(active) {
3012
+ if (active === "keyring") {
3013
+ const text2 = await this.keychain.get(
3014
+ CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
3015
+ this.keychainAccount()
3016
+ );
3017
+ if (text2 === null) {
777
3018
  return { version: MCP_AUTH_VERSION, servers: {} };
778
3019
  }
779
- throw error;
3020
+ const parsed2 = parseMcpAuthDocument(text2);
3021
+ if (parsed2.sourceVersion === 1) {
3022
+ await this.writeToBackend("keyring", parsed2.normalized);
3023
+ await this.recordDroppedLegacyServers(parsed2.droppedLegacyServers);
3024
+ }
3025
+ return parsed2.normalized;
780
3026
  }
3027
+ const text = await readTextIfPresent2(this.paths.mcpAuthFile);
3028
+ if (text === null) {
3029
+ return { version: MCP_AUTH_VERSION, servers: {} };
3030
+ }
3031
+ const parsed = parseMcpAuthDocument(text);
3032
+ if (parsed.sourceVersion === 1) {
3033
+ await this.writeToBackend("file", parsed.normalized);
3034
+ await this.recordDroppedLegacyServers(parsed.droppedLegacyServers);
3035
+ }
3036
+ return parsed.normalized;
781
3037
  }
782
- async save(auth) {
3038
+ async clearReauthenticatedServers(authenticatedServers) {
3039
+ if (!authenticatedServers.length) return;
3040
+ const existing = await readAuthStorageState(this.paths.authStateFile).catch(
3041
+ () => null
3042
+ );
3043
+ if (!existing?.mcp_reauth_required?.length) return;
3044
+ const authenticated = new Set(authenticatedServers);
3045
+ const remaining = existing.mcp_reauth_required.filter(
3046
+ (id2) => !authenticated.has(id2)
3047
+ );
3048
+ if (remaining.length === existing.mcp_reauth_required.length) return;
3049
+ const { mcp_reauth_required: _prev, ...rest } = existing;
3050
+ await writeAuthStorageState(this.paths.authStateFile, {
3051
+ ...rest,
3052
+ ...remaining.length ? { mcp_reauth_required: remaining } : {}
3053
+ });
3054
+ }
3055
+ async writeToBackend(active, auth) {
3056
+ if (active === "keyring") {
3057
+ await this.keychain.set(
3058
+ CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
3059
+ this.keychainAccount(),
3060
+ JSON.stringify(auth)
3061
+ );
3062
+ await this.clearReauthenticatedServers(Object.keys(auth.servers));
3063
+ return;
3064
+ }
783
3065
  await ensureStorageDirs(this.paths);
784
3066
  const data = JSON.stringify(auth, null, 2);
785
- await fs.writeFile(this.paths.mcpAuthFile, data, { mode: 384 });
786
- try {
787
- await fs.chmod(this.paths.mcpAuthFile, 384);
788
- } catch {
789
- }
3067
+ await writeFileAtomic(this.paths.mcpAuthFile, data, { mode: 384 });
3068
+ await this.clearReauthenticatedServers(Object.keys(auth.servers));
3069
+ }
3070
+ /**
3071
+ * Load normalized v2 MCP auth from the active backend (macOS Keychain or
3072
+ * protected `credentials/` file), running safe two-phase migration if needed.
3073
+ */
3074
+ async load() {
3075
+ return withAuthStoreLock(
3076
+ this.lockPath(),
3077
+ async () => {
3078
+ const resolved = await this.resolveBackendUnlocked();
3079
+ return this.readFromBackend(resolved.active);
3080
+ },
3081
+ this.lockOptions
3082
+ );
3083
+ }
3084
+ /**
3085
+ * Reload, mutate, and atomically save under the interprocess auth lock.
3086
+ * Skips writing if the serialized document did not change.
3087
+ */
3088
+ update(mutate) {
3089
+ return withAuthStoreLock(
3090
+ this.lockPath(),
3091
+ async () => {
3092
+ const resolved = await this.resolveBackendUnlocked();
3093
+ const auth = await this.readFromBackend(resolved.active);
3094
+ const before = JSON.stringify(auth);
3095
+ const result = await mutate(auth);
3096
+ if (JSON.stringify(auth) !== before) {
3097
+ await this.writeToBackend(resolved.active, auth);
3098
+ }
3099
+ return result;
3100
+ },
3101
+ this.lockOptions
3102
+ );
3103
+ }
3104
+ async save(auth) {
3105
+ await withAuthStoreLock(
3106
+ this.lockPath(),
3107
+ async () => {
3108
+ const resolved = await this.resolveBackendUnlocked();
3109
+ await this.writeToBackend(resolved.active, auth);
3110
+ },
3111
+ this.lockOptions
3112
+ );
790
3113
  }
791
3114
  };
792
3115
 
793
3116
  // src/process-identity.ts
794
- import { execFile } from "child_process";
795
- import { promises as fs2 } from "fs";
3117
+ import { execFile as execFile3 } from "child_process";
3118
+ import { promises as fs7 } from "fs";
796
3119
  var getProcessIdentity = async (pid, options = {}) => {
797
3120
  if (!Number.isSafeInteger(pid) || pid <= 0) return null;
798
3121
  if (process.platform === "linux") {
799
3122
  try {
800
3123
  const [stat, boot] = await Promise.all([
801
- fs2.readFile(`/proc/${pid}/stat`, "utf8"),
802
- fs2.readFile("/proc/sys/kernel/random/boot_id", "utf8")
3124
+ fs7.readFile(`/proc/${pid}/stat`, "utf8"),
3125
+ fs7.readFile("/proc/sys/kernel/random/boot_id", "utf8")
803
3126
  ]);
804
3127
  return `${boot.trim()}:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
805
3128
  } catch {
@@ -808,7 +3131,7 @@ var getProcessIdentity = async (pid, options = {}) => {
808
3131
  }
809
3132
  if (process.platform === "darwin")
810
3133
  return new Promise((resolve) => {
811
- execFile(
3134
+ execFile3(
812
3135
  "/bin/ps",
813
3136
  ["-p", String(pid), "-o", "lstart="],
814
3137
  {
@@ -823,75 +3146,319 @@ var getProcessIdentity = async (pid, options = {}) => {
823
3146
  };
824
3147
 
825
3148
  // src/projects-store.ts
826
- import { promises as fs3 } from "fs";
827
- import path5 from "path";
828
- import { parseApprovalMode } from "@codelia/shared-types";
829
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
830
- var parseApprovalModeField = (fieldPath, value) => {
831
- const parsed = parseApprovalMode(value);
832
- if (!parsed) {
833
- throw new Error(`${fieldPath} is invalid`);
3149
+ import { randomUUID as randomUUID6 } from "crypto";
3150
+ import { constants as constants4, promises as fs9 } from "fs";
3151
+ import path11 from "path";
3152
+ import { setTimeout as delay2 } from "timers/promises";
3153
+ import {
3154
+ parseApprovalMode,
3155
+ parseSandboxMode
3156
+ } from "@codelia/shared-types";
3157
+
3158
+ // src/user-storage-boundary.ts
3159
+ import { promises as fs8, lstatSync as lstatSync2, realpathSync as realpathSync2, statSync } from "fs";
3160
+ import os3 from "os";
3161
+ import path10 from "path";
3162
+ var isWithinPath = (root, target) => {
3163
+ const relative = path10.relative(root, target);
3164
+ return !path10.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path10.sep}`);
3165
+ };
3166
+ var canonicalPathOrResolvedSync = (target) => {
3167
+ const resolved = path10.resolve(target);
3168
+ try {
3169
+ return realpathSync2(resolved);
3170
+ } catch (error) {
3171
+ if (error.code !== "ENOENT") return resolved;
3172
+ const parent = path10.dirname(resolved);
3173
+ if (parent === resolved) return resolved;
3174
+ return path10.join(
3175
+ canonicalPathOrResolvedSync(parent),
3176
+ path10.basename(resolved)
3177
+ );
834
3178
  }
835
- return parsed;
3179
+ };
3180
+ var isSameConfigFilePath = (leftPath, rightPath) => {
3181
+ const left = canonicalPathOrResolvedSync(leftPath);
3182
+ const right = canonicalPathOrResolvedSync(rightPath);
3183
+ const samePath = process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
3184
+ if (samePath) return true;
3185
+ const leftStat = statSync(left, { bigint: true, throwIfNoEntry: false });
3186
+ const rightStat = statSync(right, { bigint: true, throwIfNoEntry: false });
3187
+ return !!leftStat && !!rightStat && leftStat.ino !== 0n && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
3188
+ };
3189
+ var isCanonicalHomeWorkspaceSync = (workspace) => {
3190
+ try {
3191
+ const home = path10.resolve(os3.homedir());
3192
+ return realpathSync2(workspace) === realpathSync2(home);
3193
+ } catch {
3194
+ return false;
3195
+ }
3196
+ };
3197
+ var isOwnedAncestor = (info, uid) => info.isDirectory() && (info.uid === 0 || info.uid === uid) && ((info.mode & 18) === 0 || (info.mode & 512) !== 0);
3198
+ var isOwnedPrivateDirectory = (info, uid) => info.isDirectory() && info.uid === BigInt(uid) && (info.mode & 0o022n) === 0n;
3199
+ var verifyOwnedAncestors = async (directory2, uid, errorMessage = "unsafe_projects_policy_ancestor") => {
3200
+ let child = directory2;
3201
+ while (child !== path10.dirname(child)) {
3202
+ child = path10.dirname(child);
3203
+ const info = await fs8.stat(child);
3204
+ if (!isOwnedAncestor(info, uid)) throw new Error(errorMessage);
3205
+ }
3206
+ };
3207
+ var verifyOwnedAncestorsSync = (directory2, uid, errorMessage = "unsafe_projects_policy_ancestor") => {
3208
+ let child = directory2;
3209
+ while (child !== path10.dirname(child)) {
3210
+ child = path10.dirname(child);
3211
+ const info = statSync(child);
3212
+ if (!isOwnedAncestor(info, uid)) throw new Error(errorMessage);
3213
+ }
3214
+ };
3215
+ var evaluateHomeReservedStorage = ({
3216
+ workspace,
3217
+ configured,
3218
+ resolved,
3219
+ relativePath,
3220
+ reservedOverride,
3221
+ home,
3222
+ canonicalHome,
3223
+ errorMessage,
3224
+ redirectErrorMessage
3225
+ }) => {
3226
+ const apparentHome = isWithinPath(home, configured) ? home : canonicalHome;
3227
+ const base = resolveDefaultHomeConfigDir(apparentHome);
3228
+ const expectedReserved = path10.resolve(
3229
+ reservedOverride ?? (relativePath ? path10.join(base, relativePath) : base)
3230
+ );
3231
+ if (workspace !== canonicalHome || configured !== expectedReserved || !isWithinPath(apparentHome, configured))
3232
+ throw new Error(errorMessage);
3233
+ const expectedResolved = path10.join(
3234
+ canonicalHome,
3235
+ path10.relative(apparentHome, configured)
3236
+ );
3237
+ if (resolved !== expectedResolved) throw new Error(redirectErrorMessage);
3238
+ };
3239
+ var verifyUserStorageLocation = async ({
3240
+ workspace,
3241
+ configured,
3242
+ resolved,
3243
+ relativePath = "",
3244
+ reservedOverride,
3245
+ errorMessage = "unsafe_projects_policy_path",
3246
+ redirectErrorMessage = errorMessage
3247
+ }) => {
3248
+ const resolvedConfigured = path10.resolve(configured);
3249
+ if (!isWithinPath(workspace, resolvedConfigured) && !isWithinPath(workspace, resolved))
3250
+ return { insideWorkspace: false };
3251
+ const home = path10.resolve(os3.homedir());
3252
+ let canonicalHome;
3253
+ try {
3254
+ canonicalHome = await fs8.realpath(home);
3255
+ } catch {
3256
+ throw new Error(errorMessage);
3257
+ }
3258
+ evaluateHomeReservedStorage({
3259
+ workspace,
3260
+ configured: resolvedConfigured,
3261
+ resolved,
3262
+ relativePath,
3263
+ reservedOverride,
3264
+ home,
3265
+ canonicalHome,
3266
+ errorMessage,
3267
+ redirectErrorMessage
3268
+ });
3269
+ return { insideWorkspace: true };
3270
+ };
3271
+ var verifyUserStorageLocationSync = ({
3272
+ workspace,
3273
+ configured,
3274
+ resolved,
3275
+ relativePath = "",
3276
+ reservedOverride,
3277
+ errorMessage = "unsafe_projects_policy_path",
3278
+ redirectErrorMessage = errorMessage
3279
+ }) => {
3280
+ const resolvedConfigured = path10.resolve(configured);
3281
+ if (!isWithinPath(workspace, resolvedConfigured) && !isWithinPath(workspace, resolved))
3282
+ return { insideWorkspace: false };
3283
+ const home = path10.resolve(os3.homedir());
3284
+ let canonicalHome;
3285
+ try {
3286
+ canonicalHome = realpathSync2(home);
3287
+ } catch {
3288
+ throw new Error(errorMessage);
3289
+ }
3290
+ evaluateHomeReservedStorage({
3291
+ workspace,
3292
+ configured: resolvedConfigured,
3293
+ resolved,
3294
+ relativePath,
3295
+ reservedOverride,
3296
+ home,
3297
+ canonicalHome,
3298
+ errorMessage,
3299
+ redirectErrorMessage
3300
+ });
3301
+ return { insideWorkspace: true };
3302
+ };
3303
+ var isTrustedGlobalConfigLocationSync = (workingDir, configPath) => {
3304
+ try {
3305
+ const workspace = realpathSync2(workingDir);
3306
+ const configured = path10.resolve(configPath);
3307
+ const resolved = canonicalPathOrResolvedSync(configured);
3308
+ const { insideWorkspace } = verifyUserStorageLocationSync({
3309
+ workspace,
3310
+ configured,
3311
+ resolved,
3312
+ relativePath: "config.json",
3313
+ errorMessage: "untrusted_global_config_path"
3314
+ });
3315
+ if (!insideWorkspace) return true;
3316
+ if (typeof process.geteuid !== "function") return false;
3317
+ const uid = process.geteuid();
3318
+ const dir = path10.dirname(resolved);
3319
+ if (!isOwnedPrivateDirectory(lstatSync2(dir, { bigint: true }), uid))
3320
+ return false;
3321
+ verifyOwnedAncestorsSync(dir, uid, "untrusted_global_config_path");
3322
+ const fileInfo = lstatSync2(resolved, {
3323
+ bigint: true,
3324
+ throwIfNoEntry: false
3325
+ });
3326
+ if (fileInfo && (!fileInfo.isFile() || fileInfo.nlink !== 1n || fileInfo.uid !== BigInt(uid) || (fileInfo.mode & 0o022n) !== 0n))
3327
+ return false;
3328
+ return true;
3329
+ } catch {
3330
+ return false;
3331
+ }
3332
+ };
3333
+
3334
+ // src/projects-store.ts
3335
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3336
+ var missing = (error) => error.code === "ENOENT";
3337
+ var lockFileFor = (file) => path11.join(path11.dirname(file), ".projects-policy-lock.sqlite");
3338
+ var lstatIfPresent2 = (file) => fs9.lstat(file).catch((error) => {
3339
+ if (!missing(error)) throw error;
3340
+ return void 0;
3341
+ });
3342
+ var verifyLockFile2 = async (file) => {
3343
+ const info = await lstatIfPresent2(file);
3344
+ if (info && (!info.isFile() || info.uid !== process.geteuid?.() || info.size === 0 || (info.mode & 18) !== 0))
3345
+ throw new Error("unsafe_projects_policy_lock");
3346
+ };
3347
+ var initializeUpdateLock = async (lockPath) => {
3348
+ if (await lstatIfPresent2(lockPath)) return;
3349
+ const temporary = `${lockPath}.${randomUUID6()}.tmp`;
3350
+ try {
3351
+ const file = await fs9.open(temporary, "wx", 384);
3352
+ await file.close();
3353
+ const db = await openSqlite(temporary);
3354
+ try {
3355
+ db.exec("PRAGMA user_version = 1");
3356
+ } finally {
3357
+ db.close();
3358
+ }
3359
+ try {
3360
+ await fs9.link(temporary, lockPath);
3361
+ } catch (error) {
3362
+ if (error.code !== "EEXIST") throw error;
3363
+ }
3364
+ } finally {
3365
+ await fs9.unlink(temporary).catch(() => void 0);
3366
+ }
3367
+ };
3368
+ var openUpdateLock = async (lockPath) => {
3369
+ await initializeUpdateLock(lockPath);
3370
+ await verifyLockFile2(lockPath);
3371
+ const db = await openSqlite(lockPath);
3372
+ const deadline = performance.now() + 1e3;
3373
+ try {
3374
+ db.exec("PRAGMA busy_timeout = 0");
3375
+ for (; ; ) {
3376
+ try {
3377
+ db.exec("BEGIN IMMEDIATE");
3378
+ return db;
3379
+ } catch (error) {
3380
+ if (error.code !== "SQLITE_BUSY" || performance.now() >= deadline)
3381
+ throw error;
3382
+ await delay2(20);
3383
+ }
3384
+ }
3385
+ } catch (error) {
3386
+ db.close();
3387
+ throw error;
3388
+ }
3389
+ };
3390
+ var normalizeProjectPolicy = (value, field) => {
3391
+ if (!isRecord5(value)) throw new Error(`${field} must be an object`);
3392
+ const { approval_mode, sandbox_mode, protected_paths, trust_project_allows } = value;
3393
+ if (trust_project_allows !== void 0 && typeof trust_project_allows !== "boolean")
3394
+ throw new Error(`${field}.trust_project_allows must be boolean`);
3395
+ const approvalMode = parseApprovalMode(approval_mode);
3396
+ const sandboxMode = parseSandboxMode(sandbox_mode);
3397
+ const toolAllows = value.remembered_tool_allows;
3398
+ if (toolAllows !== void 0 && (!Array.isArray(toolAllows) || toolAllows.some(
3399
+ (rule) => !isRecord5(rule) || Object.keys(rule).length !== 1 || typeof rule.tool !== "string" || !/^[a-z][a-z0-9_]*$/.test(rule.tool)
3400
+ )))
3401
+ throw new Error(
3402
+ `${field}.remembered_tool_allows must contain tool-only rules`
3403
+ );
3404
+ if (approval_mode !== void 0 && !approvalMode)
3405
+ throw new Error(`${field}.approval_mode is invalid`);
3406
+ if (sandbox_mode !== void 0 && !sandboxMode)
3407
+ throw new Error(`${field}.sandbox_mode is invalid`);
3408
+ if (protected_paths !== void 0 && (!Array.isArray(protected_paths) || protected_paths.some(
3409
+ (entry) => typeof entry !== "string" || !path11.isAbsolute(entry) || [...entry].some(
3410
+ (character) => character < " " || character === "\x7F"
3411
+ )
3412
+ )))
3413
+ throw new Error(`${field}.protected_paths must contain absolute paths`);
3414
+ return {
3415
+ ...Array.isArray(toolAllows) ? { remembered_tool_allows: toolAllows.map(({ tool }) => ({ tool })) } : {},
3416
+ ...typeof trust_project_allows === "boolean" ? { trust_project_allows } : {},
3417
+ ...approvalMode ? { approval_mode: approvalMode } : {},
3418
+ ...sandboxMode ? { sandbox_mode: sandboxMode } : {},
3419
+ ...Array.isArray(protected_paths) ? { protected_paths: [...new Set(protected_paths)] } : {}
3420
+ };
836
3421
  };
837
3422
  var normalizeProjectsPolicyFile = (value) => {
838
- if (!isRecord2(value)) {
3423
+ if (!isRecord5(value)) {
839
3424
  throw new Error("projects policy must be an object");
840
3425
  }
841
3426
  if (value.version !== 1) {
842
3427
  throw new Error("projects policy version must be 1");
843
3428
  }
844
3429
  const normalized = { version: 1 };
845
- const defaultValue = value.default;
846
- if (defaultValue !== void 0) {
847
- if (!isRecord2(defaultValue)) {
848
- throw new Error("projects policy default must be an object");
849
- }
850
- if (defaultValue.approval_mode !== void 0) {
851
- normalized.default = {
852
- approval_mode: parseApprovalModeField(
853
- "projects policy default.approval_mode",
854
- defaultValue.approval_mode
855
- )
856
- };
857
- }
3430
+ if (value.default !== void 0) {
3431
+ const entry = normalizeProjectPolicy(
3432
+ value.default,
3433
+ "projects policy default"
3434
+ );
3435
+ if (Object.keys(entry).length) normalized.default = entry;
858
3436
  }
859
- const projectsValue = value.projects;
860
- if (projectsValue !== void 0) {
861
- if (!isRecord2(projectsValue)) {
3437
+ if (value.projects !== void 0) {
3438
+ if (!isRecord5(value.projects))
862
3439
  throw new Error("projects policy projects must be an object");
863
- }
864
- const entries2 = {};
865
- for (const [key, projectValue] of Object.entries(projectsValue)) {
866
- if (!isRecord2(projectValue)) {
867
- throw new Error(`projects policy projects['${key}'] must be an object`);
868
- }
869
- if (projectValue.approval_mode !== void 0) {
870
- entries2[key] = {
871
- approval_mode: parseApprovalModeField(
872
- `projects policy projects['${key}'].approval_mode`,
873
- projectValue.approval_mode
874
- )
875
- };
876
- }
877
- }
878
- if (Object.keys(entries2).length > 0) {
879
- normalized.projects = entries2;
880
- }
3440
+ const entries2 = Object.entries(value.projects).flatMap(([key, value2]) => {
3441
+ const entry = normalizeProjectPolicy(
3442
+ value2,
3443
+ `projects policy projects['${key}']`
3444
+ );
3445
+ return Object.keys(entry).length ? [[key, entry]] : [];
3446
+ });
3447
+ if (entries2.length) normalized.projects = Object.fromEntries(entries2);
881
3448
  }
882
3449
  return normalized;
883
3450
  };
884
3451
  var atomicWriteFile = async (filePath, content) => {
885
- const dirPath = path5.dirname(filePath);
886
- const fileName = path5.basename(filePath);
887
- const tempPath = path5.join(
3452
+ const dirPath = path11.dirname(filePath);
3453
+ const fileName = path11.basename(filePath);
3454
+ const tempPath = path11.join(
888
3455
  dirPath,
889
3456
  `.${fileName}.${process.pid}.${Date.now()}.tmp`
890
3457
  );
891
- await fs3.writeFile(tempPath, content, { mode: 384 });
892
- await fs3.rename(tempPath, filePath);
3458
+ await fs9.writeFile(tempPath, content, { mode: 384 });
3459
+ await fs9.rename(tempPath, filePath);
893
3460
  if (process.platform !== "win32") {
894
- await fs3.chmod(filePath, 384);
3461
+ await fs9.chmod(filePath, 384);
895
3462
  }
896
3463
  };
897
3464
  var ProjectsPolicyStore = class {
@@ -902,10 +3469,229 @@ var ProjectsPolicyStore = class {
902
3469
  getFilePath() {
903
3470
  return this.paths.projectsFile;
904
3471
  }
905
- async load() {
3472
+ async verifyWorkspaceLocation(workspace, configured, file, access, relativePath = "projects.json", reservedFile = resolveStoragePaths().projectsFile) {
3473
+ await verifyUserStorageLocation({
3474
+ workspace,
3475
+ configured,
3476
+ resolved: file,
3477
+ relativePath,
3478
+ // Preserve existing read compatibility for owner-verified custom
3479
+ // XDG_CONFIG_HOME paths inside ~ so stored readonly/protected_paths are
3480
+ // never silently dropped, while restricting writes to default layouts.
3481
+ ...access === "read" ? { reservedOverride: reservedFile } : {},
3482
+ errorMessage: "unsafe_projects_policy_path"
3483
+ });
3484
+ }
3485
+ async trustedPath(workspace, access, configured = path11.resolve(this.paths.projectsFile), relativePath = "projects.json", reservedFile = resolveStoragePaths().projectsFile) {
3486
+ const uid = process.geteuid?.();
3487
+ if (uid === void 0) throw new Error("unsafe_projects_policy_path");
3488
+ const destination = path11.dirname(configured);
3489
+ let ancestor = destination;
3490
+ let canonical;
3491
+ for (; ; ) {
3492
+ try {
3493
+ canonical = await fs9.realpath(ancestor);
3494
+ break;
3495
+ } catch (error) {
3496
+ if (!missing(error) || ancestor === path11.dirname(ancestor)) throw error;
3497
+ if (await lstatIfPresent2(ancestor))
3498
+ throw new Error("unsafe_projects_policy_path");
3499
+ ancestor = path11.dirname(ancestor);
3500
+ }
3501
+ }
3502
+ const directory2 = path11.join(
3503
+ canonical,
3504
+ path11.relative(ancestor, destination)
3505
+ );
3506
+ const file = path11.join(directory2, path11.basename(configured));
3507
+ await this.verifyWorkspaceLocation(
3508
+ workspace,
3509
+ configured,
3510
+ file,
3511
+ access,
3512
+ relativePath,
3513
+ reservedFile
3514
+ );
3515
+ const owner = await fs9.stat(canonical);
3516
+ if (!owner.isDirectory() || owner.uid !== uid || (owner.mode & 18) !== 0)
3517
+ throw new Error("unsafe_projects_policy_directory");
3518
+ await verifyOwnedAncestors(canonical, uid);
3519
+ if (ancestor !== canonical) await verifyOwnedAncestors(ancestor, uid);
3520
+ if (access !== "read")
3521
+ await fs9.access(canonical, constants4.W_OK | constants4.X_OK);
3522
+ if (access === "create" && ancestor !== destination) {
3523
+ await fs9.mkdir(directory2, { recursive: true, mode: 448 });
3524
+ if (await fs9.realpath(directory2) !== directory2)
3525
+ throw new Error("unsafe_projects_policy_directory");
3526
+ return this.trustedPath(workspace, "write");
3527
+ }
3528
+ return file;
3529
+ }
3530
+ async readUserFile(file, owner) {
3531
+ const info = await lstatIfPresent2(file);
3532
+ if (!info) return void 0;
3533
+ if (!info.isFile() || info.nlink !== 1)
3534
+ throw new Error("unsafe_projects_policy_file");
3535
+ const handle = await fs9.open(
3536
+ file,
3537
+ constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0)
3538
+ );
3539
+ try {
3540
+ const current = await handle.stat();
3541
+ if (!current.isFile() || current.dev !== info.dev || current.ino !== info.ino || current.nlink !== 1 || owner !== null && (current.uid !== owner || (current.mode & 18) !== 0))
3542
+ throw new Error("unsafe_projects_policy_file");
3543
+ return await handle.readFile("utf8");
3544
+ } finally {
3545
+ await handle.close();
3546
+ }
3547
+ }
3548
+ /** Read user-authored permission settings through the same private-file boundary as project trust. */
3549
+ async readUserConfig(workspace, configured) {
3550
+ const uid = process.geteuid?.();
3551
+ if (uid === void 0) throw new Error("unsafe_projects_policy_path");
3552
+ const file = await this.trustedPath(
3553
+ workspace,
3554
+ "read",
3555
+ path11.resolve(configured),
3556
+ "config.json",
3557
+ this.paths.configFile
3558
+ );
3559
+ return this.readUserFile(file, uid);
3560
+ }
3561
+ async readPolicyFile(file, owner) {
3562
+ const text = await this.readUserFile(file, owner);
3563
+ const raw = text === void 0 ? { version: 1 } : JSON.parse(text);
3564
+ const normalized = normalizeProjectsPolicyFile(raw);
3565
+ return { raw, normalized };
3566
+ }
3567
+ readTrusted(file) {
3568
+ const owner = process.geteuid?.();
3569
+ if (owner === void 0) throw new Error("unsafe_projects_policy_path");
3570
+ return this.readPolicyFile(file, owner);
3571
+ }
3572
+ async hasUnverifiableProtectedPaths(workspace) {
3573
+ const configured = path11.resolve(this.paths.projectsFile);
3574
+ const canonicalParent = await fs9.realpath(path11.dirname(configured));
3575
+ const file = path11.join(canonicalParent, path11.basename(configured));
3576
+ await this.verifyWorkspaceLocation(workspace, configured, file, "read");
3577
+ const { normalized: policy } = await this.readPolicyFile(file, null);
3578
+ return Boolean(
3579
+ policy.default?.protected_paths?.length || Object.entries(policy.projects ?? {}).some(
3580
+ ([root, entry]) => entry.protected_paths?.length && path11.isAbsolute(root) && path11.relative(workspace, root) === ""
3581
+ )
3582
+ );
3583
+ }
3584
+ async loadUserOwned(workspace, { strict = false } = {}) {
3585
+ let hasUnverifiablePaths;
3586
+ try {
3587
+ if (strict && !await lstatIfPresent2(this.paths.projectsFile))
3588
+ return null;
3589
+ if (strict && process.geteuid?.() === void 0) {
3590
+ hasUnverifiablePaths = await this.hasUnverifiableProtectedPaths(workspace);
3591
+ } else {
3592
+ const file = await this.trustedPath(workspace, "read");
3593
+ return (await this.readTrusted(file)).normalized;
3594
+ }
3595
+ } catch (error) {
3596
+ if (strict)
3597
+ throw new Error("untrusted_projects_policy", { cause: error });
3598
+ return null;
3599
+ }
3600
+ if (hasUnverifiablePaths)
3601
+ throw new Error("protected_paths_owner_verification_unavailable");
3602
+ return null;
3603
+ }
3604
+ async verifyProjectModeWritable(workspace) {
3605
+ const file = await this.trustedPath(workspace, "write");
3606
+ await this.readTrusted(file);
3607
+ await verifyLockFile2(lockFileFor(file));
3608
+ }
3609
+ /** Merge into a private user policy while other runtimes are excluded. */
3610
+ async writeProjectMode(workspace, mode) {
3611
+ return this.updateProject(workspace, { sandbox_mode: mode });
3612
+ }
3613
+ async writeProjectAllowTrust(workspace, trusted, verify) {
3614
+ return this.updateProject(
3615
+ workspace,
3616
+ { trust_project_allows: trusted },
3617
+ verify
3618
+ );
3619
+ }
3620
+ async updateRememberedTool(workspace, tool, allow, verify) {
3621
+ if (!/^[a-z][a-z0-9_]*$/.test(tool))
3622
+ throw new Error("invalid_remembered_tool");
3623
+ let changed = false;
3624
+ await this.updateProject(
3625
+ workspace,
3626
+ (current) => {
3627
+ const exists = current.remembered_tool_allows?.some((rule) => rule.tool === tool) ?? false;
3628
+ if (exists === allow) return void 0;
3629
+ changed = true;
3630
+ return {
3631
+ remembered_tool_allows: [
3632
+ ...(current.remembered_tool_allows ?? []).filter(
3633
+ (rule) => rule.tool !== tool
3634
+ ),
3635
+ ...allow ? [{ tool }] : []
3636
+ ]
3637
+ };
3638
+ },
3639
+ verify
3640
+ );
3641
+ return changed;
3642
+ }
3643
+ async updateProject(workspace, patch, verify) {
3644
+ const file = await this.trustedPath(workspace, "create");
3645
+ const lock = await openUpdateLock(lockFileFor(file));
3646
+ const temporary = `${file}.${randomUUID6()}.tmp`;
3647
+ try {
3648
+ const { raw: policy } = await this.readTrusted(file);
3649
+ const projects = policy.projects;
3650
+ const changes = typeof patch === "function" ? patch(projects?.[workspace] ?? {}) : patch;
3651
+ if (!changes) {
3652
+ verify?.();
3653
+ return;
3654
+ }
3655
+ const next = {
3656
+ ...policy,
3657
+ projects: {
3658
+ ...projects,
3659
+ [workspace]: { ...projects?.[workspace], ...changes }
3660
+ }
3661
+ };
3662
+ await fs9.writeFile(temporary, `${JSON.stringify(next, null, 2)}
3663
+ `, {
3664
+ mode: 384,
3665
+ flag: "wx"
3666
+ });
3667
+ await fs9.chmod(temporary, 384);
3668
+ if (await this.trustedPath(workspace, "write") !== file)
3669
+ throw new Error("unsafe_projects_policy_path");
3670
+ verify?.();
3671
+ await fs9.rename(temporary, file);
3672
+ } finally {
3673
+ lock.close();
3674
+ await fs9.unlink(temporary).catch(() => void 0);
3675
+ }
3676
+ }
3677
+ async load(canonicalPath) {
906
3678
  try {
907
- const raw = await fs3.readFile(this.paths.projectsFile, "utf8");
908
- const parsed = JSON.parse(raw);
3679
+ const handle = await fs9.open(
3680
+ canonicalPath ?? this.paths.projectsFile,
3681
+ canonicalPath ? constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0) | (constants4.O_NONBLOCK ?? 0) : "r"
3682
+ );
3683
+ let parsed;
3684
+ try {
3685
+ if (canonicalPath) {
3686
+ const info = await handle.stat();
3687
+ const uid = process.geteuid?.();
3688
+ if (!info.isFile() || info.nlink !== 1 || uid !== void 0 && (info.uid !== uid || (info.mode & 18) !== 0))
3689
+ return null;
3690
+ }
3691
+ parsed = JSON.parse(await handle.readFile("utf8"));
3692
+ } finally {
3693
+ await handle.close();
3694
+ }
909
3695
  return normalizeProjectsPolicyFile(parsed);
910
3696
  } catch (error) {
911
3697
  if (error.code === "ENOENT") {
@@ -926,36 +3712,36 @@ var ProjectsPolicyStore = class {
926
3712
  };
927
3713
 
928
3714
  // src/session-store.ts
929
- import { promises as fs6 } from "fs";
930
- import path8 from "path";
3715
+ import { promises as fs12 } from "fs";
3716
+ import path14 from "path";
931
3717
 
932
3718
  // src/run-log-paths.ts
933
- import { createHash as createHash3 } from "crypto";
934
- import path6 from "path";
3719
+ import { createHash as createHash4 } from "crypto";
3720
+ import path12 from "path";
935
3721
  var runDatePath = (startedAt) => {
936
3722
  const date = new Date(startedAt);
937
3723
  if (!Number.isFinite(date.getTime()))
938
3724
  throw new Error("Invalid run start time");
939
- return [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join(path6.sep);
3725
+ return [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join(path12.sep);
940
3726
  };
941
3727
  var validateRunLogId = (id2) => {
942
3728
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(id2))
943
3729
  throw new Error("Invalid run/session log id");
944
3730
  return id2;
945
3731
  };
946
- var activeRunDirectory = (paths, sessionId) => path6.join(
3732
+ var activeRunDirectory = (paths, sessionId) => path12.join(
947
3733
  paths.sessionsDir,
948
3734
  "active-runs",
949
- createHash3("sha256").update(sessionId).digest("hex")
3735
+ createHash4("sha256").update(sessionId).digest("hex")
950
3736
  );
951
- var usageLogPath = (paths, datePath, runId) => path6.join(paths.root, "usage", datePath, `${validateRunLogId(runId)}.jsonl`);
3737
+ var usageLogPath = (paths, datePath, runId) => path12.join(paths.root, "usage", datePath, `${validateRunLogId(runId)}.jsonl`);
952
3738
 
953
3739
  // src/session-run-index.ts
954
- import { promises as fs5, lstatSync } from "fs";
955
- import path7 from "path";
3740
+ import { promises as fs11, lstatSync as lstatSync3 } from "fs";
3741
+ import path13 from "path";
956
3742
 
957
3743
  // src/run-log-reader.ts
958
- import { constants as constants3, existsSync, promises as fs4 } from "fs";
3744
+ import { constants as constants5, existsSync, promises as fs10 } from "fs";
959
3745
  import { createInterface } from "readline";
960
3746
  import { Readable } from "stream";
961
3747
  import { createGunzip } from "zlib";
@@ -964,17 +3750,17 @@ async function* readRunLogChunks(file) {
964
3750
  let resolved = resolveRunLogPath(file);
965
3751
  let handle;
966
3752
  try {
967
- handle = await fs4.open(
3753
+ handle = await fs10.open(
968
3754
  resolved,
969
- constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0)
3755
+ constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0)
970
3756
  );
971
3757
  } catch (error) {
972
3758
  if (error.code !== "ENOENT" || file.endsWith(".gz"))
973
3759
  throw error;
974
3760
  resolved = `${file}.gz`;
975
- handle = await fs4.open(
3761
+ handle = await fs10.open(
976
3762
  resolved,
977
- constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0)
3763
+ constants5.O_RDONLY | (constants5.O_NOFOLLOW ?? 0)
978
3764
  );
979
3765
  }
980
3766
  const source = handle.createReadStream();
@@ -1009,18 +3795,18 @@ var normalizeRunStartedAt = (startedAt) => {
1009
3795
  };
1010
3796
  var isRegularFile = (file) => {
1011
3797
  try {
1012
- return lstatSync(file).isFile();
3798
+ return lstatSync3(file).isFile();
1013
3799
  } catch {
1014
3800
  return false;
1015
3801
  }
1016
3802
  };
1017
3803
  var toRunLogRelPath = (sessionsDir, file) => {
1018
- const relative = path7.relative(sessionsDir, file).split(path7.sep).join("/").replace(/\.gz$/, "");
3804
+ const relative = path13.relative(sessionsDir, file).split(path13.sep).join("/").replace(/\.gz$/, "");
1019
3805
  return REL_PATH_PATTERN.test(relative) ? relative : void 0;
1020
3806
  };
1021
3807
  var resolveIndexedRunLog = (sessionsDir, relPath) => {
1022
3808
  if (!REL_PATH_PATTERN.test(relPath)) return void 0;
1023
- const plain = path7.join(sessionsDir, ...relPath.split("/"));
3809
+ const plain = path13.join(sessionsDir, ...relPath.split("/"));
1024
3810
  if (isRegularFile(plain)) return plain;
1025
3811
  if (isRegularFile(`${plain}.gz`)) return `${plain}.gz`;
1026
3812
  return void 0;
@@ -1040,7 +3826,7 @@ var readHeader = async (file) => {
1040
3826
  var errorCode2 = (error) => error?.code;
1041
3827
  var readDirs = async (directory2) => {
1042
3828
  try {
1043
- return await fs5.readdir(directory2, {
3829
+ return await fs11.readdir(directory2, {
1044
3830
  withFileTypes: true,
1045
3831
  encoding: "utf8"
1046
3832
  });
@@ -1058,13 +3844,13 @@ var listRunLogFiles = async (sessionsDir) => {
1058
3844
  const files = [];
1059
3845
  for (const year of await readDirs(sessionsDir)) {
1060
3846
  if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
1061
- const yearPath = path7.join(sessionsDir, year.name);
3847
+ const yearPath = path13.join(sessionsDir, year.name);
1062
3848
  for (const month of await readDirs(yearPath)) {
1063
3849
  if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
1064
- const monthPath = path7.join(yearPath, month.name);
3850
+ const monthPath = path13.join(yearPath, month.name);
1065
3851
  for (const day of await readDirs(monthPath)) {
1066
3852
  if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
1067
- const dayPath = path7.join(monthPath, day.name);
3853
+ const dayPath = path13.join(monthPath, day.name);
1068
3854
  const entries2 = (await readDirs(dayPath)).filter(
1069
3855
  (entry) => entry.isFile() && /\.jsonl(?:\.gz)?$/.test(entry.name)
1070
3856
  );
@@ -1074,7 +3860,7 @@ var listRunLogFiles = async (sessionsDir) => {
1074
3860
  for (const entry of entries2) {
1075
3861
  if (entry.name.endsWith(".gz") && plain.has(entry.name.slice(0, -3)))
1076
3862
  continue;
1077
- files.push(path7.join(dayPath, entry.name));
3863
+ files.push(path13.join(dayPath, entry.name));
1078
3864
  }
1079
3865
  }
1080
3866
  }
@@ -1094,10 +3880,10 @@ var scanSessionRunLogs = async (sessionsDir) => {
1094
3880
  try {
1095
3881
  const header = await readHeader(file);
1096
3882
  if (!header || typeof header.session_id !== "string") continue;
1097
- const startedAt = typeof header.started_at === "string" ? header.started_at : new Date((await fs5.stat(file)).mtimeMs).toISOString();
3883
+ const startedAt = typeof header.started_at === "string" ? header.started_at : new Date((await fs11.stat(file)).mtimeMs).toISOString();
1098
3884
  entries2.push({
1099
3885
  session_id: header.session_id,
1100
- run_id: typeof header.run_id === "string" ? header.run_id : path7.posix.basename(relPath, ".jsonl"),
3886
+ run_id: typeof header.run_id === "string" ? header.run_id : path13.posix.basename(relPath, ".jsonl"),
1101
3887
  rel_path: relPath,
1102
3888
  started_at: normalizeRunStartedAt(startedAt)
1103
3889
  });
@@ -1170,7 +3956,7 @@ var SessionStoreWriterImpl = class {
1170
3956
  this.runId = validateRunLogId(options.runId);
1171
3957
  this.startedAt = options.startedAt;
1172
3958
  const datePath = runDatePath(options.startedAt);
1173
- this.filePath = path8.join(
3959
+ this.filePath = path14.join(
1174
3960
  paths.sessionsDir,
1175
3961
  datePath,
1176
3962
  `${this.runId}.jsonl`
@@ -1178,7 +3964,7 @@ var SessionStoreWriterImpl = class {
1178
3964
  this.usageFilePath = usageLogPath(paths, datePath, this.runId);
1179
3965
  const dump = options.dump ?? /^(1|true)$/i.test(process.env.CODELIA_SESSION_DUMP ?? "");
1180
3966
  if (dump)
1181
- this.diagnosticFilePath = path8.join(
3967
+ this.diagnosticFilePath = path14.join(
1182
3968
  paths.sessionsDir,
1183
3969
  "diagnostics",
1184
3970
  datePath,
@@ -1253,9 +4039,9 @@ var SessionStoreWriterImpl = class {
1253
4039
  if (markerSessionId) {
1254
4040
  await this.recordRun(markerSessionId, startedAt ?? this.startedAt);
1255
4041
  const directory2 = activeRunDirectory(this.paths, markerSessionId);
1256
- await fs6.mkdir(directory2, { recursive: true });
1257
- this.activePath = path8.join(directory2, `${this.runId}.json`);
1258
- await fs6.writeFile(
4042
+ await fs12.mkdir(directory2, { recursive: true });
4043
+ this.activePath = path14.join(directory2, `${this.runId}.json`);
4044
+ await fs12.writeFile(
1259
4045
  this.activePath,
1260
4046
  JSON.stringify({
1261
4047
  pid: process.pid,
@@ -1272,11 +4058,11 @@ var SessionStoreWriterImpl = class {
1272
4058
  [this.diagnosticFilePath, dump]
1273
4059
  ]) {
1274
4060
  if (!file || line === void 0) continue;
1275
- await fs6.mkdir(path8.dirname(file), { recursive: true });
1276
- await fs6.appendFile(file, line, { encoding: "utf8", mode: 384 });
4061
+ await fs12.mkdir(path14.dirname(file), { recursive: true });
4062
+ await fs12.appendFile(file, line, { encoding: "utf8", mode: 384 });
1277
4063
  }
1278
4064
  if (terminal && this.activePath) {
1279
- await fs6.unlink(this.activePath);
4065
+ await fs12.unlink(this.activePath);
1280
4066
  this.activePath = void 0;
1281
4067
  }
1282
4068
  });
@@ -1290,22 +4076,22 @@ var SessionStoreWriterImpl = class {
1290
4076
  import {
1291
4077
  closeSync as closeSync2,
1292
4078
  existsSync as existsSync2,
1293
- promises as fs7,
4079
+ promises as fs13,
1294
4080
  fsyncSync as fsyncSync2,
1295
- lstatSync as lstatSync2,
4081
+ lstatSync as lstatSync4,
1296
4082
  openSync as openSync2,
1297
- readFileSync,
4083
+ readFileSync as readFileSync3,
1298
4084
  renameSync,
1299
4085
  unlinkSync,
1300
4086
  writeFileSync
1301
4087
  } from "fs";
1302
- import path9 from "path";
4088
+ import path15 from "path";
1303
4089
  import { stringifyContent as stringifyContent2 } from "@codelia/core";
1304
4090
 
1305
4091
  // src/conversation-archive.ts
1306
4092
  import {
1307
4093
  closeSync,
1308
- constants as constants4,
4094
+ constants as constants6,
1309
4095
  createReadStream,
1310
4096
  fstatSync,
1311
4097
  fsyncSync,
@@ -1314,13 +4100,17 @@ import {
1314
4100
  writeSync
1315
4101
  } from "fs";
1316
4102
  import { stringifyContent } from "@codelia/core";
1317
- function appendOriginalMessages(file, messages) {
4103
+ function appendOriginalMessages(file, messages, provenance) {
1318
4104
  const data = Buffer.from(
1319
- messages.map((message) => JSON.stringify(message)).join("\n") + (messages.length ? "\n" : "")
4105
+ messages.map(
4106
+ (message, index) => JSON.stringify(
4107
+ provenance?.[index] ? { ...message, approval_provenance: provenance[index] } : message
4108
+ )
4109
+ ).join("\n") + (messages.length ? "\n" : "")
1320
4110
  );
1321
4111
  const fd = openSync(
1322
4112
  file,
1323
- constants4.O_RDWR | constants4.O_CREAT | constants4.O_APPEND | (constants4.O_NOFOLLOW ?? 0),
4113
+ constants6.O_RDWR | constants6.O_CREAT | constants6.O_APPEND | (constants6.O_NOFOLLOW ?? 0),
1324
4114
  384
1325
4115
  );
1326
4116
  try {
@@ -1358,14 +4148,16 @@ var textOf = (message) => {
1358
4148
  return message.role === "assistant" && message.tool_calls?.length ? `${text}
1359
4149
  ${JSON.stringify(message.tool_calls.map((call) => ({ id: call.id, function: call.function })))}` : text;
1360
4150
  };
1361
- async function* entries(file, start) {
1362
- const fd = openSync(file, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
4151
+ async function* entries(file, start, maxBytes) {
4152
+ const fd = openSync(file, constants6.O_RDONLY | (constants6.O_NOFOLLOW ?? 0));
1363
4153
  let stream;
1364
4154
  try {
1365
4155
  const stat = fstatSync(fd);
1366
4156
  if (!stat.isFile()) throw new Error("Invalid conversation archive");
1367
4157
  if (start > stat.size)
1368
4158
  throw new Error("Conversation cursor is beyond the archive");
4159
+ if (maxBytes !== void 0 && stat.size - start > maxBytes)
4160
+ throw new Error("Approval conversation window is too large");
1369
4161
  if (start === stat.size) return;
1370
4162
  if (start > 0) {
1371
4163
  const previous = Buffer.alloc(1);
@@ -1405,6 +4197,8 @@ async function* entries(file, start) {
1405
4197
  position = end;
1406
4198
  }
1407
4199
  }
4200
+ if (maxBytes !== void 0 && length > 0)
4201
+ throw new Error("Incomplete approval conversation window");
1408
4202
  } finally {
1409
4203
  if (!stream) closeSync(fd);
1410
4204
  else if (!stream.closed) {
@@ -1416,6 +4210,47 @@ async function* entries(file, start) {
1416
4210
  }
1417
4211
  }
1418
4212
  }
4213
+ async function readOriginalApprovalContext(file, {
4214
+ userMessageId,
4215
+ proposalMessageId,
4216
+ workspace,
4217
+ cwd,
4218
+ workspaceIdentity,
4219
+ cwdIdentity
4220
+ }, isAppliedSteer) {
4221
+ const first = parseId(proposalMessageId ?? userMessageId);
4222
+ if (proposalMessageId && first >= parseId(userMessageId)) return null;
4223
+ const matchesScope = (scope) => scope.workspace === workspace && scope.cwd === cwd && scope.workspaceIdentity === workspaceIdentity && scope.cwdIdentity === cwdIdentity;
4224
+ let proposal;
4225
+ const userMessages = [];
4226
+ for await (const { id: id2, message } of entries(file, first, 2 * 1024 * 1024)) {
4227
+ const source = message.approval_provenance;
4228
+ if (message.role === "assistant") {
4229
+ if (!proposalMessageId || userMessages.length > 0) continue;
4230
+ const text = stringifyContent(message.content, { mode: "display" });
4231
+ if (!text.trim() && !message.refusal) continue;
4232
+ if (id2 !== proposalMessageId || message.tool_calls?.length || message.refusal || source?.source !== "assistant" || !matchesScope(source) || text.length > 1800)
4233
+ return null;
4234
+ proposal = { id: id2, role: "assistant", text, truncated: false };
4235
+ continue;
4236
+ }
4237
+ if (message.role !== "user" || source?.source === "internal_input")
4238
+ continue;
4239
+ if (source?.source !== "user_input" && source?.source !== "user_steer" || !matchesScope(source) || !source.text.trim() || source.text.includes("<shell_result>") || source.text.length > 1800)
4240
+ return null;
4241
+ if (userMessages.length === 0 && id2 !== userMessageId) return null;
4242
+ if (source.source === "user_steer" && !isAppliedSteer(source.runId, source.steerId))
4243
+ return null;
4244
+ userMessages.push({
4245
+ id: id2,
4246
+ role: "user",
4247
+ text: source.text,
4248
+ truncated: false
4249
+ });
4250
+ if (userMessages.length > 8) return null;
4251
+ }
4252
+ return userMessages.length && (!proposalMessageId || proposal) ? { userMessages, proposal } : null;
4253
+ }
1419
4254
  async function searchOriginalMessages(file, options) {
1420
4255
  const query = options.query.trim().toLowerCase();
1421
4256
  if (!query || query.length > 200)
@@ -1538,9 +4373,9 @@ var MESSAGES_DIRNAME = "messages";
1538
4373
  var STATE_DB_FILENAME = "state.db";
1539
4374
  var SESSION_WORKSPACE_ROOT_META_KEY = "codelia_workspace_root";
1540
4375
  var RUN_INDEX_BACKFILL_KEY = "session_runs_backfilled_at";
1541
- var resolveLegacyStateDir = (paths) => path9.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
1542
- var resolveMessagesDir = (paths) => path9.join(paths.sessionsDir, MESSAGES_DIRNAME);
1543
- var resolveStateDbPath = (paths) => path9.join(paths.sessionsDir, STATE_DB_FILENAME);
4376
+ var resolveLegacyStateDir = (paths) => path15.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
4377
+ var resolveMessagesDir = (paths) => path15.join(paths.sessionsDir, MESSAGES_DIRNAME);
4378
+ var resolveStateDbPath = (paths) => path15.join(paths.sessionsDir, STATE_DB_FILENAME);
1544
4379
  var extractLastUserMessage = (messages) => {
1545
4380
  for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
1546
4381
  const message = messages[idx];
@@ -1611,13 +4446,13 @@ var SessionStateStoreImpl = class {
1611
4446
  this.sessionsDir = paths.sessionsDir;
1612
4447
  this.legacyStateDir = resolveLegacyStateDir(paths);
1613
4448
  this.messagesDir = resolveMessagesDir(paths);
1614
- this.contextsDir = path9.join(paths.sessionsDir, "contexts");
4449
+ this.contextsDir = path15.join(paths.sessionsDir, "contexts");
1615
4450
  this.stateDbPath = resolveStateDbPath(paths);
1616
4451
  this.ensureDirs = Promise.all([
1617
- fs7.mkdir(paths.sessionsDir, { recursive: true }),
1618
- fs7.mkdir(this.legacyStateDir, { recursive: true }),
1619
- fs7.mkdir(this.messagesDir, { recursive: true }),
1620
- fs7.mkdir(this.contextsDir, { recursive: true })
4452
+ fs13.mkdir(paths.sessionsDir, { recursive: true }),
4453
+ fs13.mkdir(this.legacyStateDir, { recursive: true }),
4454
+ fs13.mkdir(this.messagesDir, { recursive: true }),
4455
+ fs13.mkdir(this.contextsDir, { recursive: true })
1621
4456
  ]).then(() => {
1622
4457
  });
1623
4458
  this.onError = options.onError;
@@ -1632,18 +4467,18 @@ var SessionStateStoreImpl = class {
1632
4467
  return this.db;
1633
4468
  }
1634
4469
  resolveLegacyPath(sessionId) {
1635
- return path9.join(this.legacyStateDir, `${sessionId}.json`);
4470
+ return path15.join(this.legacyStateDir, `${sessionId}.json`);
1636
4471
  }
1637
4472
  resolveMessagePath(sessionId) {
1638
- return path9.join(this.messagesDir, `${validateRunLogId(sessionId)}.jsonl`);
4473
+ return path15.join(this.messagesDir, `${validateRunLogId(sessionId)}.jsonl`);
1639
4474
  }
1640
4475
  contextPath(sessionId) {
1641
- return path9.join(this.contextsDir, `${validateRunLogId(sessionId)}.json`);
4476
+ return path15.join(this.contextsDir, `${validateRunLogId(sessionId)}.json`);
1642
4477
  }
1643
4478
  writeContext(sessionId, messages) {
1644
4479
  const target = this.contextPath(sessionId);
1645
4480
  const temporary = `${target}.${crypto.randomUUID()}.tmp`;
1646
- const archiveBytes = lstatSync2(this.resolveMessagePath(sessionId)).size;
4481
+ const archiveBytes = lstatSync4(this.resolveMessagePath(sessionId)).size;
1647
4482
  try {
1648
4483
  const fd = openSync2(temporary, "wx", 384);
1649
4484
  try {
@@ -1666,16 +4501,16 @@ var SessionStateStoreImpl = class {
1666
4501
  [sessionId]
1667
4502
  );
1668
4503
  if (row?.archive_version === 1) {
1669
- if (!lstatSync2(this.resolveMessagePath(sessionId)).isFile())
4504
+ if (!lstatSync4(this.resolveMessagePath(sessionId)).isFile())
1670
4505
  throw new Error("Invalid original conversation archive");
1671
4506
  return false;
1672
4507
  }
1673
4508
  const file = this.resolveMessagePath(sessionId);
1674
4509
  let messages = [];
1675
4510
  if (existsSync2(file)) {
1676
- if (!lstatSync2(file).isFile())
4511
+ if (!lstatSync4(file).isFile())
1677
4512
  throw new Error("Invalid legacy conversation file");
1678
- messages = deserializeMessages(readFileSync(file, "utf8"));
4513
+ messages = deserializeMessages(readFileSync3(file, "utf8"));
1679
4514
  } else appendOriginalMessages(file, []);
1680
4515
  this.writeContext(sessionId, messages);
1681
4516
  db.run(
@@ -1687,41 +4522,7 @@ var SessionStateStoreImpl = class {
1687
4522
  }
1688
4523
  async openDatabase() {
1689
4524
  await this.ensureDirs;
1690
- if (process.versions.bun) {
1691
- const bunSqliteSpecifier = "bun:sqlite";
1692
- const { Database } = await import(bunSqliteSpecifier);
1693
- const db2 = new Database(this.stateDbPath, { create: true });
1694
- return {
1695
- exec: (sql) => {
1696
- db2.exec(sql);
1697
- },
1698
- run: (sql, params = []) => {
1699
- db2.query(sql).run(...params);
1700
- },
1701
- get: (sql, params = []) => {
1702
- const row = db2.query(sql).get(...params);
1703
- return row ?? void 0;
1704
- },
1705
- all: (sql, params = []) => db2.query(sql).all(...params)
1706
- };
1707
- }
1708
- const betterSqliteSpecifier = "better-sqlite3";
1709
- const betterSqliteModule = await import(betterSqliteSpecifier);
1710
- const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
1711
- const db = new BetterSqlite3(this.stateDbPath);
1712
- return {
1713
- exec: (sql) => {
1714
- db.exec(sql);
1715
- },
1716
- run: (sql, params = []) => {
1717
- db.prepare(sql).run(...params);
1718
- },
1719
- get: (sql, params = []) => {
1720
- const row = db.prepare(sql).get(...params);
1721
- return row ?? void 0;
1722
- },
1723
- all: (sql, params = []) => db.prepare(sql).all(...params)
1724
- };
4525
+ return openSqlite(this.stateDbPath);
1725
4526
  }
1726
4527
  initDatabaseSchema(db) {
1727
4528
  db.exec("PRAGMA busy_timeout = 5000;");
@@ -1763,6 +4564,12 @@ var SessionStateStoreImpl = class {
1763
4564
  db.exec(`
1764
4565
  CREATE INDEX IF NOT EXISTS idx_session_state_updated_at
1765
4566
  ON session_state(updated_at DESC);
4567
+ CREATE TABLE IF NOT EXISTS session_approval_steers (
4568
+ session_id TEXT NOT NULL,
4569
+ run_id TEXT NOT NULL,
4570
+ steer_id TEXT NOT NULL,
4571
+ PRIMARY KEY (session_id, run_id, steer_id)
4572
+ );
1766
4573
  `);
1767
4574
  db.exec(`
1768
4575
  CREATE TABLE IF NOT EXISTS session_runs (
@@ -1831,7 +4638,7 @@ var SessionStateStoreImpl = class {
1831
4638
  }
1832
4639
  async loadLegacy(sessionId) {
1833
4640
  try {
1834
- const file = await fs7.readFile(this.resolveLegacyPath(sessionId), "utf8");
4641
+ const file = await fs13.readFile(this.resolveLegacyPath(sessionId), "utf8");
1835
4642
  const parsed = JSON.parse(file);
1836
4643
  if (!parsed || typeof parsed !== "object") return null;
1837
4644
  if (!parsed.session_id || !parsed.updated_at) return null;
@@ -1871,14 +4678,14 @@ var SessionStateStoreImpl = class {
1871
4678
  try {
1872
4679
  if (row.archive_version === 1) {
1873
4680
  const checkpoint = JSON.parse(
1874
- await fs7.readFile(this.contextPath(sessionId), "utf8")
4681
+ await fs13.readFile(this.contextPath(sessionId), "utf8")
1875
4682
  );
1876
4683
  if (checkpoint.version !== 1 || !Array.isArray(checkpoint.messages))
1877
4684
  throw new Error("Invalid active conversation checkpoint");
1878
4685
  messages = checkpoint.messages;
1879
4686
  } else
1880
4687
  messages = deserializeMessages(
1881
- await fs7.readFile(this.resolveMessagePath(sessionId), "utf8")
4688
+ await fs13.readFile(this.resolveMessagePath(sessionId), "utf8")
1882
4689
  );
1883
4690
  } catch (error) {
1884
4691
  if (error.code === "ENOENT" && row.archive_version !== 1) {
@@ -1958,12 +4765,16 @@ var SessionStateStoreImpl = class {
1958
4765
  );
1959
4766
  });
1960
4767
  }
1961
- async appendMessages(sessionId, messages) {
4768
+ async appendMessages(sessionId, messages, origins) {
1962
4769
  const db = await this.requireDb("archive.append", sessionId);
1963
4770
  if (!await this.getSummary(sessionId)) await this.load(sessionId);
1964
4771
  await this.withRetentionGuard(sessionId, () => {
1965
4772
  this.ensureArchive(sessionId, db);
1966
- appendOriginalMessages(this.resolveMessagePath(sessionId), messages);
4773
+ appendOriginalMessages(
4774
+ this.resolveMessagePath(sessionId),
4775
+ messages,
4776
+ origins
4777
+ );
1967
4778
  });
1968
4779
  }
1969
4780
  async searchMessages(sessionId, options) {
@@ -1974,6 +4785,25 @@ var SessionStateStoreImpl = class {
1974
4785
  if (!await this.getSummary(sessionId)) await this.load(sessionId);
1975
4786
  return readOriginalMessage(this.resolveMessagePath(sessionId), options);
1976
4787
  }
4788
+ async readApprovalContext(sessionId, references) {
4789
+ if (!await this.getSummary(sessionId)) return null;
4790
+ const db = await this.requireDb("archive.approval", sessionId);
4791
+ return readOriginalApprovalContext(
4792
+ this.resolveMessagePath(sessionId),
4793
+ references,
4794
+ (runId, steerId) => !!db.get(
4795
+ "SELECT 1 AS applied FROM session_approval_steers WHERE session_id = ? AND run_id = ? AND steer_id = ?",
4796
+ [sessionId, runId, steerId]
4797
+ )
4798
+ );
4799
+ }
4800
+ async confirmApprovalSteer(sessionId, runId, steerId) {
4801
+ const db = await this.requireDb("archive.steer", sessionId);
4802
+ db.run(
4803
+ "INSERT OR IGNORE INTO session_approval_steers (session_id, run_id, steer_id) VALUES (?, ?, ?)",
4804
+ [sessionId, runId, steerId]
4805
+ );
4806
+ }
1977
4807
  async load(sessionId) {
1978
4808
  const db = await this.requireDb("load", sessionId);
1979
4809
  try {
@@ -2193,7 +5023,7 @@ var SessionStateStoreImpl = class {
2193
5023
  async listLegacySummaries() {
2194
5024
  let entries2;
2195
5025
  try {
2196
- entries2 = await fs7.readdir(this.legacyStateDir, {
5026
+ entries2 = await fs13.readdir(this.legacyStateDir, {
2197
5027
  withFileTypes: true,
2198
5028
  encoding: "utf8"
2199
5029
  });
@@ -2205,9 +5035,9 @@ var SessionStateStoreImpl = class {
2205
5035
  for (const entry of entries2) {
2206
5036
  if (!entry.isFile()) continue;
2207
5037
  if (!entry.name.endsWith(".json")) continue;
2208
- const filePath = path9.join(this.legacyStateDir, entry.name);
5038
+ const filePath = path15.join(this.legacyStateDir, entry.name);
2209
5039
  try {
2210
- const contents = await fs7.readFile(filePath, "utf8");
5040
+ const contents = await fs13.readFile(filePath, "utf8");
2211
5041
  const parsed = JSON.parse(contents);
2212
5042
  if (!parsed || typeof parsed !== "object") continue;
2213
5043
  if (!parsed.session_id || !parsed.updated_at) continue;
@@ -2277,18 +5107,18 @@ var RunEventStoreFactoryImpl = class {
2277
5107
 
2278
5108
  // src/run-log-retention.ts
2279
5109
  import {
2280
- promises as fs11,
5110
+ promises as fs17,
2281
5111
  linkSync,
2282
- lstatSync as lstatSync4,
5112
+ lstatSync as lstatSync6,
2283
5113
  renameSync as renameSync2,
2284
5114
  unlinkSync as unlinkSync3,
2285
5115
  utimesSync
2286
5116
  } from "fs";
2287
- import path12 from "path";
5117
+ import path18 from "path";
2288
5118
 
2289
5119
  // src/run-log-compression.ts
2290
- import { createHash as createHash4 } from "crypto";
2291
- import { createReadStream as createReadStream2, createWriteStream, promises as fs8 } from "fs";
5120
+ import { createHash as createHash5 } from "crypto";
5121
+ import { createReadStream as createReadStream2, createWriteStream, promises as fs14 } from "fs";
2292
5122
  import { Readable as Readable2, Transform } from "stream";
2293
5123
  import { pipeline } from "stream/promises";
2294
5124
  import { createGunzip as createGunzip2, createGzip } from "zlib";
@@ -2388,7 +5218,7 @@ async function* projectArchivedRunLog(file, usage) {
2388
5218
  // src/run-log-compression.ts
2389
5219
  async function prepareCompressedLog(file, usage) {
2390
5220
  const temporary = `${file}.${crypto.randomUUID()}.gz.tmp`;
2391
- const hash = createHash4("sha256");
5221
+ const hash = createHash5("sha256");
2392
5222
  let bytes = 0;
2393
5223
  try {
2394
5224
  await pipeline(
@@ -2404,7 +5234,7 @@ async function prepareCompressedLog(file, usage) {
2404
5234
  createWriteStream(temporary, { flags: "wx", mode: 384 })
2405
5235
  );
2406
5236
  const expected = hash.digest("hex");
2407
- const verification = createHash4("sha256");
5237
+ const verification = createHash5("sha256");
2408
5238
  let decoded = 0;
2409
5239
  await pipeline(
2410
5240
  createReadStream2(temporary),
@@ -2419,32 +5249,32 @@ async function prepareCompressedLog(file, usage) {
2419
5249
  );
2420
5250
  if (decoded !== bytes || verification.digest("hex") !== expected)
2421
5251
  throw new Error("Compressed run log verification failed");
2422
- const persisted = await fs8.open(temporary, "r+");
5252
+ const persisted = await fs14.open(temporary, "r+");
2423
5253
  try {
2424
5254
  await persisted.sync();
2425
5255
  } finally {
2426
5256
  await persisted.close();
2427
5257
  }
2428
- return { temporary, size: (await fs8.stat(temporary)).size };
5258
+ return { temporary, size: (await fs14.stat(temporary)).size };
2429
5259
  } catch (error) {
2430
- await fs8.rm(temporary, { force: true });
5260
+ await fs14.rm(temporary, { force: true });
2431
5261
  throw error;
2432
5262
  }
2433
5263
  }
2434
5264
 
2435
5265
  // src/run-log-files.ts
2436
5266
  import {
2437
- promises as fs9,
2438
- lstatSync as lstatSync3,
5267
+ promises as fs15,
5268
+ lstatSync as lstatSync5,
2439
5269
  readdirSync,
2440
- readFileSync as readFileSync2,
5270
+ readFileSync as readFileSync4,
2441
5271
  unlinkSync as unlinkSync2
2442
5272
  } from "fs";
2443
- import path10 from "path";
5273
+ import path16 from "path";
2444
5274
  var MAX_ACTIVE_RUN_MARKER_BYTES = 256;
2445
5275
  var isRegularDirectory = async (directory2) => {
2446
5276
  try {
2447
- return (await fs9.lstat(directory2)).isDirectory();
5277
+ return (await fs15.lstat(directory2)).isDirectory();
2448
5278
  } catch {
2449
5279
  return false;
2450
5280
  }
@@ -2470,9 +5300,9 @@ async function readHeader2(file) {
2470
5300
  }
2471
5301
  async function inspectCandidate(root, datePath, name, diagnostic) {
2472
5302
  const compressed = name.endsWith(".jsonl.gz");
2473
- const file = path10.join(root, datePath, name);
5303
+ const file = path16.join(root, datePath, name);
2474
5304
  try {
2475
- const stat = await fs9.lstat(file);
5305
+ const stat = await fs15.lstat(file);
2476
5306
  if (!stat.isFile()) return void 0;
2477
5307
  const header = await readHeader2(file);
2478
5308
  if (!header || name !== `${header.run_id}.jsonl${compressed ? ".gz" : ""}` || compressed && header.meta?.codelia_log_archive_version === RUN_LOG_ARCHIVE_VERSION)
@@ -2497,19 +5327,19 @@ async function inspectCandidate(root, datePath, name, diagnostic) {
2497
5327
  async function collectRunLogCandidates(root, diagnostic = false) {
2498
5328
  if (!await isRegularDirectory(root)) return [];
2499
5329
  const candidates = [];
2500
- for (const year of await fs9.readdir(root, { withFileTypes: true })) {
5330
+ for (const year of await fs15.readdir(root, { withFileTypes: true })) {
2501
5331
  if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
2502
- for (const month of await fs9.readdir(path10.join(root, year.name), {
5332
+ for (const month of await fs15.readdir(path16.join(root, year.name), {
2503
5333
  withFileTypes: true
2504
5334
  })) {
2505
5335
  if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
2506
- for (const day of await fs9.readdir(
2507
- path10.join(root, year.name, month.name),
5336
+ for (const day of await fs15.readdir(
5337
+ path16.join(root, year.name, month.name),
2508
5338
  { withFileTypes: true }
2509
5339
  )) {
2510
5340
  if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
2511
- const datePath = path10.join(year.name, month.name, day.name);
2512
- const entries2 = await fs9.readdir(path10.join(root, datePath), {
5341
+ const datePath = path16.join(year.name, month.name, day.name);
5342
+ const entries2 = await fs15.readdir(path16.join(root, datePath), {
2513
5343
  withFileTypes: true
2514
5344
  });
2515
5345
  const plain = new Set(
@@ -2541,10 +5371,10 @@ async function collectRunLogCandidatesAt(root, relPaths, diagnostic = false) {
2541
5371
  const name = parts.pop();
2542
5372
  if (!name?.endsWith(".jsonl") || parts.length !== 3 || !/^\d{4}$/.test(parts[0] ?? "") || !/^\d{2}$/.test(parts[1] ?? "") || !/^\d{2}$/.test(parts[2] ?? "") || name.includes("\\"))
2543
5373
  continue;
2544
- const datePath = path10.join(...parts);
5374
+ const datePath = path16.join(...parts);
2545
5375
  let selected = name;
2546
5376
  try {
2547
- await fs9.lstat(path10.join(root, datePath, name));
5377
+ await fs15.lstat(path16.join(root, datePath, name));
2548
5378
  } catch {
2549
5379
  if (diagnostic) continue;
2550
5380
  selected = `${name}.gz`;
@@ -2568,19 +5398,19 @@ async function removeReusedProcessMarkers(paths, sessionId, identify = (pid) =>
2568
5398
  return;
2569
5399
  }
2570
5400
  for (const entry of entries2) {
2571
- const file = path10.join(directory2, entry);
5401
+ const file = path16.join(directory2, entry);
2572
5402
  try {
2573
- const before = lstatSync3(file);
5403
+ const before = lstatSync5(file);
2574
5404
  if (!before.isFile() || before.size > MAX_ACTIVE_RUN_MARKER_BYTES)
2575
5405
  continue;
2576
- const contents = readFileSync2(file, "utf8");
5406
+ const contents = readFileSync4(file, "utf8");
2577
5407
  const { pid, identity } = JSON.parse(contents);
2578
5408
  if (!Number.isSafeInteger(pid) || pid < 1 || typeof identity !== "string" || !identity)
2579
5409
  continue;
2580
5410
  const current = await identify(pid);
2581
5411
  if (!current || current === identity) continue;
2582
- const after = lstatSync3(file);
2583
- if (after.isFile() && after.ino === before.ino && after.dev === before.dev && after.size === before.size && after.mtimeMs === before.mtimeMs && readFileSync2(file, "utf8") === contents)
5412
+ const after = lstatSync5(file);
5413
+ if (after.isFile() && after.ino === before.ino && after.dev === before.dev && after.size === before.size && after.mtimeMs === before.mtimeMs && readFileSync4(file, "utf8") === contents)
2584
5414
  unlinkSync2(file);
2585
5415
  } catch {
2586
5416
  }
@@ -2592,9 +5422,9 @@ function hasActiveRunWriter(paths, sessionId) {
2592
5422
  for (const entry of readdirSync(directory2, { withFileTypes: true })) {
2593
5423
  if (!entry.isFile()) return true;
2594
5424
  try {
2595
- const file = path10.join(directory2, entry.name);
2596
- if (lstatSync3(file).size > MAX_ACTIVE_RUN_MARKER_BYTES) return true;
2597
- const { pid } = JSON.parse(readFileSync2(file, "utf8"));
5425
+ const file = path16.join(directory2, entry.name);
5426
+ if (lstatSync5(file).size > MAX_ACTIVE_RUN_MARKER_BYTES) return true;
5427
+ const { pid } = JSON.parse(readFileSync4(file, "utf8"));
2598
5428
  if (!Number.isSafeInteger(pid) || pid < 1) return true;
2599
5429
  try {
2600
5430
  process.kill(pid, 0);
@@ -2613,8 +5443,8 @@ function hasActiveRunWriter(paths, sessionId) {
2613
5443
  }
2614
5444
 
2615
5445
  // src/run-log-usage.ts
2616
- import { promises as fs10 } from "fs";
2617
- import path11 from "path";
5446
+ import { promises as fs16 } from "fs";
5447
+ import path17 from "path";
2618
5448
 
2619
5449
  // src/run-log-request-model.ts
2620
5450
  var TOKENS = /["\\{}[\]:,]/g;
@@ -2761,7 +5591,7 @@ async function preserveRunUsage(paths, source) {
2761
5591
  const records = /* @__PURE__ */ new Map();
2762
5592
  const requestModels = /* @__PURE__ */ new Map();
2763
5593
  try {
2764
- const stat = await fs10.lstat(destination);
5594
+ const stat = await fs16.lstat(destination);
2765
5595
  if (!stat.isFile()) throw new Error("Invalid usage log");
2766
5596
  for await (const record2 of readUsageRecords(destination))
2767
5597
  if (record2.type === "llm.usage")
@@ -2802,15 +5632,15 @@ async function preserveRunUsage(paths, source) {
2802
5632
  name: record2.model?.name ?? source.model?.name
2803
5633
  })
2804
5634
  );
2805
- await fs10.mkdir(path11.dirname(destination), { recursive: true });
5635
+ await fs16.mkdir(path17.dirname(destination), { recursive: true });
2806
5636
  const temporary = `${destination}.${process.pid}.${crypto.randomUUID()}.tmp`;
2807
5637
  try {
2808
5638
  const lines = ordered.map((record2) => JSON.stringify(record2)).join("\n");
2809
- await fs10.writeFile(temporary, `${lines}
5639
+ await fs16.writeFile(temporary, `${lines}
2810
5640
  `, { mode: 384 });
2811
- await fs10.rename(temporary, destination);
5641
+ await fs16.rename(temporary, destination);
2812
5642
  } finally {
2813
- await fs10.rm(temporary, { force: true });
5643
+ await fs16.rm(temporary, { force: true });
2814
5644
  }
2815
5645
  return ordered;
2816
5646
  }
@@ -2825,7 +5655,7 @@ var eligible = (summary, newestMtime, now) => {
2825
5655
  };
2826
5656
  function commitCandidate(candidate, compressed, result) {
2827
5657
  try {
2828
- const stat = lstatSync4(candidate.file);
5658
+ const stat = lstatSync6(candidate.file);
2829
5659
  if (!stat.isFile() || stat.ino !== candidate.ino || stat.dev !== candidate.dev || stat.size !== candidate.size || stat.mtimeMs !== candidate.mtimeMs) {
2830
5660
  result.skipped++;
2831
5661
  return;
@@ -2863,7 +5693,7 @@ async function processCandidate(context, candidate, newestMtime, usage) {
2863
5693
  } catch {
2864
5694
  result.failed++;
2865
5695
  } finally {
2866
- if (compressed) await fs11.rm(compressed.temporary, { force: true });
5696
+ if (compressed) await fs17.rm(compressed.temporary, { force: true });
2867
5697
  }
2868
5698
  }
2869
5699
  async function cleanupRunLogs(options) {
@@ -2878,7 +5708,7 @@ async function cleanupRunLogs(options) {
2878
5708
  };
2879
5709
  const context = { paths, sessions, now, result };
2880
5710
  if (!await isRegularDirectory(paths.sessionsDir)) return result;
2881
- const diagnosticsDir = path12.join(paths.sessionsDir, "diagnostics");
5711
+ const diagnosticsDir = path18.join(paths.sessionsDir, "diagnostics");
2882
5712
  let relPaths;
2883
5713
  if (options.sessionId) {
2884
5714
  try {
@@ -2927,8 +5757,8 @@ async function cleanupRunLogs(options) {
2927
5757
  result.skipped += group.length - selected.length;
2928
5758
  if (selected.length === 0) continue;
2929
5759
  try {
2930
- const snapshot = await fs11.lstat(
2931
- path12.join(paths.sessionsDir, "messages", `${sessionId}.jsonl`)
5760
+ const snapshot = await fs17.lstat(
5761
+ path18.join(paths.sessionsDir, "messages", `${sessionId}.jsonl`)
2932
5762
  );
2933
5763
  if (!snapshot.isFile() || snapshot.size === 0) {
2934
5764
  result.skipped += selected.length;
@@ -2964,8 +5794,8 @@ var StoragePathServiceImpl = class {
2964
5794
  };
2965
5795
 
2966
5796
  // src/task-registry.ts
2967
- import { promises as fs12 } from "fs";
2968
- import path13 from "path";
5797
+ import { promises as fs18 } from "fs";
5798
+ import path19 from "path";
2969
5799
  var TASKS_DIRNAME = "tasks";
2970
5800
  var sortByUpdatedDesc = (tasks) => [...tasks].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
2971
5801
  var toShellKeyBase = (label2) => {
@@ -3023,14 +5853,14 @@ var assignMissingShellKeys = (tasks) => {
3023
5853
  return updates;
3024
5854
  };
3025
5855
  var atomicWrite = async (filePath, payload) => {
3026
- const dir = path13.dirname(filePath);
3027
- const base = path13.basename(filePath);
3028
- const tmp = path13.join(
5856
+ const dir = path19.dirname(filePath);
5857
+ const base = path19.basename(filePath);
5858
+ const tmp = path19.join(
3029
5859
  dir,
3030
5860
  `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
3031
5861
  );
3032
- await fs12.writeFile(tmp, payload, "utf8");
3033
- await fs12.rename(tmp, filePath);
5862
+ await fs18.writeFile(tmp, payload, "utf8");
5863
+ await fs18.rename(tmp, filePath);
3034
5864
  };
3035
5865
  var isTaskState = (value) => value === "queued" || value === "running" || value === "completed" || value === "failed" || value === "cancelled";
3036
5866
  var isTaskKind = (value) => value === "shell" || value === "subagent";
@@ -3141,7 +5971,7 @@ var normalizeTaskRecord = (value) => {
3141
5971
  };
3142
5972
  var readTaskFile = async (filePath) => {
3143
5973
  try {
3144
- const raw = await fs12.readFile(filePath, "utf8");
5974
+ const raw = await fs18.readFile(filePath, "utf8");
3145
5975
  return normalizeTaskRecord(JSON.parse(raw));
3146
5976
  } catch {
3147
5977
  return null;
@@ -3156,19 +5986,19 @@ var TaskRegistryStore = class {
3156
5986
  return;
3157
5987
  }
3158
5988
  const root = resolveStoragePaths().root;
3159
- this.tasksDir = path13.join(root, TASKS_DIRNAME);
5989
+ this.tasksDir = path19.join(root, TASKS_DIRNAME);
3160
5990
  }
3161
5991
  async ensureDir() {
3162
- await fs12.mkdir(this.tasksDir, { recursive: true });
5992
+ await fs18.mkdir(this.tasksDir, { recursive: true });
3163
5993
  }
3164
5994
  taskPath(taskId) {
3165
- return path13.join(this.tasksDir, taskFileName(taskId));
5995
+ return path19.join(this.tasksDir, taskFileName(taskId));
3166
5996
  }
3167
5997
  async list() {
3168
5998
  await this.ensureDir();
3169
- const entries2 = await fs12.readdir(this.tasksDir, { withFileTypes: true });
5999
+ const entries2 = await fs18.readdir(this.tasksDir, { withFileTypes: true });
3170
6000
  const tasks = (await Promise.all(
3171
- entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(path13.join(this.tasksDir, entry.name)))
6001
+ entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(path19.join(this.tasksDir, entry.name)))
3172
6002
  )).filter((task) => task !== null);
3173
6003
  const keyBackfills = assignMissingShellKeys(tasks);
3174
6004
  if (keyBackfills.length > 0) {
@@ -3210,8 +6040,8 @@ var TaskRegistryStore = class {
3210
6040
  };
3211
6041
 
3212
6042
  // src/tool-output-cache.ts
3213
- import { promises as fs13 } from "fs";
3214
- import path14 from "path";
6043
+ import { promises as fs19 } from "fs";
6044
+ import path20 from "path";
3215
6045
  var DEFAULT_MAX_MATCHES = 50;
3216
6046
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
3217
6047
  var DEFAULT_MAX_READ_BYTES = 64 * 1024;
@@ -3323,15 +6153,15 @@ var ToolOutputCacheStoreImpl = class {
3323
6153
  async save(record2) {
3324
6154
  const refId = normalizeRefId(record2.tool_call_id);
3325
6155
  const filePath = this.resolvePath(refId);
3326
- await fs13.mkdir(this.baseDir, { recursive: true });
3327
- await fs13.writeFile(filePath, record2.content, "utf8");
6156
+ await fs19.mkdir(this.baseDir, { recursive: true });
6157
+ await fs19.writeFile(filePath, record2.content, "utf8");
3328
6158
  const byteSize = Buffer.byteLength(record2.content, "utf8");
3329
6159
  const lineCount = record2.content.split(/\r?\n/).length;
3330
6160
  return { id: refId, byte_size: byteSize, line_count: lineCount };
3331
6161
  }
3332
6162
  async read(refId, options = {}) {
3333
6163
  const filePath = this.resolvePath(refId);
3334
- const content = await fs13.readFile(filePath, "utf8");
6164
+ const content = await fs19.readFile(filePath, "utf8");
3335
6165
  const lines = content.split(/\r?\n/);
3336
6166
  const offset = options.offset ?? 0;
3337
6167
  const limit = options.limit ?? lines.length;
@@ -3390,7 +6220,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
3390
6220
  }
3391
6221
  async readTail(refId, options) {
3392
6222
  const filePath = this.resolvePath(refId);
3393
- const content = await fs13.readFile(filePath, "utf8");
6223
+ const content = await fs19.readFile(filePath, "utf8");
3394
6224
  const lines = content.split(/\r?\n/);
3395
6225
  const tailLines = Math.max(1, Math.trunc(options.tail_lines));
3396
6226
  const start = Math.max(0, lines.length - tailLines);
@@ -3402,7 +6232,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
3402
6232
  }
3403
6233
  async readLine(refId, options) {
3404
6234
  const filePath = this.resolvePath(refId);
3405
- const content = await fs13.readFile(filePath, "utf8");
6235
+ const content = await fs19.readFile(filePath, "utf8");
3406
6236
  const lines = content.split(/\r?\n/);
3407
6237
  const lineIndex = options.line_number - 1;
3408
6238
  if (lineIndex < 0 || lineIndex >= lines.length) {
@@ -3443,7 +6273,7 @@ tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${opti
3443
6273
  }
3444
6274
  async grep(refId, options) {
3445
6275
  const filePath = this.resolvePath(refId);
3446
- const content = await fs13.readFile(filePath, "utf8");
6276
+ const content = await fs19.readFile(filePath, "utf8");
3447
6277
  const lines = content.split(/\r?\n/);
3448
6278
  const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
3449
6279
  const before = Math.max(0, options.before ?? 0);
@@ -3494,13 +6324,23 @@ ${snippet}`;
3494
6324
  return output;
3495
6325
  }
3496
6326
  resolvePath(refId) {
3497
- return path14.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
6327
+ return path20.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
3498
6328
  }
3499
6329
  };
3500
6330
  export {
6331
+ AUTH_VERSION_V1,
6332
+ AUTH_VERSION_V2,
6333
+ CODELIA_AUTH_KEYCHAIN_SERVICE,
6334
+ CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
6335
+ CredentialConflictError,
6336
+ DEFAULT_AUTH_LOCK_TIMEOUT_MS,
6337
+ DEFAULT_OAUTH_REFRESH_TIMEOUT_MS,
3501
6338
  FileAttachmentStore,
3502
6339
  IMAGE_MAX_BYTES,
3503
6340
  ImageArtifactStore,
6341
+ KeychainError,
6342
+ MCP_AUTH_VERSION,
6343
+ MacOsKeychainClient,
3504
6344
  McpAuthStore,
3505
6345
  ProjectsPolicyStore,
3506
6346
  RUN_LOG_RETENTION_MS,
@@ -3511,17 +6351,57 @@ export {
3511
6351
  StoragePathServiceImpl,
3512
6352
  TaskRegistryStore,
3513
6353
  ToolOutputCacheStoreImpl,
6354
+ authLockPathFor,
6355
+ buildMcpAuthBinding,
6356
+ canonicalJsonEqual,
6357
+ canonicalJsonStringify,
6358
+ canonicalPathOrResolvedSync,
6359
+ canonicalizeMcpUri,
3514
6360
  cleanupRunLogs,
6361
+ clearStoreAcrossAllLocationsUnlocked,
6362
+ coordinateCredentialBackend,
6363
+ coordinateCredentialBackendUnlocked,
3515
6364
  createAttachmentId,
6365
+ deriveMcpIssuer,
3516
6366
  detectImageAttachmentType,
6367
+ enforceWindowsOwnerOnlyDacl,
6368
+ ensureCredentialsDirectory,
3517
6369
  ensureStorageDirs,
3518
6370
  getProcessIdentity,
6371
+ inspectCredentialStorageStatus,
3519
6372
  isAttachmentId,
6373
+ isCanonicalHomeWorkspaceSync,
6374
+ isSameConfigFilePath,
6375
+ isTrustedGlobalConfigLocationSync,
6376
+ isWithinPath,
6377
+ keychainAccountForConfigDir,
6378
+ mcpAuthBindingMatches,
6379
+ mcpAuthStoreAdapter,
6380
+ openSqlite,
6381
+ parseAuthDocument,
6382
+ parseAuthStorageState,
6383
+ parseMcpAuthDocument,
6384
+ providerAuthStoreAdapter,
6385
+ readAuthStorageState,
6386
+ readAuthStorageStateSync,
3520
6387
  readRunLogLines,
6388
+ resolveConfiguredAuthStorageMode,
6389
+ resolveCredentialConflict,
3521
6390
  resolveIndexedRunLog,
3522
6391
  resolveRunLogPath,
3523
6392
  resolveStoragePaths,
6393
+ resolveWindowsSystem32Dir,
6394
+ runTwoPhaseMigration,
3524
6395
  scanSessionRunLogs,
3525
6396
  validateImageAttachment,
3526
- validateImagePng
6397
+ validateImagePng,
6398
+ verifyOwnedAncestors,
6399
+ verifyOwnedAncestorsSync,
6400
+ verifyUserStorageLocation,
6401
+ verifyUserStorageLocationSync,
6402
+ verifyWindowsCredentialFileAcl,
6403
+ verifyWindowsCredentialFileAclSync,
6404
+ withAuthStoreLock,
6405
+ writeAuthStorageState,
6406
+ writeFileAtomic
3527
6407
  };