@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.cjs CHANGED
@@ -30,9 +30,19 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ AUTH_VERSION_V1: () => AUTH_VERSION_V1,
34
+ AUTH_VERSION_V2: () => AUTH_VERSION_V2,
35
+ CODELIA_AUTH_KEYCHAIN_SERVICE: () => CODELIA_AUTH_KEYCHAIN_SERVICE,
36
+ CODELIA_MCP_AUTH_KEYCHAIN_SERVICE: () => CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
37
+ CredentialConflictError: () => CredentialConflictError,
38
+ DEFAULT_AUTH_LOCK_TIMEOUT_MS: () => DEFAULT_AUTH_LOCK_TIMEOUT_MS,
39
+ DEFAULT_OAUTH_REFRESH_TIMEOUT_MS: () => DEFAULT_OAUTH_REFRESH_TIMEOUT_MS,
33
40
  FileAttachmentStore: () => FileAttachmentStore,
34
41
  IMAGE_MAX_BYTES: () => IMAGE_MAX_BYTES,
35
42
  ImageArtifactStore: () => ImageArtifactStore,
43
+ KeychainError: () => KeychainError,
44
+ MCP_AUTH_VERSION: () => MCP_AUTH_VERSION,
45
+ MacOsKeychainClient: () => MacOsKeychainClient,
36
46
  McpAuthStore: () => McpAuthStore,
37
47
  ProjectsPolicyStore: () => ProjectsPolicyStore,
38
48
  RUN_LOG_RETENTION_MS: () => RUN_LOG_RETENTION_MS,
@@ -43,37 +53,111 @@ __export(index_exports, {
43
53
  StoragePathServiceImpl: () => StoragePathServiceImpl,
44
54
  TaskRegistryStore: () => TaskRegistryStore,
45
55
  ToolOutputCacheStoreImpl: () => ToolOutputCacheStoreImpl,
56
+ authLockPathFor: () => authLockPathFor,
57
+ buildMcpAuthBinding: () => buildMcpAuthBinding,
58
+ canonicalJsonEqual: () => canonicalJsonEqual,
59
+ canonicalJsonStringify: () => canonicalJsonStringify,
60
+ canonicalPathOrResolvedSync: () => canonicalPathOrResolvedSync,
61
+ canonicalizeMcpUri: () => canonicalizeMcpUri,
46
62
  cleanupRunLogs: () => cleanupRunLogs,
63
+ clearStoreAcrossAllLocationsUnlocked: () => clearStoreAcrossAllLocationsUnlocked,
64
+ coordinateCredentialBackend: () => coordinateCredentialBackend,
65
+ coordinateCredentialBackendUnlocked: () => coordinateCredentialBackendUnlocked,
47
66
  createAttachmentId: () => createAttachmentId,
67
+ deriveMcpIssuer: () => deriveMcpIssuer,
48
68
  detectImageAttachmentType: () => detectImageAttachmentType,
69
+ enforceWindowsOwnerOnlyDacl: () => enforceWindowsOwnerOnlyDacl,
70
+ ensureCredentialsDirectory: () => ensureCredentialsDirectory,
49
71
  ensureStorageDirs: () => ensureStorageDirs,
50
72
  getProcessIdentity: () => getProcessIdentity,
73
+ inspectCredentialStorageStatus: () => inspectCredentialStorageStatus,
51
74
  isAttachmentId: () => isAttachmentId,
75
+ isCanonicalHomeWorkspaceSync: () => isCanonicalHomeWorkspaceSync,
76
+ isSameConfigFilePath: () => isSameConfigFilePath,
77
+ isTrustedGlobalConfigLocationSync: () => isTrustedGlobalConfigLocationSync,
78
+ isWithinPath: () => isWithinPath,
79
+ keychainAccountForConfigDir: () => keychainAccountForConfigDir,
80
+ mcpAuthBindingMatches: () => mcpAuthBindingMatches,
81
+ mcpAuthStoreAdapter: () => mcpAuthStoreAdapter,
82
+ openSqlite: () => openSqlite,
83
+ parseAuthDocument: () => parseAuthDocument,
84
+ parseAuthStorageState: () => parseAuthStorageState,
85
+ parseMcpAuthDocument: () => parseMcpAuthDocument,
86
+ providerAuthStoreAdapter: () => providerAuthStoreAdapter,
87
+ readAuthStorageState: () => readAuthStorageState,
88
+ readAuthStorageStateSync: () => readAuthStorageStateSync,
52
89
  readRunLogLines: () => readRunLogLines,
90
+ resolveConfiguredAuthStorageMode: () => resolveConfiguredAuthStorageMode,
91
+ resolveCredentialConflict: () => resolveCredentialConflict,
53
92
  resolveIndexedRunLog: () => resolveIndexedRunLog,
54
93
  resolveRunLogPath: () => resolveRunLogPath,
55
94
  resolveStoragePaths: () => resolveStoragePaths,
95
+ resolveWindowsSystem32Dir: () => resolveWindowsSystem32Dir,
96
+ runTwoPhaseMigration: () => runTwoPhaseMigration,
56
97
  scanSessionRunLogs: () => scanSessionRunLogs,
57
98
  validateImageAttachment: () => validateImageAttachment,
58
- validateImagePng: () => validateImagePng
99
+ validateImagePng: () => validateImagePng,
100
+ verifyOwnedAncestors: () => verifyOwnedAncestors,
101
+ verifyOwnedAncestorsSync: () => verifyOwnedAncestorsSync,
102
+ verifyUserStorageLocation: () => verifyUserStorageLocation,
103
+ verifyUserStorageLocationSync: () => verifyUserStorageLocationSync,
104
+ verifyWindowsCredentialFileAcl: () => verifyWindowsCredentialFileAcl,
105
+ verifyWindowsCredentialFileAclSync: () => verifyWindowsCredentialFileAclSync,
106
+ withAuthStoreLock: () => withAuthStoreLock,
107
+ writeAuthStorageState: () => writeAuthStorageState,
108
+ writeFileAtomic: () => writeFileAtomic
59
109
  });
60
110
  module.exports = __toCommonJS(index_exports);
61
111
 
112
+ // src/atomic-file.ts
113
+ var import_node_crypto = require("crypto");
114
+ var import_node_fs = require("fs");
115
+ var import_node_path = __toESM(require("path"), 1);
116
+ var writeFileAtomic = async (targetPath, data, options = {}) => {
117
+ const mode = options.mode ?? 384;
118
+ const dir = import_node_path.default.dirname(targetPath);
119
+ const base = import_node_path.default.basename(targetPath);
120
+ const temporary = import_node_path.default.join(dir, `.${base}.${(0, import_node_crypto.randomUUID)()}.tmp`);
121
+ let handle;
122
+ try {
123
+ handle = await import_node_fs.promises.open(temporary, "wx", mode);
124
+ await handle.writeFile(data, "utf8");
125
+ await handle.sync();
126
+ await handle.close();
127
+ handle = void 0;
128
+ try {
129
+ await import_node_fs.promises.chmod(temporary, mode);
130
+ } catch {
131
+ }
132
+ await import_node_fs.promises.rename(temporary, targetPath);
133
+ try {
134
+ await import_node_fs.promises.chmod(targetPath, mode);
135
+ } catch {
136
+ }
137
+ } catch (error) {
138
+ if (handle) {
139
+ await handle.close().catch(() => void 0);
140
+ }
141
+ await import_node_fs.promises.unlink(temporary).catch(() => void 0);
142
+ throw error;
143
+ }
144
+ };
145
+
62
146
  // src/attachments.ts
63
- var import_node_crypto2 = require("crypto");
64
- var import_node_fs2 = require("fs");
147
+ var import_node_crypto3 = require("crypto");
148
+ var import_node_fs3 = require("fs");
65
149
  var import_promises2 = require("fs/promises");
66
- var import_node_path = __toESM(require("path"), 1);
150
+ var import_node_path2 = __toESM(require("path"), 1);
67
151
 
68
152
  // src/image-files.ts
69
- var import_node_crypto = require("crypto");
70
- var import_node_fs = require("fs");
153
+ var import_node_crypto2 = require("crypto");
154
+ var import_node_fs2 = require("fs");
71
155
  var import_promises = require("fs/promises");
72
- var imageHash = (bytes) => (0, import_node_crypto.createHash)("sha256").update(bytes).digest("hex");
156
+ var imageHash = (bytes) => (0, import_node_crypto2.createHash)("sha256").update(bytes).digest("hex");
73
157
  async function readImageFileBounded(file, limit) {
74
158
  const handle = await (0, import_promises.open)(
75
159
  file,
76
- import_node_fs.constants.O_RDONLY | (import_node_fs.constants.O_NOFOLLOW ?? 0) | (import_node_fs.constants.O_NONBLOCK ?? 0)
160
+ import_node_fs2.constants.O_RDONLY | (import_node_fs2.constants.O_NOFOLLOW ?? 0) | (import_node_fs2.constants.O_NONBLOCK ?? 0)
77
161
  );
78
162
  try {
79
163
  const stat = await handle.stat();
@@ -104,8 +188,8 @@ var UUID = /^[0-9a-f-]{36}$/;
104
188
  var SHA256 = /^[0-9a-f]{64}$/;
105
189
  var MAX_BYTES = 32 * 1024 * 1024;
106
190
  var BLOCK_BYTES = 64 * 1024;
107
- var digest = (bytes) => (0, import_node_crypto2.createHash)("sha256").update(bytes).digest("hex");
108
- var createAttachmentId = () => `codelia-attachment-${(0, import_node_crypto2.randomUUID)()}`;
191
+ var digest = (bytes) => (0, import_node_crypto3.createHash)("sha256").update(bytes).digest("hex");
192
+ var createAttachmentId = () => `codelia-attachment-${(0, import_node_crypto3.randomUUID)()}`;
109
193
  var isAttachmentId = (id2) => ID.test(id2);
110
194
  var FileAttachmentStore = class {
111
195
  constructor(root, images) {
@@ -117,9 +201,9 @@ var FileAttachmentStore = class {
117
201
  resolveImage = (ref) => this.images.resolve(ref);
118
202
  async commit(sessionId, entries2) {
119
203
  if (!entries2.length) return;
120
- const batch = (0, import_node_crypto2.randomUUID)();
121
- const marker = import_node_path.default.join(this.root, "committed", batch);
122
- await (0, import_promises2.mkdir)(import_node_path.default.join(this.root, "committed"), {
204
+ const batch = (0, import_node_crypto3.randomUUID)();
205
+ const marker = import_node_path2.default.join(this.root, "committed", batch);
206
+ await (0, import_promises2.mkdir)(import_node_path2.default.join(this.root, "committed"), {
123
207
  recursive: true,
124
208
  mode: 448
125
209
  });
@@ -131,7 +215,7 @@ var FileAttachmentStore = class {
131
215
  if (!isAttachmentId(ref.attachment_id) || bytes.length !== ref.byte_size || bytes.length > MAX_BYTES || digest(bytes) !== ref.sha256) {
132
216
  throw new Error("Invalid attachment original");
133
217
  }
134
- const dir = import_node_path.default.join(this.root, ref.attachment_id);
218
+ const dir = import_node_path2.default.join(this.root, ref.attachment_id);
135
219
  await (0, import_promises2.mkdir)(dir, { mode: 448 });
136
220
  created.push(dir);
137
221
  const metadata = { ...record2, sessionId, batch };
@@ -148,13 +232,13 @@ var FileAttachmentStore = class {
148
232
  digest(bytes.subarray(offset, offset + BLOCK_BYTES))
149
233
  );
150
234
  }
151
- await (0, import_promises2.writeFile)(import_node_path.default.join(dir, "original"), bytes, {
235
+ await (0, import_promises2.writeFile)(import_node_path2.default.join(dir, "original"), bytes, {
152
236
  flag: "wx",
153
237
  mode: 384
154
238
  });
155
239
  }
156
240
  await (0, import_promises2.writeFile)(
157
- import_node_path.default.join(dir, "metadata.json"),
241
+ import_node_path2.default.join(dir, "metadata.json"),
158
242
  JSON.stringify(metadata),
159
243
  { flag: "wx", mode: 384 }
160
244
  );
@@ -180,114 +264,2231 @@ var FileAttachmentStore = class {
180
264
  await this.readImage(metadata);
181
265
  } else {
182
266
  const bytes = await readImageFileBounded(
183
- import_node_path.default.join(this.root, attachmentId, "original"),
267
+ import_node_path2.default.join(this.root, attachmentId, "original"),
184
268
  ref.byte_size
185
269
  );
186
- if (bytes.length !== ref.byte_size || digest(bytes) !== ref.sha256)
187
- throw new Error("Attachment original is corrupt");
270
+ if (bytes.length !== ref.byte_size || digest(bytes) !== ref.sha256)
271
+ throw new Error("Attachment original is corrupt");
272
+ }
273
+ return { ref, ...imageRef ? { imageRef } : {} };
274
+ }
275
+ async read(attachmentId, sessionId, offset, length) {
276
+ const metadata = await this.metadata(attachmentId, sessionId);
277
+ if (!metadata) throw new Error("Attachment unavailable in this session");
278
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || length > 256 * 1024)
279
+ throw new Error("Invalid attachment byte range");
280
+ const end = Math.min(offset + length, metadata.ref.byte_size);
281
+ if (metadata.imageRef)
282
+ return (await this.readImage(metadata)).subarray(offset, end);
283
+ const file = await (0, import_promises2.open)(
284
+ import_node_path2.default.join(this.root, attachmentId, "original"),
285
+ import_node_fs3.constants.O_RDONLY | (import_node_fs3.constants.O_NOFOLLOW ?? 0) | (import_node_fs3.constants.O_NONBLOCK ?? 0)
286
+ );
287
+ try {
288
+ const stat = await file.stat();
289
+ if (!stat.isFile() || stat.size !== metadata.ref.byte_size)
290
+ throw new Error("Attachment original is corrupt");
291
+ if (offset >= end) return Buffer.alloc(0);
292
+ const firstBlock = Math.floor(offset / BLOCK_BYTES);
293
+ const lastBlock = Math.ceil(end / BLOCK_BYTES);
294
+ const start = firstBlock * BLOCK_BYTES;
295
+ const bytes = Buffer.alloc(
296
+ Math.min(lastBlock * BLOCK_BYTES, stat.size) - start
297
+ );
298
+ let count = 0;
299
+ while (count < bytes.length) {
300
+ const result = await file.read(
301
+ bytes,
302
+ count,
303
+ bytes.length - count,
304
+ start + count
305
+ );
306
+ if (!result.bytesRead)
307
+ throw new Error("Attachment original is corrupt");
308
+ count += result.bytesRead;
309
+ }
310
+ for (let block = firstBlock; block < lastBlock; block++) {
311
+ const beg = (block - firstBlock) * BLOCK_BYTES;
312
+ if (metadata.blocks?.[block] !== digest(bytes.subarray(beg, beg + BLOCK_BYTES))) {
313
+ throw new Error("Attachment original is corrupt");
314
+ }
315
+ }
316
+ return bytes.subarray(offset - start, end - start);
317
+ } finally {
318
+ await file.close();
319
+ }
320
+ }
321
+ async metadata(attachmentId, sessionId) {
322
+ if (!isAttachmentId(attachmentId)) return null;
323
+ const dir = import_node_path2.default.join(this.root, attachmentId);
324
+ try {
325
+ if (!(await (0, import_promises2.lstat)(dir)).isDirectory()) return null;
326
+ const metadata = JSON.parse(
327
+ (await readImageFileBounded(import_node_path2.default.join(dir, "metadata.json"), 64 * 1024)).toString()
328
+ );
329
+ const { ref, imageRef, blocks } = metadata;
330
+ if (metadata.sessionId !== sessionId || !UUID.test(metadata.batch) || ref?.attachment_id !== attachmentId)
331
+ return null;
332
+ 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")
333
+ throw new Error("Invalid attachment metadata");
334
+ if (!imageRef && (!Array.isArray(blocks) || blocks.length !== Math.ceil(ref.byte_size / BLOCK_BYTES)))
335
+ throw new Error("Invalid attachment block index");
336
+ const marker = import_node_path2.default.join(this.root, "committed", metadata.batch);
337
+ return (await (0, import_promises2.lstat)(marker)).isFile() ? metadata : null;
338
+ } catch (error) {
339
+ if (error.code === "ENOENT") return null;
340
+ throw error;
341
+ }
342
+ }
343
+ async readImage({
344
+ ref,
345
+ imageRef,
346
+ sessionId
347
+ }) {
348
+ 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)
349
+ throw new Error("Invalid image attachment reference");
350
+ const { metadata, bytes } = await this.images.read(
351
+ imageRef.artifact_id,
352
+ sessionId
353
+ );
354
+ 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)
355
+ throw new Error("Image attachment original is corrupt");
356
+ return bytes;
357
+ }
358
+ };
359
+
360
+ // src/auth-lock.ts
361
+ var import_node_crypto4 = require("crypto");
362
+ var import_node_fs5 = require("fs");
363
+ var import_node_path4 = __toESM(require("path"), 1);
364
+ var import_promises3 = require("timers/promises");
365
+
366
+ // src/sqlite.ts
367
+ var openSqlite = async (filename) => {
368
+ if (process.versions.bun) {
369
+ const bunSqliteSpecifier = "bun:sqlite";
370
+ const { Database } = await import(bunSqliteSpecifier);
371
+ const db2 = new Database(filename, { create: true });
372
+ return {
373
+ close: () => db2.close(),
374
+ exec: (sql) => {
375
+ db2.exec(sql);
376
+ },
377
+ run: (sql, params = []) => {
378
+ db2.query(sql).run(...params);
379
+ },
380
+ get: (sql, params = []) => {
381
+ const row = db2.query(sql).get(...params);
382
+ return row ?? void 0;
383
+ },
384
+ all: (sql, params = []) => db2.query(sql).all(...params)
385
+ };
386
+ }
387
+ const betterSqliteSpecifier = "better-sqlite3";
388
+ const betterSqliteModule = await import(betterSqliteSpecifier);
389
+ const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
390
+ const db = new BetterSqlite3(filename);
391
+ return {
392
+ close: () => db.close(),
393
+ exec: (sql) => {
394
+ db.exec(sql);
395
+ },
396
+ run: (sql, params = []) => {
397
+ db.prepare(sql).run(...params);
398
+ },
399
+ get: (sql, params = []) => {
400
+ const row = db.prepare(sql).get(...params);
401
+ return row ?? void 0;
402
+ },
403
+ all: (sql, params = []) => db.prepare(sql).all(...params)
404
+ };
405
+ };
406
+
407
+ // src/windows-acl.ts
408
+ var import_node_child_process = require("child_process");
409
+ var import_node_fs4 = require("fs");
410
+ var import_node_path3 = __toESM(require("path"), 1);
411
+ var import_node_util = require("util");
412
+ var execFileAsync = (0, import_node_util.promisify)(import_node_child_process.execFile);
413
+ var resolveWindowsSystem32Dir = (env = process.env) => {
414
+ const root = (env.SystemRoot ?? env.WINDIR ?? "").trim() || "C:\\Windows";
415
+ if (!/^[A-Za-z]:\\/u.test(root) || root.includes("..")) {
416
+ throw new Error("unsafe_windows_credentials_acl: invalid_system_root");
417
+ }
418
+ return import_node_path3.default.win32.join(root, "System32");
419
+ };
420
+ var execOptions = {
421
+ windowsHide: true,
422
+ timeout: 5e3,
423
+ maxBuffer: 32 * 1024
424
+ };
425
+ var defaultRunner = async (exe, args, options) => execFileAsync(exe, [...args], { ...options, ...execOptions });
426
+ var aclScript = `
427
+ $ErrorActionPreference = 'Stop'
428
+ $target = $env:CODELIA_ACL_TARGET
429
+ $operation = $env:CODELIA_ACL_OPERATION
430
+ $legacy = $operation -eq 'legacy_file'
431
+ $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User
432
+ $system = [System.Security.Principal.SecurityIdentifier]::new('S-1-5-18')
433
+ $administrators = 'S-1-5-32-544'
434
+ $sections = [System.Security.AccessControl.AccessControlSections]'Owner, Access'
435
+ $inherit = [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
436
+ $inheritAces = [System.Security.AccessControl.AceFlags]'ContainerInherit, ObjectInherit'
437
+ $full = [System.Security.AccessControl.FileSystemRights]::FullControl
438
+ # Include generic read and execute if Windows left the generic bits unmapped.
439
+ $legacyReadMask = (
440
+ [int][System.Security.AccessControl.FileSystemRights]::ReadAndExecute -bor
441
+ [int][System.Security.AccessControl.FileSystemRights]::Synchronize -bor
442
+ [int]::MinValue -bor 0x20000000
443
+ )
444
+
445
+ function Get-TargetType([string]$file, [bool]$directory) {
446
+ try {
447
+ $attributes = [System.IO.File]::GetAttributes($file)
448
+ } catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] {
449
+ return 'missing'
450
+ }
451
+ if ($attributes -band [System.IO.FileAttributes]::ReparsePoint) { return 'reparse_point' }
452
+ if ([bool]($attributes -band [System.IO.FileAttributes]::Directory) -ne $directory) {
453
+ return 'unexpected_target_type'
454
+ }
455
+ return 'ok'
456
+ }
457
+
458
+ function Test-CredentialAcl($acl, [bool]$directory) {
459
+ $descriptor = [System.Security.AccessControl.RawSecurityDescriptor]::new(
460
+ $acl.GetSecurityDescriptorBinaryForm(), 0)
461
+ if ($descriptor.Owner.Value -ne $user.Value) { return 'owner_mismatch' }
462
+ if ($null -eq $descriptor.DiscretionaryAcl) { return 'null_dacl' }
463
+ if ($directory -and -not $acl.AreAccessRulesProtected) { return 'unprotected_dacl' }
464
+ $hasUser = $false
465
+ foreach ($ace in $descriptor.DiscretionaryAcl) {
466
+ if ($legacy -and ($ace.AceType -eq [System.Security.AccessControl.AceType]::AccessDenied -or
467
+ $ace.AceFlags.HasFlag([System.Security.AccessControl.AceFlags]::InheritOnly))) { continue }
468
+ if ($ace.AceType -ne [System.Security.AccessControl.AceType]::AccessAllowed) {
469
+ return 'unexpected_ace_type'
470
+ }
471
+ $sid = $ace.SecurityIdentifier.Value
472
+ if ($legacy) {
473
+ # The old config root may have inherited Administrators and read grants.
474
+ if ($sid -ne $user.Value -and $sid -ne $system.Value -and $sid -ne $administrators -and
475
+ ($ace.AccessMask -band (-bnot $legacyReadMask))) { return 'legacy_write_grant' }
476
+ continue
477
+ }
478
+ if ($sid -ne $user.Value -and $sid -ne $system.Value) { return 'unexpected_principals' }
479
+ if ($directory -and ($ace.AccessMask -ne [int]$full -or $ace.AceFlags -ne $inheritAces)) {
480
+ return 'unexpected_directory_ace'
481
+ }
482
+ if ($sid -eq $user.Value) { $hasUser = $true }
483
+ }
484
+ if (-not $legacy -and -not $hasUser) { return 'missing_user_grant' }
485
+ return 'ok'
486
+ }
487
+
488
+ if ($operation -eq 'ensure_directory') {
489
+ $targetType = Get-TargetType $target $true
490
+ if ($targetType -ne 'ok') { $targetType; exit }
491
+ $acl = [System.IO.Directory]::GetAccessControl($target, $sections)
492
+ $result = Test-CredentialAcl $acl $true
493
+ if ($result -eq 'ok' -or $result -eq 'owner_mismatch') { $result; exit }
494
+
495
+ $privateAcl = [System.Security.AccessControl.DirectorySecurity]::new()
496
+ $privateAcl.SetAccessRuleProtection($true, $false)
497
+ $propagate = [System.Security.AccessControl.PropagationFlags]::None
498
+ $allow = [System.Security.AccessControl.AccessControlType]::Allow
499
+ $privateAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new(
500
+ $user, $full, $inherit, $propagate, $allow))
501
+ if ($user.Value -ne $system.Value) {
502
+ $privateAcl.AddAccessRule([System.Security.AccessControl.FileSystemAccessRule]::new(
503
+ $system, $full, $inherit, $propagate, $allow))
504
+ }
505
+ [System.IO.Directory]::SetAccessControl($target, $privateAcl)
506
+ $targetType = Get-TargetType $target $true
507
+ if ($targetType -ne 'ok') { $targetType; exit }
508
+ Test-CredentialAcl ([System.IO.Directory]::GetAccessControl($target, $sections)) $true
509
+ exit
510
+ }
511
+
512
+ if ($operation -eq 'file') {
513
+ $parent = [System.IO.Path]::GetDirectoryName($target)
514
+ $parentType = Get-TargetType $parent $true
515
+ if ($parentType -ne 'ok') { $parentType; exit }
516
+ $parentAcl = Test-CredentialAcl ([System.IO.Directory]::GetAccessControl($parent, $sections)) $true
517
+ if ($parentAcl -ne 'ok') { $parentAcl; exit }
518
+ }
519
+ try {
520
+ $targetType = Get-TargetType $target $false
521
+ if ($targetType -ne 'ok') { $targetType; exit }
522
+ Test-CredentialAcl ([System.IO.File]::GetAccessControl($target, $sections)) $false
523
+ } catch [System.IO.FileNotFoundException], [System.IO.DirectoryNotFoundException] {
524
+ 'missing'
525
+ }
526
+ `;
527
+ var encodedAclScript = Buffer.from(aclScript, "utf16le").toString("base64");
528
+ function aclCommand(target, operation, env) {
529
+ const system32 = resolveWindowsSystem32Dir(env);
530
+ return {
531
+ exe: import_node_path3.default.win32.join(
532
+ system32,
533
+ "WindowsPowerShell",
534
+ "v1.0",
535
+ "powershell.exe"
536
+ ),
537
+ args: [
538
+ "-NoProfile",
539
+ "-NonInteractive",
540
+ "-EncodedCommand",
541
+ encodedAclScript
542
+ ],
543
+ options: {
544
+ cwd: system32,
545
+ env: {
546
+ ...env,
547
+ CODELIA_ACL_TARGET: import_node_path3.default.win32.resolve(target),
548
+ CODELIA_ACL_OPERATION: operation
549
+ }
550
+ }
551
+ };
552
+ }
553
+ var aclFailures = /* @__PURE__ */ new Set([
554
+ "missing",
555
+ "owner_mismatch",
556
+ "reparse_point",
557
+ "unexpected_target_type",
558
+ "null_dacl",
559
+ "unprotected_dacl",
560
+ "unexpected_ace_type",
561
+ "unexpected_principals",
562
+ "legacy_write_grant",
563
+ "unexpected_directory_ace",
564
+ "missing_user_grant"
565
+ ]);
566
+ function verifyAclResult(stdout, operation) {
567
+ const result = stdout.trim();
568
+ if (result === "ok") return true;
569
+ if (operation !== "ensure_directory" && result === "missing") return false;
570
+ const reason = aclFailures.has(result) ? result : "invalid_probe_result";
571
+ throw new Error(`unsafe_windows_credentials_acl: ${reason}`);
572
+ }
573
+ async function runAclCommand(target, operation, runner, env) {
574
+ const { exe, args, options } = aclCommand(target, operation, env);
575
+ let stdout;
576
+ try {
577
+ ({ stdout } = await runner(exe, args, options));
578
+ } catch {
579
+ throw new Error("unsafe_windows_credentials_acl: acl_probe_failed");
580
+ }
581
+ return verifyAclResult(stdout, operation);
582
+ }
583
+ var enforceWindowsOwnerOnlyDacl = async (dirPath, runner = defaultRunner, env = process.env) => {
584
+ await runAclCommand(dirPath, "ensure_directory", runner, env);
585
+ };
586
+ var isMissing = (error) => error?.code === "ENOENT";
587
+ var verifyWindowsCredentialFileAcl = async (filePath, legacy = false) => {
588
+ if (process.platform !== "win32") return true;
589
+ try {
590
+ await import_node_fs4.promises.lstat(filePath);
591
+ } catch (error) {
592
+ if (isMissing(error)) return false;
593
+ throw error;
594
+ }
595
+ return runAclCommand(
596
+ filePath,
597
+ legacy ? "legacy_file" : "file",
598
+ defaultRunner,
599
+ process.env
600
+ );
601
+ };
602
+ var verifyWindowsCredentialFileAclSync = (filePath, legacy = false) => {
603
+ if (process.platform !== "win32") return true;
604
+ try {
605
+ (0, import_node_fs4.lstatSync)(filePath);
606
+ } catch (error) {
607
+ if (isMissing(error)) return false;
608
+ throw error;
609
+ }
610
+ const operation = legacy ? "legacy_file" : "file";
611
+ const { exe, args, options } = aclCommand(filePath, operation, process.env);
612
+ let stdout;
613
+ try {
614
+ stdout = (0, import_node_child_process.execFileSync)(exe, args, {
615
+ ...options,
616
+ ...execOptions,
617
+ encoding: "utf8",
618
+ stdio: ["ignore", "pipe", "pipe"]
619
+ });
620
+ } catch {
621
+ throw new Error("unsafe_windows_credentials_acl: acl_probe_failed");
622
+ }
623
+ return verifyAclResult(stdout, operation);
624
+ };
625
+ var ensureCredentialsDirectory = async (credentialsDir, options) => {
626
+ const platform = options?.platform ?? process.platform;
627
+ await import_node_fs4.promises.mkdir(credentialsDir, { recursive: true, mode: 448 });
628
+ if (platform === "win32") {
629
+ await enforceWindowsOwnerOnlyDacl(credentialsDir, options?.windowsRunner);
630
+ return;
631
+ }
632
+ const info = await import_node_fs4.promises.lstat(credentialsDir);
633
+ if (!info.isDirectory() || info.uid !== process.geteuid?.()) {
634
+ throw new Error("unsafe_credentials_directory");
635
+ }
636
+ if ((info.mode & 511) !== 448) await import_node_fs4.promises.chmod(credentialsDir, 448);
637
+ };
638
+
639
+ // src/auth-lock.ts
640
+ var DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 3e4;
641
+ var DEFAULT_AUTH_LOCK_TIMEOUT_MS = 35e3;
642
+ var DEFAULT_POLL_MS = 25;
643
+ var inProcessQueues = /* @__PURE__ */ new Map();
644
+ var authLockPathFor = (dir) => import_node_path4.default.join(dir, ".auth-store-lock.sqlite");
645
+ var isMissing2 = (error) => error?.code === "ENOENT";
646
+ var lstatIfPresent = (file) => import_node_fs5.promises.lstat(file).catch((error) => {
647
+ if (!isMissing2(error)) throw error;
648
+ return void 0;
649
+ });
650
+ var verifyLockFile = async (file) => {
651
+ const info = await lstatIfPresent(file);
652
+ if (!info) return;
653
+ const uid = process.geteuid?.();
654
+ if (!info.isFile() || info.size === 0 || uid !== void 0 && (info.uid !== uid || (info.mode & 18) !== 0)) {
655
+ throw new Error("unsafe_auth_store_lock");
656
+ }
657
+ };
658
+ var initializeLockFile = async (lockPath) => {
659
+ if (await lstatIfPresent(lockPath)) return;
660
+ const temporary = `${lockPath}.${(0, import_node_crypto4.randomUUID)()}.tmp`;
661
+ try {
662
+ const file = await import_node_fs5.promises.open(temporary, "wx", 384);
663
+ await file.close();
664
+ const db = await openSqlite(temporary);
665
+ try {
666
+ db.exec("PRAGMA user_version = 1");
667
+ } finally {
668
+ db.close();
669
+ }
670
+ try {
671
+ await import_node_fs5.promises.link(temporary, lockPath);
672
+ } catch (error) {
673
+ if (error.code !== "EEXIST") throw error;
674
+ }
675
+ } finally {
676
+ await import_node_fs5.promises.unlink(temporary).catch(() => void 0);
677
+ }
678
+ };
679
+ var isSqliteBusy = (error) => {
680
+ const code = error?.code;
681
+ if (code === "SQLITE_BUSY" || code === "SQLITE_LOCKED") return true;
682
+ const message = error instanceof Error ? error.message : String(error);
683
+ return /database is locked|SQLITE_BUSY/i.test(message);
684
+ };
685
+ var openAuthLock = async (lockPath, timeoutMs, pollMs) => {
686
+ await ensureCredentialsDirectory(import_node_path4.default.dirname(lockPath));
687
+ await initializeLockFile(lockPath);
688
+ await verifyLockFile(lockPath);
689
+ if (process.platform === "win32") {
690
+ if (!await verifyWindowsCredentialFileAcl(lockPath)) {
691
+ throw new Error("unsafe_auth_store_lock");
692
+ }
693
+ await Promise.all(
694
+ ["-journal", "-wal", "-shm"].map(
695
+ (suffix) => verifyWindowsCredentialFileAcl(lockPath + suffix)
696
+ )
697
+ );
698
+ }
699
+ const db = await openSqlite(lockPath);
700
+ const deadline = performance.now() + timeoutMs;
701
+ try {
702
+ db.exec("PRAGMA busy_timeout = 0");
703
+ for (; ; ) {
704
+ try {
705
+ db.exec("BEGIN IMMEDIATE");
706
+ return db;
707
+ } catch (error) {
708
+ if (!isSqliteBusy(error) || performance.now() >= deadline) {
709
+ throw error;
710
+ }
711
+ await (0, import_promises3.setTimeout)(pollMs);
712
+ }
713
+ }
714
+ } catch (error) {
715
+ db.close();
716
+ throw error;
717
+ }
718
+ };
719
+ var enqueueInProcess = async (key, fn) => {
720
+ const previous = inProcessQueues.get(key) ?? Promise.resolve();
721
+ const next = previous.then(fn, fn);
722
+ const settled = next.then(
723
+ () => void 0,
724
+ () => void 0
725
+ );
726
+ inProcessQueues.set(key, settled);
727
+ try {
728
+ return await next;
729
+ } finally {
730
+ if (inProcessQueues.get(key) === settled) inProcessQueues.delete(key);
731
+ }
732
+ };
733
+ var withAuthStoreLock = (lockPath, fn, options = {}) => {
734
+ const resolved = import_node_path4.default.resolve(lockPath);
735
+ const timeoutMs = options.timeoutMs ?? DEFAULT_AUTH_LOCK_TIMEOUT_MS;
736
+ const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
737
+ return enqueueInProcess(resolved, async () => {
738
+ const db = await openAuthLock(resolved, timeoutMs, pollMs);
739
+ try {
740
+ return await fn();
741
+ } finally {
742
+ try {
743
+ db.exec("ROLLBACK");
744
+ } catch {
745
+ }
746
+ db.close();
747
+ }
748
+ });
749
+ };
750
+
751
+ // src/macos-keychain.ts
752
+ var import_node_child_process2 = require("child_process");
753
+ var import_node_crypto5 = require("crypto");
754
+ var import_node_fs6 = require("fs");
755
+ var import_node_os = __toESM(require("os"), 1);
756
+ var import_node_path5 = __toESM(require("path"), 1);
757
+ var CODELIA_AUTH_KEYCHAIN_SERVICE = "codelia.auth";
758
+ var CODELIA_MCP_AUTH_KEYCHAIN_SERVICE = "codelia.mcp-auth";
759
+ var DEFAULT_SECURITY_PATH = "/usr/bin/security";
760
+ var DEFAULT_ASYNC_TIMEOUT_MS = 5e3;
761
+ var DEFAULT_SYNC_TIMEOUT_MS = 2e3;
762
+ var AUTHORIZATION_TIMEOUT_MS = 12e4;
763
+ var MAX_SECURITY_BUFFER = 8 * 1024 * 1024;
764
+ var SECURITY_INTERACTIVE_MAX_LINE_BYTES = 4096;
765
+ var MAX_STDERR_CAPTURE_BYTES = 16384;
766
+ var MAX_CHUNKS = 64;
767
+ var SWEEP_CONSECUTIVE_MISS_LIMIT = 2;
768
+ var MAX_SNAPSHOT_ATTEMPTS = 3;
769
+ var CHUNK_RAW_BYTES = 1800;
770
+ var MAX_KEYCHAIN_PAYLOAD_BYTES = MAX_CHUNKS * CHUNK_RAW_BYTES;
771
+ var CHUNK_PREFIX = "cb1:";
772
+ var GEN_POINTER_PREFIX = "cb2:";
773
+ var SAFE_TOKEN_RE = /^[A-Za-z0-9._:#-]+$/;
774
+ var KeychainError = class extends Error {
775
+ code;
776
+ constructor(code, message) {
777
+ super(message);
778
+ this.name = "KeychainError";
779
+ this.code = code;
780
+ }
781
+ };
782
+ var canonicalDirForHash = (configDir) => {
783
+ const resolved = import_node_path5.default.resolve(configDir);
784
+ try {
785
+ return (0, import_node_fs6.realpathSync)(resolved);
786
+ } catch {
787
+ return resolved;
788
+ }
789
+ };
790
+ var keychainAccountForConfigDir = (configDir) => {
791
+ const digest2 = (0, import_node_crypto5.createHash)("sha256").update(canonicalDirForHash(configDir)).digest("hex").slice(0, 16);
792
+ return `codelia-${digest2}`;
793
+ };
794
+ var validateKeychainToken = (label2, value) => {
795
+ if (!value || !SAFE_TOKEN_RE.test(value)) {
796
+ throw new KeychainError(
797
+ "keychain_error",
798
+ `Invalid Keychain ${label2} identifier`
799
+ );
800
+ }
801
+ };
802
+ var chunkServiceName = (service, index) => index === 0 ? service : `${service}#${index}`;
803
+ var genChunkServiceName = (service, gen, index) => `${service}#g:${gen}:${index}`;
804
+ var encodePayloadChunks = (value) => {
805
+ const raw = Buffer.from(value, "utf8");
806
+ const total = Math.max(1, Math.ceil(raw.length / CHUNK_RAW_BYTES));
807
+ if (total > MAX_CHUNKS) {
808
+ throw new KeychainError(
809
+ "keychain_error",
810
+ `Keychain payload exceeds maximum size (${MAX_KEYCHAIN_PAYLOAD_BYTES} bytes)`
811
+ );
812
+ }
813
+ const chunks = [];
814
+ for (let i = 0; i < total; i += 1) {
815
+ const slice = raw.subarray(
816
+ i * CHUNK_RAW_BYTES,
817
+ Math.min(raw.length, (i + 1) * CHUNK_RAW_BYTES)
818
+ );
819
+ chunks.push(`${CHUNK_PREFIX}${total}:${slice.toString("base64")}`);
820
+ }
821
+ return chunks;
822
+ };
823
+ var FIXED_GEN_SLOTS = ["a", "b"];
824
+ var parseGenPointer = (raw) => {
825
+ if (!raw.startsWith(GEN_POINTER_PREFIX)) return null;
826
+ const parts = raw.slice(GEN_POINTER_PREFIX.length).split(":");
827
+ if (parts.length !== 2) {
828
+ throw new KeychainError(
829
+ "keychain_error",
830
+ "Corrupt Keychain generation pointer"
831
+ );
832
+ }
833
+ const [gen, totalStr] = parts;
834
+ const countAndDigest = /^([1-9][0-9]*)(?:\.([a-f0-9]{64}))?$/.exec(totalStr);
835
+ const total = Number(countAndDigest?.[1]);
836
+ if (!/^(?:a|b|[0-9a-f]{8,16})$/.test(gen) || !Number.isInteger(total) || total < 1 || total > MAX_CHUNKS) {
837
+ throw new KeychainError(
838
+ "keychain_error",
839
+ "Corrupt Keychain generation pointer metadata"
840
+ );
841
+ }
842
+ return { gen, total, digest: countAndDigest?.[2] };
843
+ };
844
+ var parseChunkEnvelope = (raw) => {
845
+ if (!raw.startsWith(CHUNK_PREFIX)) return null;
846
+ const rest = raw.slice(CHUNK_PREFIX.length);
847
+ const sep = rest.indexOf(":");
848
+ if (sep <= 0) {
849
+ throw new KeychainError(
850
+ "keychain_error",
851
+ "Corrupt Keychain chunk envelope"
852
+ );
853
+ }
854
+ const total = Number.parseInt(rest.slice(0, sep), 10);
855
+ const base64 = rest.slice(sep + 1);
856
+ if (!Number.isInteger(total) || total < 1 || total > MAX_CHUNKS || !/^[A-Za-z0-9+/=]*$/.test(base64)) {
857
+ throw new KeychainError(
858
+ "keychain_error",
859
+ "Corrupt Keychain chunk metadata"
860
+ );
861
+ }
862
+ return { total, base64 };
863
+ };
864
+ var extractValidatedChunkBase64 = (rawChunk, expectedTotal, index, service) => {
865
+ if (rawChunk === null) {
866
+ throw new KeychainError(
867
+ "keychain_error",
868
+ `Missing Keychain chunk ${index + 1}/${expectedTotal} for ${service}`
869
+ );
870
+ }
871
+ const parsed = parseChunkEnvelope(rawChunk);
872
+ if (!parsed || parsed.total !== expectedTotal) {
873
+ throw new KeychainError(
874
+ "keychain_error",
875
+ `Inconsistent Keychain chunk ${index + 1}/${expectedTotal} for ${service}`
876
+ );
877
+ }
878
+ return parsed.base64;
879
+ };
880
+ var decodeBase64Chunks = (parts) => Buffer.from(parts.join(""), "base64").toString("utf8");
881
+ var payloadDigest = (value) => (0, import_node_crypto5.createHash)("sha256").update(value, "utf8").digest("hex");
882
+ var decodeLegacyOrSingleValue = (trimmed) => {
883
+ if (trimmed.startsWith("{")) return trimmed;
884
+ if (/^[0-9a-fA-F]+$/.test(trimmed) && trimmed.length % 2 === 0) {
885
+ const decoded = Buffer.from(trimmed, "hex").toString("utf8");
886
+ if (decoded.startsWith("{")) return decoded;
887
+ }
888
+ throw new KeychainError(
889
+ "keychain_error",
890
+ "Keychain item contains unrecognized credential format"
891
+ );
892
+ };
893
+ function* readChunkedSnapshot(service, root) {
894
+ if (root === null) return { value: null };
895
+ const pointer = parseGenPointer(root);
896
+ const first = pointer ? null : parseChunkEnvelope(root);
897
+ if (!pointer && !first) return { value: decodeLegacyOrSingleValue(root) };
898
+ if (first?.total === 1) return { value: decodeBase64Chunks([first.base64]) };
899
+ const total = pointer?.total ?? first?.total ?? 0;
900
+ const parts = first ? [first.base64] : [];
901
+ let result;
902
+ try {
903
+ for (let i = parts.length; i < total; i += 1) {
904
+ const rawChunk = yield pointer ? genChunkServiceName(service, pointer.gen, i) : chunkServiceName(service, i);
905
+ parts.push(extractValidatedChunkBase64(rawChunk, total, i, service));
906
+ }
907
+ const value = decodeBase64Chunks(parts);
908
+ if (pointer?.digest && pointer.digest !== payloadDigest(value)) {
909
+ throw new KeychainError(
910
+ "keychain_error",
911
+ "Inconsistent Keychain payload"
912
+ );
913
+ }
914
+ result = { value };
915
+ } catch (error) {
916
+ result = { error };
917
+ }
918
+ const currentRoot = yield service;
919
+ if (currentRoot !== root) return { nextRoot: currentRoot };
920
+ if ("error" in result) throw result.error;
921
+ return result;
922
+ }
923
+ var isNotFoundOutput = (code, stderr) => code === 44 || /could not be found in the keychain|SecKeychainSearchCopyNext: The specified item could not be found/i.test(
924
+ stderr
925
+ );
926
+ var classifySecurityFailure = (code, stderr, timedOut = false) => {
927
+ if (timedOut) {
928
+ return new KeychainError(
929
+ "keychain_error",
930
+ "macOS Keychain operation timed out. Run `codelia auth authorize-keychain` from a local terminal, then retry."
931
+ );
932
+ }
933
+ if (code === 36 || /User interaction is not allowed|errSecInteractionNotAllowed|keychain is locked/i.test(
934
+ stderr
935
+ )) {
936
+ return new KeychainError(
937
+ "keychain_locked",
938
+ "macOS login Keychain is locked; run `security unlock-keychain ~/Library/Keychains/login.keychain-db`"
939
+ );
940
+ }
941
+ if (code === 128 || /User canceled the operation|errSecUserCanceled|errSecAuthFailed|The user name or passphrase you entered is not correct/i.test(
942
+ stderr
943
+ )) {
944
+ return new KeychainError(
945
+ "keychain_access_denied",
946
+ "macOS Keychain denied access; run `codelia auth authorize-keychain` from a local terminal"
947
+ );
948
+ }
949
+ return new KeychainError("keychain_error", "macOS Keychain operation failed");
950
+ };
951
+ var securityEnv = () => ({
952
+ HOME: import_node_os.default.homedir(),
953
+ PATH: "/usr/bin:/bin",
954
+ ...process.env.USER ? { USER: process.env.USER } : {},
955
+ ...process.env.LOGNAME ? { LOGNAME: process.env.LOGNAME } : {}
956
+ });
957
+ var MacOsKeychainClient = class {
958
+ securityBinary;
959
+ hasCustomBinary;
960
+ constructor(options) {
961
+ const custom = options?.securityPath ?? options?.helperPath;
962
+ this.securityBinary = custom ?? DEFAULT_SECURITY_PATH;
963
+ this.hasCustomBinary = Boolean(custom);
964
+ }
965
+ resolveBinary() {
966
+ if (!this.hasCustomBinary && process.platform !== "darwin") {
967
+ return null;
968
+ }
969
+ if (!this.hasCustomBinary && process.env.CODELIA_TEST_KEYCHAIN_DISABLED === "1") {
970
+ throw new KeychainError(
971
+ "keychain_unavailable",
972
+ "macOS Keychain is disabled for tests"
973
+ );
974
+ }
975
+ try {
976
+ (0, import_node_fs6.accessSync)(this.securityBinary, import_node_fs6.constants.X_OK);
977
+ return this.securityBinary;
978
+ } catch {
979
+ return null;
980
+ }
981
+ }
982
+ requireBinary() {
983
+ const binary = this.resolveBinary();
984
+ if (!binary) {
985
+ throw new KeychainError(
986
+ "keychain_unavailable",
987
+ process.platform !== "darwin" ? "unsupported_platform" : "macOS /usr/bin/security is unavailable"
988
+ );
989
+ }
990
+ return binary;
991
+ }
992
+ runArgsAsync(args, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
993
+ const binary = this.requireBinary();
994
+ return new Promise((resolve, reject) => {
995
+ (0, import_node_child_process2.execFile)(
996
+ binary,
997
+ [...args],
998
+ {
999
+ cwd: "/",
1000
+ env: securityEnv(),
1001
+ timeout: timeoutMs,
1002
+ killSignal: "SIGKILL",
1003
+ maxBuffer: MAX_SECURITY_BUFFER,
1004
+ encoding: "utf8"
1005
+ },
1006
+ (error, stdout, stderr) => {
1007
+ if (!error) {
1008
+ resolve({ code: 0, stdout, stderr });
1009
+ return;
1010
+ }
1011
+ const timedOut = Boolean(error.killed && error.code === null);
1012
+ const exitCode = typeof error.code === "number" ? error.code : null;
1013
+ if (timedOut) {
1014
+ reject(classifySecurityFailure(exitCode, stderr ?? "", true));
1015
+ return;
1016
+ }
1017
+ resolve({
1018
+ code: exitCode ?? 1,
1019
+ stdout: stdout ?? "",
1020
+ stderr: stderr ?? error.message
1021
+ });
1022
+ }
1023
+ );
1024
+ });
1025
+ }
1026
+ runInteractiveBatchAsync(commands, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
1027
+ const binary = this.requireBinary();
1028
+ const payload = `${commands.join("\n")}
1029
+ `;
1030
+ for (const line of commands) {
1031
+ if (Buffer.byteLength(line, "utf8") + 1 >= SECURITY_INTERACTIVE_MAX_LINE_BYTES) {
1032
+ throw new KeychainError(
1033
+ "keychain_error",
1034
+ "Keychain batch command exceeds 4096-byte security -i line limit"
1035
+ );
1036
+ }
1037
+ }
1038
+ return new Promise((resolve, reject) => {
1039
+ const child = (0, import_node_child_process2.spawn)(binary, ["-i"], {
1040
+ cwd: "/",
1041
+ env: securityEnv(),
1042
+ stdio: ["pipe", "pipe", "pipe"]
1043
+ });
1044
+ let stderr = "";
1045
+ let timedOut = false;
1046
+ const timer = setTimeout(() => {
1047
+ timedOut = true;
1048
+ child.kill("SIGKILL");
1049
+ }, timeoutMs);
1050
+ child.stdout.on("data", () => void 0);
1051
+ child.stderr.on("data", (chunk) => {
1052
+ if (stderr.length < MAX_STDERR_CAPTURE_BYTES) {
1053
+ stderr += chunk.toString("utf8");
1054
+ }
1055
+ });
1056
+ child.once("error", () => {
1057
+ clearTimeout(timer);
1058
+ reject(
1059
+ new KeychainError(
1060
+ "keychain_unavailable",
1061
+ "Failed to launch macOS /usr/bin/security"
1062
+ )
1063
+ );
1064
+ });
1065
+ child.once("close", (code) => {
1066
+ clearTimeout(timer);
1067
+ if (timedOut) {
1068
+ reject(classifySecurityFailure(code, stderr, true));
1069
+ return;
1070
+ }
1071
+ if (code !== 0) {
1072
+ reject(classifySecurityFailure(code, stderr, false));
1073
+ return;
1074
+ }
1075
+ resolve();
1076
+ });
1077
+ child.stdin.on("error", () => void 0);
1078
+ child.stdin.end(payload);
1079
+ });
1080
+ }
1081
+ findRawAsync(service, account, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
1082
+ validateKeychainToken("service", service);
1083
+ validateKeychainToken("account", account);
1084
+ return this.runArgsAsync(
1085
+ ["find-generic-password", "-w", "-a", account, "-s", service],
1086
+ timeoutMs
1087
+ ).then(({ code, stdout, stderr }) => {
1088
+ if (code === 0) return stdout.replace(/\r?\n$/, "");
1089
+ if (isNotFoundOutput(code, stderr)) return null;
1090
+ throw classifySecurityFailure(code, stderr);
1091
+ });
1092
+ }
1093
+ findRawSync(service, account, timeoutMs = DEFAULT_SYNC_TIMEOUT_MS) {
1094
+ validateKeychainToken("service", service);
1095
+ validateKeychainToken("account", account);
1096
+ const binary = this.requireBinary();
1097
+ try {
1098
+ const stdout = (0, import_node_child_process2.execFileSync)(
1099
+ binary,
1100
+ ["find-generic-password", "-w", "-a", account, "-s", service],
1101
+ {
1102
+ cwd: "/",
1103
+ env: securityEnv(),
1104
+ stdio: ["ignore", "pipe", "pipe"],
1105
+ timeout: timeoutMs,
1106
+ killSignal: "SIGKILL",
1107
+ maxBuffer: MAX_SECURITY_BUFFER,
1108
+ encoding: "utf8"
1109
+ }
1110
+ );
1111
+ return stdout.replace(/\r?\n$/, "");
1112
+ } catch (error) {
1113
+ const err = error;
1114
+ const status = typeof err.status === "number" ? err.status : null;
1115
+ const stderr = typeof err.stderr === "string" ? err.stderr : Buffer.isBuffer(err.stderr) ? err.stderr.toString("utf8") : "";
1116
+ const timedOut = err.code === "ETIMEDOUT" || status === null && Boolean(err.signal);
1117
+ if (!timedOut && isNotFoundOutput(status, stderr)) {
1118
+ return null;
1119
+ }
1120
+ throw classifySecurityFailure(status, stderr, timedOut);
1121
+ }
1122
+ }
1123
+ async probe() {
1124
+ if (!this.hasCustomBinary && process.platform !== "darwin") {
1125
+ return {
1126
+ available: false,
1127
+ reason: "unsupported_platform",
1128
+ message: "OS Keychain backend is currently supported on macOS only"
1129
+ };
1130
+ }
1131
+ try {
1132
+ const binary = this.resolveBinary();
1133
+ if (!binary) {
1134
+ return {
1135
+ available: false,
1136
+ reason: "keychain_unavailable",
1137
+ message: "macOS /usr/bin/security is unavailable"
1138
+ };
1139
+ }
1140
+ const { code, stderr } = await this.runArgsAsync(["show-keychain-info"]);
1141
+ if (code === 0) return { available: true };
1142
+ const classified = classifySecurityFailure(code, stderr);
1143
+ return {
1144
+ available: false,
1145
+ reason: classified.code === "keychain_locked" ? "keychain_locked" : "keychain_unavailable",
1146
+ message: classified.message
1147
+ };
1148
+ } catch (error) {
1149
+ const isLocked = error instanceof KeychainError && error.code === "keychain_locked";
1150
+ return {
1151
+ available: false,
1152
+ reason: isLocked ? "keychain_locked" : "keychain_unavailable",
1153
+ message: error instanceof Error ? error.message : String(error)
1154
+ };
1155
+ }
1156
+ }
1157
+ async readFullAsync(service, account, timeoutMs = DEFAULT_ASYNC_TIMEOUT_MS) {
1158
+ const find = (name) => this.findRawAsync(name, account, timeoutMs);
1159
+ let root = await find(service);
1160
+ for (let attempt = 0; attempt < MAX_SNAPSHOT_ATTEMPTS; attempt += 1) {
1161
+ const snapshot = readChunkedSnapshot(service, root);
1162
+ let step = snapshot.next();
1163
+ while (!step.done) step = snapshot.next(await find(step.value));
1164
+ if ("value" in step.value) return step.value.value;
1165
+ root = step.value.nextRoot;
1166
+ }
1167
+ throw new KeychainError(
1168
+ "keychain_error",
1169
+ "Keychain changed during read; retry"
1170
+ );
1171
+ }
1172
+ async get(service, account) {
1173
+ return this.readFullAsync(service, account, DEFAULT_ASYNC_TIMEOUT_MS);
1174
+ }
1175
+ getSync(service, account, timeoutMs = DEFAULT_SYNC_TIMEOUT_MS) {
1176
+ const deadline = performance.now() + timeoutMs;
1177
+ const find = (name) => {
1178
+ const remaining = Math.ceil(deadline - performance.now());
1179
+ if (remaining <= 0) throw classifySecurityFailure(null, "", true);
1180
+ return this.findRawSync(name, account, remaining);
1181
+ };
1182
+ let root = find(service);
1183
+ for (let attempt = 0; attempt < MAX_SNAPSHOT_ATTEMPTS; attempt += 1) {
1184
+ const snapshot = readChunkedSnapshot(service, root);
1185
+ let step = snapshot.next();
1186
+ while (!step.done) step = snapshot.next(find(step.value));
1187
+ if ("value" in step.value) return step.value.value;
1188
+ root = step.value.nextRoot;
1189
+ }
1190
+ throw new KeychainError(
1191
+ "keychain_error",
1192
+ "Keychain changed during read; retry"
1193
+ );
1194
+ }
1195
+ async sweepGenSlotBestEffort(service, account, gen, startIndex = 0) {
1196
+ let consecutiveMisses = 0;
1197
+ for (let i = startIndex; i < MAX_CHUNKS; i += 1) {
1198
+ const deleted = await this.deleteSingleItem(
1199
+ genChunkServiceName(service, gen, i),
1200
+ account
1201
+ ).catch(() => false);
1202
+ if (deleted) {
1203
+ consecutiveMisses = 0;
1204
+ } else {
1205
+ consecutiveMisses += 1;
1206
+ if (consecutiveMisses >= SWEEP_CONSECUTIVE_MISS_LIMIT) break;
1207
+ }
1208
+ }
1209
+ }
1210
+ /**
1211
+ * Exhaustively delete every possible chunk index (`0..MAX_CHUNKS-1`) in a
1212
+ * fixed generation slot and propagate any non-not-found delete error.
1213
+ */
1214
+ async deleteAllSlotChunksStrict(service, account, gen) {
1215
+ let deletedAny = false;
1216
+ for (let i = 0; i < MAX_CHUNKS; i += 1) {
1217
+ const deleted = await this.deleteSingleItem(
1218
+ genChunkServiceName(service, gen, i),
1219
+ account
1220
+ );
1221
+ if (deleted) deletedAny = true;
1222
+ }
1223
+ return deletedAny;
1224
+ }
1225
+ async cleanupOldChunks(service, account, previousRoot, keepGen) {
1226
+ try {
1227
+ if (previousRoot) {
1228
+ let prevPtr = null;
1229
+ try {
1230
+ prevPtr = parseGenPointer(previousRoot);
1231
+ } catch {
1232
+ prevPtr = null;
1233
+ }
1234
+ if (prevPtr && prevPtr.gen !== keepGen) {
1235
+ for (let i = 0; i < prevPtr.total; i += 1) {
1236
+ await this.deleteSingleItem(
1237
+ genChunkServiceName(service, prevPtr.gen, i),
1238
+ account
1239
+ ).catch(() => false);
1240
+ }
1241
+ }
1242
+ let prevCb1 = null;
1243
+ try {
1244
+ prevCb1 = parseChunkEnvelope(previousRoot);
1245
+ } catch {
1246
+ prevCb1 = null;
1247
+ }
1248
+ if (prevCb1 && prevCb1.total > 1) {
1249
+ for (let i = 1; i < prevCb1.total; i += 1) {
1250
+ await this.deleteSingleItem(
1251
+ chunkServiceName(service, i),
1252
+ account
1253
+ ).catch(() => false);
1254
+ }
1255
+ }
1256
+ }
1257
+ for (const slot of FIXED_GEN_SLOTS) {
1258
+ if (slot !== keepGen) {
1259
+ await this.sweepGenSlotBestEffort(service, account, slot, 0);
1260
+ }
1261
+ }
1262
+ } catch {
1263
+ }
1264
+ }
1265
+ async writeSingleChunk(service, account, encoded, previousRoot) {
1266
+ await this.runInteractiveBatchAsync([
1267
+ `add-generic-password -U -a ${account} -s ${service} -w ${encoded}`
1268
+ ]);
1269
+ const verified = await this.findRawAsync(service, account);
1270
+ if (verified !== encoded) {
1271
+ throw new KeychainError(
1272
+ "keychain_error",
1273
+ "macOS Keychain write verification failed"
1274
+ );
1275
+ }
1276
+ await this.cleanupOldChunks(service, account, previousRoot);
1277
+ }
1278
+ /**
1279
+ * Multi-chunk write: alternates between fixed A/B slots (`a` and `b`) so
1280
+ * existing credentials stay untouched until every staged chunk verifies via
1281
+ * read-back AND crashed writes remain deterministically discoverable on logout.
1282
+ */
1283
+ async writeMultiChunk(service, account, chunks, previousRoot, digest2) {
1284
+ const activeGen = previousRoot ? parseGenPointer(previousRoot)?.gen : void 0;
1285
+ const gen = activeGen === "a" ? "b" : "a";
1286
+ const stageCommands = chunks.map(
1287
+ (encoded, index) => `add-generic-password -U -a ${account} -s ${genChunkServiceName(service, gen, index)} -w ${encoded}`
1288
+ );
1289
+ const rollbackStaged = async () => {
1290
+ for (let i = 0; i < chunks.length; i += 1) {
1291
+ await this.deleteSingleItem(
1292
+ genChunkServiceName(service, gen, i),
1293
+ account
1294
+ ).catch(() => false);
1295
+ }
1296
+ };
1297
+ try {
1298
+ await this.runInteractiveBatchAsync(stageCommands);
1299
+ for (let i = 0; i < chunks.length; i += 1) {
1300
+ const verified = await this.findRawAsync(
1301
+ genChunkServiceName(service, gen, i),
1302
+ account
1303
+ );
1304
+ if (verified !== chunks[i]) {
1305
+ throw new KeychainError(
1306
+ "keychain_error",
1307
+ `macOS Keychain staged chunk ${i + 1}/${chunks.length} failed verification`
1308
+ );
1309
+ }
1310
+ }
1311
+ } catch (error) {
1312
+ await rollbackStaged();
1313
+ throw error;
1314
+ }
1315
+ const pointerValue = `${GEN_POINTER_PREFIX}${gen}:${chunks.length}.${digest2}`;
1316
+ await this.runInteractiveBatchAsync([
1317
+ `add-generic-password -U -a ${account} -s ${service} -w ${pointerValue}`
1318
+ ]);
1319
+ const verifiedPointer = await this.findRawAsync(service, account);
1320
+ if (verifiedPointer !== pointerValue) {
1321
+ await rollbackStaged();
1322
+ throw new KeychainError(
1323
+ "keychain_error",
1324
+ "macOS Keychain pointer verification failed"
1325
+ );
1326
+ }
1327
+ await this.sweepGenSlotBestEffort(service, account, gen, chunks.length);
1328
+ await this.cleanupOldChunks(service, account, previousRoot, gen);
1329
+ }
1330
+ async set(service, account, value) {
1331
+ validateKeychainToken("service", service);
1332
+ validateKeychainToken("account", account);
1333
+ const chunks = encodePayloadChunks(value);
1334
+ const previousRoot = await this.findRawAsync(service, account);
1335
+ if (chunks.length === 1) {
1336
+ await this.writeSingleChunk(service, account, chunks[0], previousRoot);
1337
+ return;
1338
+ }
1339
+ await this.writeMultiChunk(
1340
+ service,
1341
+ account,
1342
+ chunks,
1343
+ previousRoot,
1344
+ payloadDigest(value)
1345
+ );
1346
+ }
1347
+ async deleteSingleItem(service, account) {
1348
+ validateKeychainToken("service", service);
1349
+ validateKeychainToken("account", account);
1350
+ const { code, stderr } = await this.runArgsAsync([
1351
+ "delete-generic-password",
1352
+ "-a",
1353
+ account,
1354
+ "-s",
1355
+ service
1356
+ ]);
1357
+ if (code === 0) return true;
1358
+ if (isNotFoundOutput(code, stderr)) return false;
1359
+ throw classifySecurityFailure(code, stderr);
1360
+ }
1361
+ async delete(service, account) {
1362
+ validateKeychainToken("service", service);
1363
+ validateKeychainToken("account", account);
1364
+ const existing = await this.findRawAsync(service, account);
1365
+ let deletedAny = false;
1366
+ if (existing) {
1367
+ let prevCb1 = null;
1368
+ try {
1369
+ prevCb1 = parseChunkEnvelope(existing);
1370
+ } catch {
1371
+ prevCb1 = null;
1372
+ }
1373
+ if (prevCb1 && prevCb1.total > 1) {
1374
+ for (let i = 1; i < prevCb1.total; i += 1) {
1375
+ if (await this.deleteSingleItem(chunkServiceName(service, i), account)) {
1376
+ deletedAny = true;
1377
+ }
1378
+ }
1379
+ }
1380
+ let prevPtr = null;
1381
+ try {
1382
+ prevPtr = parseGenPointer(existing);
1383
+ } catch {
1384
+ prevPtr = null;
1385
+ }
1386
+ if (prevPtr && !FIXED_GEN_SLOTS.includes(
1387
+ prevPtr.gen
1388
+ )) {
1389
+ for (let i = 0; i < prevPtr.total; i += 1) {
1390
+ if (await this.deleteSingleItem(
1391
+ genChunkServiceName(service, prevPtr.gen, i),
1392
+ account
1393
+ )) {
1394
+ deletedAny = true;
1395
+ }
1396
+ }
1397
+ }
1398
+ }
1399
+ const deletedPrimary = await this.deleteSingleItem(service, account);
1400
+ if (deletedPrimary) deletedAny = true;
1401
+ for (const slot of FIXED_GEN_SLOTS) {
1402
+ if (await this.deleteAllSlotChunksStrict(service, account, slot)) {
1403
+ deletedAny = true;
1404
+ }
1405
+ }
1406
+ return deletedAny;
1407
+ }
1408
+ /** Let macOS prompt the user to authorize reading each existing item. */
1409
+ async authorize(service, account) {
1410
+ const fullValue = await this.readFullAsync(
1411
+ service,
1412
+ account,
1413
+ AUTHORIZATION_TIMEOUT_MS
1414
+ );
1415
+ return fullValue !== null;
1416
+ }
1417
+ };
1418
+
1419
+ // src/auth-schema.ts
1420
+ var AUTH_VERSION_V1 = 1;
1421
+ var AUTH_VERSION_V2 = 2;
1422
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1423
+ var normalizeApiKey = (value) => {
1424
+ if (!isRecord(value) || typeof value.api_key !== "string") return null;
1425
+ return {
1426
+ api_key: value.api_key,
1427
+ ...typeof value.api_base === "string" && value.api_base.length > 0 ? { api_base: value.api_base } : {}
1428
+ };
1429
+ };
1430
+ var normalizeOAuth = (value) => {
1431
+ if (!isRecord(value) || typeof value.access_token !== "string" || typeof value.refresh_token !== "string" || typeof value.expires_at !== "number" || !Number.isFinite(value.expires_at)) {
1432
+ return null;
1433
+ }
1434
+ return {
1435
+ access_token: value.access_token,
1436
+ refresh_token: value.refresh_token,
1437
+ expires_at: value.expires_at,
1438
+ ...typeof value.account_id === "string" && value.account_id.length > 0 ? { account_id: value.account_id } : {}
1439
+ };
1440
+ };
1441
+ var normalizeProviderEntryV1 = (value) => {
1442
+ if (!isRecord(value)) {
1443
+ throw new Error("auth.json contains invalid provider entry");
1444
+ }
1445
+ if (value.method === "api_key") {
1446
+ const apiKey = normalizeApiKey(value);
1447
+ if (!apiKey) {
1448
+ throw new Error("auth.json contains invalid api_key entry");
1449
+ }
1450
+ return {
1451
+ chat_method: "api_key",
1452
+ credentials: { api_key: apiKey }
1453
+ };
1454
+ }
1455
+ if (value.method === "oauth") {
1456
+ const oauth = normalizeOAuth(value.oauth);
1457
+ if (!oauth) {
1458
+ throw new Error("auth.json contains invalid oauth entry");
1459
+ }
1460
+ return {
1461
+ chat_method: "oauth",
1462
+ credentials: { oauth }
1463
+ };
1464
+ }
1465
+ throw new Error("auth.json contains unsupported auth method");
1466
+ };
1467
+ var normalizeProviderEntryV2 = (value) => {
1468
+ if (!isRecord(value) || !isRecord(value.credentials)) {
1469
+ throw new Error("auth.json v2 contains invalid provider entry");
1470
+ }
1471
+ const chatMethod = value.chat_method;
1472
+ if (chatMethod !== void 0 && chatMethod !== "api_key" && chatMethod !== "oauth") {
1473
+ throw new Error("auth.json v2 contains invalid chat_method");
1474
+ }
1475
+ const credentials = {};
1476
+ if (value.credentials.api_key !== void 0) {
1477
+ const apiKey = normalizeApiKey(value.credentials.api_key);
1478
+ if (!apiKey) {
1479
+ throw new Error("auth.json v2 contains invalid api_key credential");
1480
+ }
1481
+ credentials.api_key = apiKey;
1482
+ }
1483
+ if (value.credentials.oauth !== void 0) {
1484
+ const oauth = normalizeOAuth(value.credentials.oauth);
1485
+ if (!oauth) {
1486
+ throw new Error("auth.json v2 contains invalid oauth credential");
1487
+ }
1488
+ credentials.oauth = oauth;
1489
+ }
1490
+ return {
1491
+ ...chatMethod ? { chat_method: chatMethod } : {},
1492
+ credentials
1493
+ };
1494
+ };
1495
+ var parseAuthDocument = (text) => {
1496
+ const parsed = JSON.parse(text);
1497
+ if (!isRecord(parsed)) {
1498
+ throw new Error("auth.json has unsupported format");
1499
+ }
1500
+ if (parsed.version === AUTH_VERSION_V1) {
1501
+ const rawProviders = isRecord(parsed.providers) ? parsed.providers : {};
1502
+ const providers = {};
1503
+ for (const [name, entry] of Object.entries(rawProviders)) {
1504
+ providers[name] = normalizeProviderEntryV1(entry);
1505
+ }
1506
+ return {
1507
+ normalized: { version: AUTH_VERSION_V2, providers },
1508
+ sourceVersion: 1
1509
+ };
1510
+ }
1511
+ if (parsed.version === AUTH_VERSION_V2) {
1512
+ const rawProviders = isRecord(parsed.providers) ? parsed.providers : {};
1513
+ const providers = {};
1514
+ for (const [name, entry] of Object.entries(rawProviders)) {
1515
+ providers[name] = normalizeProviderEntryV2(entry);
1516
+ }
1517
+ return {
1518
+ normalized: { version: AUTH_VERSION_V2, providers },
1519
+ sourceVersion: 2
1520
+ };
1521
+ }
1522
+ throw new Error("auth.json has unsupported version");
1523
+ };
1524
+ var providerAuthStoreAdapter = {
1525
+ name: "auth",
1526
+ service: CODELIA_AUTH_KEYCHAIN_SERVICE,
1527
+ filePath: (paths) => paths.authFile,
1528
+ legacyFilePath: (paths) => paths.legacyAuthFile,
1529
+ empty: () => ({ version: AUTH_VERSION_V2, providers: {} }),
1530
+ isNonEmpty: (doc) => Object.keys(doc.providers).length > 0,
1531
+ parse: (text) => parseAuthDocument(text)
1532
+ };
1533
+
1534
+ // src/credential-backend.ts
1535
+ var import_node_fs8 = require("fs");
1536
+ var import_node_path7 = __toESM(require("path"), 1);
1537
+
1538
+ // src/credential-migration.ts
1539
+ var import_node_fs7 = require("fs");
1540
+ var CredentialConflictError = class extends Error {
1541
+ code = "credential_storage_conflict";
1542
+ store;
1543
+ constructor(store, detail) {
1544
+ super(
1545
+ detail ?? `Credential storage conflict detected for '${store}': both source and destination contain different credentials. Resolve the conflict before continuing.`
1546
+ );
1547
+ this.name = "CredentialConflictError";
1548
+ this.store = store;
1549
+ }
1550
+ };
1551
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1552
+ var canonicalizeValue = (value) => {
1553
+ if (Array.isArray(value)) {
1554
+ return value.map(canonicalizeValue);
1555
+ }
1556
+ if (isRecord2(value)) {
1557
+ const sorted = {};
1558
+ for (const key of Object.keys(value).sort()) {
1559
+ const entry = value[key];
1560
+ if (entry !== void 0) {
1561
+ sorted[key] = canonicalizeValue(entry);
1562
+ }
1563
+ }
1564
+ return sorted;
1565
+ }
1566
+ return value;
1567
+ };
1568
+ var canonicalJsonStringify = (value) => JSON.stringify(canonicalizeValue(value));
1569
+ var canonicalJsonEqual = (left, right) => canonicalJsonStringify(left) === canonicalJsonStringify(right);
1570
+ var parseAuthStorageState = (text) => {
1571
+ const parsed = JSON.parse(text);
1572
+ if (!isRecord2(parsed) || parsed.version !== 1) {
1573
+ throw new Error("storage-state.json has unsupported version");
1574
+ }
1575
+ const active = parsed.active_backend;
1576
+ if (active !== "file" && active !== "keyring") {
1577
+ throw new Error("storage-state.json has invalid active_backend");
1578
+ }
1579
+ if (parsed.mcp_reauth_required !== void 0 && (!Array.isArray(parsed.mcp_reauth_required) || !parsed.mcp_reauth_required.every((item) => typeof item === "string"))) {
1580
+ throw new Error("storage-state.json has invalid mcp_reauth_required");
1581
+ }
1582
+ const mcpReauth = parsed.mcp_reauth_required;
1583
+ if (parsed.status === "steady") {
1584
+ return {
1585
+ version: 1,
1586
+ status: "steady",
1587
+ active_backend: active,
1588
+ ...mcpReauth?.length ? { mcp_reauth_required: mcpReauth } : {}
1589
+ };
1590
+ }
1591
+ if (parsed.status === "migrating") {
1592
+ const target = parsed.target_backend;
1593
+ const stores = isRecord2(parsed.stores) ? parsed.stores : null;
1594
+ const authStatus = stores?.auth;
1595
+ const mcpStatus = stores?.mcp_auth;
1596
+ if (target !== "file" && target !== "keyring" || authStatus !== "pending" && authStatus !== "verified" || mcpStatus !== "pending" && mcpStatus !== "verified") {
1597
+ throw new Error("storage-state.json has invalid migrating state");
1598
+ }
1599
+ let cleanupPending;
1600
+ if (parsed.cleanup_pending !== void 0) {
1601
+ if (!isRecord2(parsed.cleanup_pending)) {
1602
+ throw new Error("storage-state.json has invalid cleanup_pending");
1603
+ }
1604
+ const sourceBackend = parsed.cleanup_pending.source_backend;
1605
+ const authFlag = parsed.cleanup_pending.auth;
1606
+ const mcpFlag = parsed.cleanup_pending.mcp_auth;
1607
+ if (sourceBackend !== "file" && sourceBackend !== "legacy_file" && sourceBackend !== "keyring" || typeof authFlag !== "boolean" || typeof mcpFlag !== "boolean") {
1608
+ throw new Error("storage-state.json has invalid cleanup_pending");
1609
+ }
1610
+ cleanupPending = {
1611
+ source_backend: sourceBackend,
1612
+ auth: authFlag,
1613
+ mcp_auth: mcpFlag
1614
+ };
1615
+ }
1616
+ return {
1617
+ version: 1,
1618
+ status: "migrating",
1619
+ active_backend: active,
1620
+ target_backend: target,
1621
+ stores: { auth: authStatus, mcp_auth: mcpStatus },
1622
+ ...cleanupPending ? { cleanup_pending: cleanupPending } : {},
1623
+ ...mcpReauth?.length ? { mcp_reauth_required: mcpReauth } : {}
1624
+ };
1625
+ }
1626
+ throw new Error("storage-state.json has invalid status");
1627
+ };
1628
+ var readAuthStorageState = async (stateFile) => {
1629
+ if (!await verifyWindowsCredentialFileAcl(stateFile)) return null;
1630
+ let text;
1631
+ try {
1632
+ text = await import_node_fs7.promises.readFile(stateFile, "utf8");
1633
+ } catch (error) {
1634
+ if (error?.code === "ENOENT") return null;
1635
+ throw error;
1636
+ }
1637
+ return parseAuthStorageState(text);
1638
+ };
1639
+ var readAuthStorageStateSync = (stateFile) => {
1640
+ if (!verifyWindowsCredentialFileAclSync(stateFile)) return null;
1641
+ let text;
1642
+ try {
1643
+ text = (0, import_node_fs7.readFileSync)(stateFile, "utf8");
1644
+ } catch (error) {
1645
+ if (error?.code === "ENOENT") return null;
1646
+ throw error;
1647
+ }
1648
+ return parseAuthStorageState(text);
1649
+ };
1650
+ var writeAuthStorageState = async (stateFile, state) => {
1651
+ await writeFileAtomic(stateFile, JSON.stringify(state, null, 2), {
1652
+ mode: 384
1653
+ });
1654
+ };
1655
+ var runTwoPhaseMigration = async (options) => {
1656
+ const [authSrc, authDst, mcpSrc, mcpDst] = await Promise.all([
1657
+ options.authSlot.readSource(),
1658
+ options.authSlot.readDest(),
1659
+ options.mcpSlot.readSource(),
1660
+ options.mcpSlot.readDest()
1661
+ ]);
1662
+ const evaluate = (name, src, dst) => {
1663
+ if (!src.present) return "none";
1664
+ if (src.nonEmpty && dst.nonEmpty) {
1665
+ if (canonicalJsonEqual(src.normalized, dst.normalized)) {
1666
+ return "recover";
1667
+ }
1668
+ throw new CredentialConflictError(name);
1669
+ }
1670
+ if (!src.nonEmpty && dst.nonEmpty) {
1671
+ return "recover";
1672
+ }
1673
+ if (dst.present && canonicalJsonEqual(src.normalized, dst.normalized)) {
1674
+ return "recover";
1675
+ }
1676
+ return "copy";
1677
+ };
1678
+ const authAction = evaluate("auth", authSrc, authDst);
1679
+ const mcpAction = evaluate("mcp_auth", mcpSrc, mcpDst);
1680
+ const mcpReauthSet = /* @__PURE__ */ new Set([
1681
+ ...options.existingMcpReauth ?? [],
1682
+ ...mcpSrc.extraWarnings ?? []
1683
+ ]);
1684
+ const mcpReauthRequired = [...mcpReauthSet].sort();
1685
+ if (authAction === "none" && mcpAction === "none") {
1686
+ if (options.fromBackend !== options.toBackend || options.commitSteadyIfEmpty) {
1687
+ await writeAuthStorageState(options.stateFile, {
1688
+ version: 1,
1689
+ status: "steady",
1690
+ active_backend: options.toBackend,
1691
+ ...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
1692
+ });
1693
+ }
1694
+ return { migrated: false, mcpReauthRequired };
1695
+ }
1696
+ const migratingState = {
1697
+ version: 1,
1698
+ status: "migrating",
1699
+ active_backend: options.fromBackend,
1700
+ target_backend: options.toBackend,
1701
+ stores: {
1702
+ auth: authAction === "copy" ? "pending" : "verified",
1703
+ mcp_auth: mcpAction === "copy" ? "pending" : "verified"
1704
+ },
1705
+ ...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
1706
+ };
1707
+ await writeAuthStorageState(options.stateFile, migratingState);
1708
+ if (authAction === "copy") {
1709
+ await options.authSlot.writeDest(authSrc.normalized);
1710
+ const verified = await options.authSlot.verifyDest(authSrc.normalized);
1711
+ if (!verified) {
1712
+ throw new Error("auth migration read-back verification failed");
1713
+ }
1714
+ migratingState.stores.auth = "verified";
1715
+ await writeAuthStorageState(options.stateFile, migratingState);
1716
+ }
1717
+ if (mcpAction === "copy") {
1718
+ await options.mcpSlot.writeDest(mcpSrc.normalized);
1719
+ const verified = await options.mcpSlot.verifyDest(mcpSrc.normalized);
1720
+ if (!verified) {
1721
+ throw new Error("mcp-auth migration read-back verification failed");
1722
+ }
1723
+ migratingState.stores.mcp_auth = "verified";
1724
+ await writeAuthStorageState(options.stateFile, migratingState);
1725
+ }
1726
+ if (authSrc.present || mcpSrc.present) {
1727
+ migratingState.cleanup_pending = {
1728
+ source_backend: options.cleanupSourceKind ?? options.fromBackend,
1729
+ auth: authSrc.present,
1730
+ mcp_auth: mcpSrc.present
1731
+ };
1732
+ await writeAuthStorageState(options.stateFile, migratingState);
1733
+ }
1734
+ if (authSrc.present) {
1735
+ await options.authSlot.cleanupSource();
1736
+ }
1737
+ if (mcpSrc.present) {
1738
+ await options.mcpSlot.cleanupSource();
1739
+ }
1740
+ await writeAuthStorageState(options.stateFile, {
1741
+ version: 1,
1742
+ status: "steady",
1743
+ active_backend: options.toBackend,
1744
+ ...mcpReauthRequired.length ? { mcp_reauth_required: mcpReauthRequired } : {}
1745
+ });
1746
+ return { migrated: true, mcpReauthRequired };
1747
+ };
1748
+
1749
+ // src/paths.ts
1750
+ var import_promises4 = require("fs/promises");
1751
+ var import_node_os2 = __toESM(require("os"), 1);
1752
+ var import_node_path6 = __toESM(require("path"), 1);
1753
+ var DEFAULT_ROOT_DIR = ".codelia";
1754
+ var LAYOUT_ENV = "CODELIA_LAYOUT";
1755
+ var XDG_DIR_NAME = "codelia";
1756
+ var CONFIG_FILENAME = "config.json";
1757
+ var CREDENTIALS_DIRNAME = "credentials";
1758
+ var AUTH_FILENAME = "auth.json";
1759
+ var MCP_AUTH_FILENAME = "mcp-auth.json";
1760
+ var AUTH_STATE_FILENAME = "storage-state.json";
1761
+ var PROJECTS_FILENAME = "projects.json";
1762
+ var CACHE_DIRNAME = "cache";
1763
+ var TOOL_OUTPUT_CACHE_DIRNAME = "tool-output";
1764
+ var SESSIONS_DIRNAME = "sessions";
1765
+ var LOGS_DIRNAME = "logs";
1766
+ function resolveStoragePaths(options = {}) {
1767
+ if (options.rootOverride) {
1768
+ return buildHomeLayout(options.rootOverride);
1769
+ }
1770
+ const layoutValue = options.layout ?? process.env[LAYOUT_ENV];
1771
+ const layout = normalizeLayout(layoutValue);
1772
+ if (layout === "xdg") {
1773
+ return buildXdgLayout();
1774
+ }
1775
+ return buildHomeLayout(defaultHomeRoot());
1776
+ }
1777
+ async function ensureStorageDirs(paths) {
1778
+ await Promise.all([
1779
+ (0, import_promises4.mkdir)(paths.configDir, { recursive: true }),
1780
+ (0, import_promises4.mkdir)(paths.cacheDir, { recursive: true }),
1781
+ (0, import_promises4.mkdir)(paths.toolOutputCacheDir, { recursive: true }),
1782
+ (0, import_promises4.mkdir)(paths.sessionsDir, { recursive: true }),
1783
+ (0, import_promises4.mkdir)(paths.logsDir, { recursive: true })
1784
+ ]);
1785
+ }
1786
+ function resolveDefaultHomeConfigDir(home = import_node_os2.default.homedir(), layoutValue = process.env[LAYOUT_ENV]) {
1787
+ const layout = normalizeLayout(layoutValue);
1788
+ return layout === "xdg" ? import_node_path6.default.join(home, ".config", XDG_DIR_NAME) : import_node_path6.default.join(home, DEFAULT_ROOT_DIR);
1789
+ }
1790
+ function normalizeLayout(value) {
1791
+ if (value && value.toLowerCase() === "xdg") return "xdg";
1792
+ return "home";
1793
+ }
1794
+ function defaultHomeRoot() {
1795
+ return import_node_path6.default.join(import_node_os2.default.homedir(), DEFAULT_ROOT_DIR);
1796
+ }
1797
+ function buildHomeLayout(root) {
1798
+ const configDir = root;
1799
+ const credentialsDir = import_node_path6.default.join(configDir, CREDENTIALS_DIRNAME);
1800
+ return {
1801
+ root,
1802
+ configDir,
1803
+ configFile: import_node_path6.default.join(configDir, CONFIG_FILENAME),
1804
+ credentialsDir,
1805
+ authFile: import_node_path6.default.join(credentialsDir, AUTH_FILENAME),
1806
+ mcpAuthFile: import_node_path6.default.join(credentialsDir, MCP_AUTH_FILENAME),
1807
+ legacyAuthFile: import_node_path6.default.join(configDir, AUTH_FILENAME),
1808
+ legacyMcpAuthFile: import_node_path6.default.join(configDir, MCP_AUTH_FILENAME),
1809
+ authStateFile: import_node_path6.default.join(credentialsDir, AUTH_STATE_FILENAME),
1810
+ projectsFile: import_node_path6.default.join(configDir, PROJECTS_FILENAME),
1811
+ cacheDir: import_node_path6.default.join(root, CACHE_DIRNAME),
1812
+ toolOutputCacheDir: import_node_path6.default.join(
1813
+ root,
1814
+ CACHE_DIRNAME,
1815
+ TOOL_OUTPUT_CACHE_DIRNAME
1816
+ ),
1817
+ sessionsDir: import_node_path6.default.join(root, SESSIONS_DIRNAME),
1818
+ logsDir: import_node_path6.default.join(root, LOGS_DIRNAME)
1819
+ };
1820
+ }
1821
+ function buildXdgLayout() {
1822
+ const home = import_node_os2.default.homedir();
1823
+ const configRoot = process.env.XDG_CONFIG_HOME ?? import_node_path6.default.join(home, ".config");
1824
+ const cacheRoot = process.env.XDG_CACHE_HOME ?? import_node_path6.default.join(home, ".cache");
1825
+ const stateRoot = process.env.XDG_STATE_HOME ?? import_node_path6.default.join(home, ".local", "state");
1826
+ const configDir = import_node_path6.default.join(configRoot, XDG_DIR_NAME);
1827
+ const credentialsDir = import_node_path6.default.join(configDir, CREDENTIALS_DIRNAME);
1828
+ const cacheDir = import_node_path6.default.join(cacheRoot, XDG_DIR_NAME);
1829
+ const stateDir = import_node_path6.default.join(stateRoot, XDG_DIR_NAME);
1830
+ return {
1831
+ root: stateDir,
1832
+ configDir,
1833
+ configFile: import_node_path6.default.join(configDir, CONFIG_FILENAME),
1834
+ credentialsDir,
1835
+ authFile: import_node_path6.default.join(credentialsDir, AUTH_FILENAME),
1836
+ mcpAuthFile: import_node_path6.default.join(credentialsDir, MCP_AUTH_FILENAME),
1837
+ legacyAuthFile: import_node_path6.default.join(configDir, AUTH_FILENAME),
1838
+ legacyMcpAuthFile: import_node_path6.default.join(configDir, MCP_AUTH_FILENAME),
1839
+ authStateFile: import_node_path6.default.join(credentialsDir, AUTH_STATE_FILENAME),
1840
+ projectsFile: import_node_path6.default.join(configDir, PROJECTS_FILENAME),
1841
+ cacheDir,
1842
+ toolOutputCacheDir: import_node_path6.default.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
1843
+ sessionsDir: import_node_path6.default.join(stateDir, SESSIONS_DIRNAME),
1844
+ logsDir: import_node_path6.default.join(stateDir, LOGS_DIRNAME)
1845
+ };
1846
+ }
1847
+
1848
+ // src/credential-backend.ts
1849
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1850
+ var probeUnavailableError = (probe, message = probe.message) => new KeychainError(
1851
+ probe.reason === "keychain_locked" ? "keychain_locked" : "keychain_unavailable",
1852
+ message
1853
+ );
1854
+ var buildSteadyState = (activeBackend, mcpReauthRequired) => ({
1855
+ version: 1,
1856
+ status: "steady",
1857
+ active_backend: activeBackend,
1858
+ ...mcpReauthRequired?.length ? { mcp_reauth_required: [...mcpReauthRequired] } : {}
1859
+ });
1860
+ var isKeyringOwnedOrTargeting = (state) => state?.active_backend === "keyring" || state?.status === "migrating" && state.target_backend === "keyring";
1861
+ var isKeyringInvolved = (state) => isKeyringOwnedOrTargeting(state) || state?.status === "migrating" && state.cleanup_pending?.source_backend === "keyring";
1862
+ var parseStorageModeValue = (value) => {
1863
+ if (value === "auto" || value === "keyring" || value === "file") {
1864
+ return value;
1865
+ }
1866
+ return void 0;
1867
+ };
1868
+ var resolveConfiguredAuthStorageMode = (paths, overrideMode) => {
1869
+ if (overrideMode) return overrideMode;
1870
+ const envRaw = process.env.CODELIA_AUTH_STORAGE?.trim();
1871
+ if (envRaw) {
1872
+ const parsed = parseStorageModeValue(envRaw);
1873
+ if (!parsed) {
1874
+ throw new Error(
1875
+ `Invalid CODELIA_AUTH_STORAGE="${envRaw}" (expected "auto", "keyring", or "file")`
1876
+ );
1877
+ }
1878
+ return parsed;
1879
+ }
1880
+ const globalConfigPath = process.env.CODELIA_CONFIG_PATH?.trim() ? import_node_path7.default.resolve(process.env.CODELIA_CONFIG_PATH.trim()) : paths.configFile;
1881
+ try {
1882
+ const raw = (0, import_node_fs8.readFileSync)(globalConfigPath, "utf8");
1883
+ const parsed = JSON.parse(raw);
1884
+ if (isRecord3(parsed) && isRecord3(parsed.auth)) {
1885
+ const mode = parsed.auth.storage;
1886
+ if (mode !== void 0) {
1887
+ const valid = parseStorageModeValue(mode);
1888
+ if (!valid) {
1889
+ throw new Error(
1890
+ `Invalid global auth.storage="${String(mode)}" (expected "auto", "keyring", or "file")`
1891
+ );
1892
+ }
1893
+ return valid;
1894
+ }
1895
+ }
1896
+ } catch (error) {
1897
+ if (error?.code !== "ENOENT") {
1898
+ if (error instanceof Error && error.message.startsWith("Invalid global auth.storage")) {
1899
+ throw error;
1900
+ }
1901
+ }
1902
+ }
1903
+ return "auto";
1904
+ };
1905
+ var readTextIfPresent = async (filePath, legacy = false) => {
1906
+ if (!await verifyWindowsCredentialFileAcl(filePath, legacy)) return null;
1907
+ try {
1908
+ return await import_node_fs8.promises.readFile(filePath, "utf8");
1909
+ } catch (error) {
1910
+ if (error?.code === "ENOENT") return null;
1911
+ throw error;
1912
+ }
1913
+ };
1914
+ var readFileSlot = async (filePath, adapter, legacy = false) => {
1915
+ const text = await readTextIfPresent(filePath, legacy);
1916
+ if (text === null) {
1917
+ return { present: false, normalized: adapter.empty(), nonEmpty: false };
1918
+ }
1919
+ const parsed = adapter.parse(text);
1920
+ return {
1921
+ present: true,
1922
+ normalized: parsed.normalized,
1923
+ nonEmpty: adapter.isNonEmpty(parsed.normalized),
1924
+ sourceVersion: parsed.sourceVersion,
1925
+ extraWarnings: parsed.extraWarnings
1926
+ };
1927
+ };
1928
+ var readKeychainSlot = async (keychain, service, account, adapter) => {
1929
+ const text = await keychain.get(service, account);
1930
+ if (text === null) {
1931
+ return { present: false, normalized: adapter.empty(), nonEmpty: false };
1932
+ }
1933
+ const parsed = adapter.parse(text);
1934
+ return {
1935
+ present: true,
1936
+ normalized: parsed.normalized,
1937
+ nonEmpty: adapter.isNonEmpty(parsed.normalized)
1938
+ };
1939
+ };
1940
+ var unlinkIfPresent = async (filePath) => {
1941
+ try {
1942
+ await import_node_fs8.promises.unlink(filePath);
1943
+ } catch (error) {
1944
+ if (error?.code === "ENOENT") return;
1945
+ throw error;
1946
+ }
1947
+ };
1948
+ var makeKeychainTargetSlot = (keychain, account, adapter, sourcePath) => ({
1949
+ name: adapter.name,
1950
+ readSource: () => readFileSlot(sourcePath, adapter),
1951
+ readDest: () => readKeychainSlot(keychain, adapter.service, account, adapter),
1952
+ writeDest: async (normalized) => {
1953
+ await keychain.set(adapter.service, account, JSON.stringify(normalized));
1954
+ },
1955
+ verifyDest: async (expected) => {
1956
+ const back = await readKeychainSlot(
1957
+ keychain,
1958
+ adapter.service,
1959
+ account,
1960
+ adapter
1961
+ );
1962
+ return back.present && canonicalJsonEqual(back.normalized, expected);
1963
+ },
1964
+ cleanupSource: () => unlinkIfPresent(sourcePath)
1965
+ });
1966
+ var makeFileDestHandlers = (paths, adapter) => {
1967
+ const destPath = adapter.filePath(paths);
1968
+ return {
1969
+ readDest: () => readFileSlot(destPath, adapter),
1970
+ writeDest: async (normalized) => {
1971
+ await ensureStorageDirs(paths);
1972
+ await writeFileAtomic(destPath, JSON.stringify(normalized, null, 2), {
1973
+ mode: 384
1974
+ });
1975
+ },
1976
+ verifyDest: async (expected) => {
1977
+ const back = await readFileSlot(destPath, adapter);
1978
+ return back.present && canonicalJsonEqual(back.normalized, expected);
1979
+ }
1980
+ };
1981
+ };
1982
+ var makeFileFromKeychainSlot = (paths, keychain, account, adapter) => ({
1983
+ name: adapter.name,
1984
+ readSource: () => readKeychainSlot(keychain, adapter.service, account, adapter),
1985
+ ...makeFileDestHandlers(paths, adapter),
1986
+ cleanupSource: async () => {
1987
+ await keychain.delete(adapter.service, account);
1988
+ }
1989
+ });
1990
+ var makeFileFromLegacySlot = (paths, adapter) => {
1991
+ const sourcePath = adapter.legacyFilePath(paths);
1992
+ return {
1993
+ name: adapter.name,
1994
+ readSource: () => readFileSlot(sourcePath, adapter, true),
1995
+ ...makeFileDestHandlers(paths, adapter),
1996
+ cleanupSource: () => unlinkIfPresent(sourcePath)
1997
+ };
1998
+ };
1999
+ var completePendingCleanupUnlocked = async (options) => {
2000
+ const pending = options.state.cleanup_pending;
2001
+ if (!pending) return options.state;
2002
+ if (pending.source_backend === "keyring" && options.state.target_backend === "file") {
2003
+ const probe = await options.keychain.probe();
2004
+ if (!probe.available) {
2005
+ throw probeUnavailableError(
2006
+ probe,
2007
+ `Cannot finish cleanup of previous Keychain credentials after migration while Keychain is unavailable (${probe.reason}): ${probe.message}`
2008
+ );
2009
+ }
2010
+ if (pending.auth) {
2011
+ await options.keychain.delete(
2012
+ options.authAdapter.service,
2013
+ options.account
2014
+ );
2015
+ }
2016
+ if (pending.mcp_auth) {
2017
+ await options.keychain.delete(
2018
+ options.mcpAdapter.service,
2019
+ options.account
2020
+ );
2021
+ }
2022
+ } else if (pending.source_backend === "legacy_file") {
2023
+ if (pending.auth) {
2024
+ await unlinkIfPresent(options.authAdapter.legacyFilePath(options.paths));
2025
+ }
2026
+ if (pending.mcp_auth) {
2027
+ await unlinkIfPresent(options.mcpAdapter.legacyFilePath(options.paths));
2028
+ }
2029
+ } else {
2030
+ const isLegacyCleanup = options.state.target_backend !== "keyring";
2031
+ const cleanupAuthPath = isLegacyCleanup ? options.authAdapter.legacyFilePath(options.paths) : options.authAdapter.filePath(options.paths);
2032
+ const cleanupMcpPath = isLegacyCleanup ? options.mcpAdapter.legacyFilePath(options.paths) : options.mcpAdapter.filePath(options.paths);
2033
+ if (pending.auth) {
2034
+ await unlinkIfPresent(cleanupAuthPath);
2035
+ }
2036
+ if (pending.mcp_auth) {
2037
+ await unlinkIfPresent(cleanupMcpPath);
2038
+ }
2039
+ }
2040
+ const committed = buildSteadyState(
2041
+ options.state.target_backend,
2042
+ options.state.mcp_reauth_required
2043
+ );
2044
+ await writeAuthStorageState(options.paths.authStateFile, committed);
2045
+ return committed;
2046
+ };
2047
+ var coordinateCredentialBackendUnlocked = async (options) => {
2048
+ const { paths, authAdapter, mcpAdapter } = options;
2049
+ const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
2050
+ const configured = resolveConfiguredAuthStorageMode(
2051
+ paths,
2052
+ options.storageMode
2053
+ );
2054
+ const account = keychainAccountForConfigDir(paths.configDir);
2055
+ await ensureStorageDirs(paths);
2056
+ let state = await readAuthStorageState(
2057
+ paths.authStateFile
2058
+ );
2059
+ if (state?.status === "migrating" && state.cleanup_pending) {
2060
+ state = await completePendingCleanupUnlocked({
2061
+ paths,
2062
+ state,
2063
+ keychain,
2064
+ account,
2065
+ authAdapter,
2066
+ mcpAdapter
2067
+ });
2068
+ }
2069
+ const migrateLegacyToCredentials = async () => {
2070
+ const [legacyAuth, legacyMcp] = await Promise.all([
2071
+ readTextIfPresent(authAdapter.legacyFilePath(paths), true),
2072
+ readTextIfPresent(mcpAdapter.legacyFilePath(paths), true)
2073
+ ]);
2074
+ if (legacyAuth === null && legacyMcp === null) return;
2075
+ await runTwoPhaseMigration({
2076
+ stateFile: paths.authStateFile,
2077
+ fromBackend: state?.active_backend ?? "file",
2078
+ toBackend: state?.active_backend ?? "file",
2079
+ cleanupSourceKind: "legacy_file",
2080
+ authSlot: makeFileFromLegacySlot(paths, authAdapter),
2081
+ mcpSlot: makeFileFromLegacySlot(paths, mcpAdapter),
2082
+ existingMcpReauth: state?.mcp_reauth_required
2083
+ });
2084
+ state = await readAuthStorageState(paths.authStateFile);
2085
+ };
2086
+ const keyringOwnedOrInFlight = isKeyringOwnedOrTargeting(state);
2087
+ if (configured === "file") {
2088
+ await migrateLegacyToCredentials();
2089
+ if (keyringOwnedOrInFlight) {
2090
+ const probe2 = await keychain.probe();
2091
+ if (!probe2.available) {
2092
+ throw probeUnavailableError(
2093
+ probe2,
2094
+ `Cannot switch auth.storage to "file" while Keychain is unavailable: ${probe2.message}`
2095
+ );
2096
+ }
2097
+ await runTwoPhaseMigration({
2098
+ stateFile: paths.authStateFile,
2099
+ fromBackend: "keyring",
2100
+ toBackend: "file",
2101
+ authSlot: makeFileFromKeychainSlot(
2102
+ paths,
2103
+ keychain,
2104
+ account,
2105
+ authAdapter
2106
+ ),
2107
+ mcpSlot: makeFileFromKeychainSlot(paths, keychain, account, mcpAdapter),
2108
+ existingMcpReauth: state?.mcp_reauth_required,
2109
+ commitSteadyIfEmpty: true
2110
+ });
2111
+ state = await readAuthStorageState(paths.authStateFile);
2112
+ } else if (!state || state.status === "migrating") {
2113
+ await writeAuthStorageState(
2114
+ paths.authStateFile,
2115
+ buildSteadyState("file", state?.mcp_reauth_required)
2116
+ );
2117
+ }
2118
+ return {
2119
+ configured,
2120
+ active: "file",
2121
+ state: "steady"
2122
+ };
2123
+ }
2124
+ const probe = await keychain.probe();
2125
+ if (!probe.available) {
2126
+ if (configured === "keyring") {
2127
+ throw probeUnavailableError(probe);
2128
+ }
2129
+ if (keyringOwnedOrInFlight) {
2130
+ throw probeUnavailableError(
2131
+ probe,
2132
+ `Credentials are managed in macOS Keychain. ${probe.message}`
2133
+ );
2134
+ }
2135
+ await migrateLegacyToCredentials();
2136
+ return {
2137
+ configured,
2138
+ active: "file",
2139
+ state: "steady",
2140
+ fallbackReason: probe.reason
2141
+ };
2142
+ }
2143
+ await migrateLegacyToCredentials();
2144
+ const [credAuthText, credMcpText] = await Promise.all([
2145
+ readTextIfPresent(authAdapter.filePath(paths)),
2146
+ readTextIfPresent(mcpAdapter.filePath(paths))
2147
+ ]);
2148
+ if (credAuthText !== null || credMcpText !== null || state?.status === "migrating") {
2149
+ await runTwoPhaseMigration({
2150
+ stateFile: paths.authStateFile,
2151
+ fromBackend: "file",
2152
+ toBackend: "keyring",
2153
+ authSlot: makeKeychainTargetSlot(
2154
+ keychain,
2155
+ account,
2156
+ authAdapter,
2157
+ authAdapter.filePath(paths)
2158
+ ),
2159
+ mcpSlot: makeKeychainTargetSlot(
2160
+ keychain,
2161
+ account,
2162
+ mcpAdapter,
2163
+ mcpAdapter.filePath(paths)
2164
+ ),
2165
+ existingMcpReauth: state?.mcp_reauth_required,
2166
+ commitSteadyIfEmpty: true
2167
+ });
2168
+ state = await readAuthStorageState(paths.authStateFile);
2169
+ } else if (state?.active_backend !== "keyring") {
2170
+ await writeAuthStorageState(
2171
+ paths.authStateFile,
2172
+ buildSteadyState("keyring", state?.mcp_reauth_required)
2173
+ );
2174
+ }
2175
+ return {
2176
+ configured,
2177
+ active: "keyring",
2178
+ state: "steady"
2179
+ };
2180
+ };
2181
+ var coordinateCredentialBackend = (options) => {
2182
+ const paths = options.paths ?? resolveStoragePaths();
2183
+ return withAuthStoreLock(
2184
+ authLockPathFor(paths.credentialsDir),
2185
+ () => coordinateCredentialBackendUnlocked({
2186
+ ...options,
2187
+ paths
2188
+ }),
2189
+ options.lock
2190
+ );
2191
+ };
2192
+ var clearStoreAcrossAllLocationsUnlocked = async (options) => {
2193
+ const { paths, adapter } = options;
2194
+ const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
2195
+ const account = keychainAccountForConfigDir(paths.configDir);
2196
+ await ensureStorageDirs(paths);
2197
+ await unlinkIfPresent(adapter.filePath(paths));
2198
+ await unlinkIfPresent(adapter.legacyFilePath(paths));
2199
+ const probe = await keychain.probe();
2200
+ if (probe.available) {
2201
+ await keychain.delete(adapter.service, account);
2202
+ } else {
2203
+ const storedState = await readAuthStorageState(paths.authStateFile).catch(
2204
+ () => null
2205
+ );
2206
+ if (isKeyringInvolved(storedState)) {
2207
+ throw probeUnavailableError(
2208
+ probe,
2209
+ `Cannot clear Keychain credentials while Keychain is unavailable (${probe.reason}): ${probe.message}`
2210
+ );
188
2211
  }
189
- return { ref, ...imageRef ? { imageRef } : {} };
190
2212
  }
191
- async read(attachmentId, sessionId, offset, length) {
192
- const metadata = await this.metadata(attachmentId, sessionId);
193
- if (!metadata) throw new Error("Attachment unavailable in this session");
194
- if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || length > 256 * 1024)
195
- throw new Error("Invalid attachment byte range");
196
- const end = Math.min(offset + length, metadata.ref.byte_size);
197
- if (metadata.imageRef)
198
- return (await this.readImage(metadata)).subarray(offset, end);
199
- const file = await (0, import_promises2.open)(
200
- import_node_path.default.join(this.root, attachmentId, "original"),
201
- import_node_fs2.constants.O_RDONLY | (import_node_fs2.constants.O_NOFOLLOW ?? 0) | (import_node_fs2.constants.O_NONBLOCK ?? 0)
2213
+ };
2214
+ var resolveDefaultTargetBackend = async (configured, keychain) => {
2215
+ if (configured === "file") return "file";
2216
+ if (configured === "keyring") return "keyring";
2217
+ return (await keychain.probe()).available ? "keyring" : "file";
2218
+ };
2219
+ var resolveKeepKeyringStore = async (ctx, adapter) => {
2220
+ const probe = await ctx.keychain.probe();
2221
+ if (!probe.available) {
2222
+ throw probeUnavailableError(
2223
+ probe,
2224
+ `Cannot keep Keychain credentials while Keychain is unavailable: ${probe.message}`
202
2225
  );
203
- try {
204
- const stat = await file.stat();
205
- if (!stat.isFile() || stat.size !== metadata.ref.byte_size)
206
- throw new Error("Attachment original is corrupt");
207
- if (offset >= end) return Buffer.alloc(0);
208
- const firstBlock = Math.floor(offset / BLOCK_BYTES);
209
- const lastBlock = Math.ceil(end / BLOCK_BYTES);
210
- const start = firstBlock * BLOCK_BYTES;
211
- const bytes = Buffer.alloc(
212
- Math.min(lastBlock * BLOCK_BYTES, stat.size) - start
2226
+ }
2227
+ const slot = await readKeychainSlot(
2228
+ ctx.keychain,
2229
+ adapter.service,
2230
+ ctx.account,
2231
+ adapter
2232
+ );
2233
+ const fileSlot = await readFileSlot(
2234
+ adapter.filePath(ctx.paths),
2235
+ adapter
2236
+ ).catch(() => ({ present: true, nonEmpty: true }));
2237
+ const legacySlot = await readFileSlot(
2238
+ adapter.legacyFilePath(ctx.paths),
2239
+ adapter,
2240
+ true
2241
+ ).catch(() => ({ present: true, nonEmpty: true }));
2242
+ if (!slot.present && !fileSlot.present && !legacySlot.present) {
2243
+ return;
2244
+ }
2245
+ if (!slot.present || !slot.nonEmpty && (fileSlot.nonEmpty || legacySlot.nonEmpty)) {
2246
+ throw new Error(
2247
+ `Cannot keep Keychain store for '${adapter.name}': Keychain has no saved credentials`
2248
+ );
2249
+ }
2250
+ await unlinkIfPresent(adapter.filePath(ctx.paths));
2251
+ await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
2252
+ };
2253
+ var resolveKeepFileStore = async (ctx, adapter) => {
2254
+ const slot = await readFileSlot(adapter.filePath(ctx.paths), adapter);
2255
+ if (!slot.present) {
2256
+ throw new Error(
2257
+ `Cannot keep file store for '${adapter.name}': ${adapter.filePath(ctx.paths)} does not exist`
2258
+ );
2259
+ }
2260
+ await writeFileAtomic(
2261
+ adapter.filePath(ctx.paths),
2262
+ JSON.stringify(slot.normalized, null, 2),
2263
+ { mode: 384 }
2264
+ );
2265
+ await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
2266
+ const probe = await ctx.keychain.probe();
2267
+ if (probe.available) {
2268
+ await ctx.keychain.delete(adapter.service, ctx.account);
2269
+ } else if (ctx.existingState?.active_backend === "keyring") {
2270
+ throw probeUnavailableError(
2271
+ probe,
2272
+ `Cannot remove superseded Keychain entry while Keychain is unavailable: ${probe.message}`
2273
+ );
2274
+ }
2275
+ };
2276
+ var resolveKeepLegacyStore = async (ctx, adapter) => {
2277
+ const legacy = await readFileSlot(
2278
+ adapter.legacyFilePath(ctx.paths),
2279
+ adapter,
2280
+ true
2281
+ );
2282
+ if (!legacy.present) {
2283
+ throw new Error(
2284
+ `Cannot keep legacy store for '${adapter.name}': ${adapter.legacyFilePath(ctx.paths)} does not exist`
2285
+ );
2286
+ }
2287
+ const targetBackend = await resolveDefaultTargetBackend(
2288
+ ctx.configured,
2289
+ ctx.keychain
2290
+ );
2291
+ if (targetBackend === "keyring") {
2292
+ const probe2 = await ctx.keychain.probe();
2293
+ if (!probe2.available) {
2294
+ throw probeUnavailableError(
2295
+ probe2,
2296
+ `Cannot promote legacy store to Keychain while Keychain is unavailable: ${probe2.message}`
213
2297
  );
214
- let count = 0;
215
- while (count < bytes.length) {
216
- const result = await file.read(
217
- bytes,
218
- count,
219
- bytes.length - count,
220
- start + count
221
- );
222
- if (!result.bytesRead)
223
- throw new Error("Attachment original is corrupt");
224
- count += result.bytesRead;
225
- }
226
- for (let block = firstBlock; block < lastBlock; block++) {
227
- const beg = (block - firstBlock) * BLOCK_BYTES;
228
- if (metadata.blocks?.[block] !== digest(bytes.subarray(beg, beg + BLOCK_BYTES))) {
229
- throw new Error("Attachment original is corrupt");
230
- }
231
- }
232
- return bytes.subarray(offset - start, end - start);
233
- } finally {
234
- await file.close();
235
2298
  }
236
- }
237
- async metadata(attachmentId, sessionId) {
238
- if (!isAttachmentId(attachmentId)) return null;
239
- const dir = import_node_path.default.join(this.root, attachmentId);
240
- try {
241
- if (!(await (0, import_promises2.lstat)(dir)).isDirectory()) return null;
242
- const metadata = JSON.parse(
243
- (await readImageFileBounded(import_node_path.default.join(dir, "metadata.json"), 64 * 1024)).toString()
2299
+ await ctx.keychain.set(
2300
+ adapter.service,
2301
+ ctx.account,
2302
+ JSON.stringify(legacy.normalized)
2303
+ );
2304
+ const verify = await readKeychainSlot(
2305
+ ctx.keychain,
2306
+ adapter.service,
2307
+ ctx.account,
2308
+ adapter
2309
+ );
2310
+ if (!verify.present || !canonicalJsonEqual(verify.normalized, legacy.normalized)) {
2311
+ throw new Error(
2312
+ `Failed to verify promoted '${adapter.name}' in Keychain`
244
2313
  );
245
- const { ref, imageRef, blocks } = metadata;
246
- if (metadata.sessionId !== sessionId || !UUID.test(metadata.batch) || ref?.attachment_id !== attachmentId)
247
- return null;
248
- if (!Number.isSafeInteger(ref.byte_size) || ref.byte_size < 0 || ref.byte_size > MAX_BYTES || !SHA256.test(ref.sha256) || typeof ref.media_type !== "string" || typeof ref.display_name !== "string")
249
- throw new Error("Invalid attachment metadata");
250
- if (!imageRef && (!Array.isArray(blocks) || blocks.length !== Math.ceil(ref.byte_size / BLOCK_BYTES)))
251
- throw new Error("Invalid attachment block index");
252
- const marker = import_node_path.default.join(this.root, "committed", metadata.batch);
253
- return (await (0, import_promises2.lstat)(marker)).isFile() ? metadata : null;
254
- } catch (error) {
255
- if (error.code === "ENOENT") return null;
256
- throw error;
257
2314
  }
2315
+ await unlinkIfPresent(adapter.filePath(ctx.paths));
2316
+ await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
2317
+ return;
258
2318
  }
259
- async readImage({
260
- ref,
261
- imageRef,
262
- sessionId
263
- }) {
264
- if (!imageRef || imageRef.sha256 !== ref.sha256 || imageRef.byte_size !== ref.byte_size || imageRef.media_type !== ref.media_type || imageRef.width !== ref.width || imageRef.height !== ref.height)
265
- throw new Error("Invalid image attachment reference");
266
- const { metadata, bytes } = await this.images.read(
267
- imageRef.artifact_id,
268
- sessionId
269
- );
270
- if (metadata.kind !== "attachment" || metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size || metadata.media_type !== ref.media_type || metadata.width !== ref.width || metadata.height !== ref.height)
271
- throw new Error("Image attachment original is corrupt");
272
- return bytes;
2319
+ await writeFileAtomic(
2320
+ adapter.filePath(ctx.paths),
2321
+ JSON.stringify(legacy.normalized, null, 2),
2322
+ { mode: 384 }
2323
+ );
2324
+ await unlinkIfPresent(adapter.legacyFilePath(ctx.paths));
2325
+ const probe = await ctx.keychain.probe();
2326
+ if (probe.available) {
2327
+ await ctx.keychain.delete(adapter.service, ctx.account);
2328
+ }
2329
+ };
2330
+ var resolveCredentialConflict = async (options) => {
2331
+ const paths = options.paths ?? resolveStoragePaths();
2332
+ const keychain = options.keychain ?? new MacOsKeychainClient({ credentialsDir: paths.credentialsDir });
2333
+ const account = keychainAccountForConfigDir(paths.configDir);
2334
+ const targets = options.stores?.length ? [...new Set(options.stores)] : ["auth", "mcp_auth"];
2335
+ return withAuthStoreLock(
2336
+ authLockPathFor(paths.credentialsDir),
2337
+ async () => {
2338
+ await ensureStorageDirs(paths);
2339
+ const configured = resolveConfiguredAuthStorageMode(
2340
+ paths,
2341
+ options.storageMode
2342
+ );
2343
+ const existingState = await readAuthStorageState(
2344
+ paths.authStateFile
2345
+ ).catch(() => null);
2346
+ const ctx = {
2347
+ paths,
2348
+ keychain,
2349
+ account,
2350
+ configured,
2351
+ existingState
2352
+ };
2353
+ const resolveOne = async (adapter) => {
2354
+ switch (options.strategy) {
2355
+ case "clear_all":
2356
+ await clearStoreAcrossAllLocationsUnlocked({
2357
+ paths,
2358
+ adapter,
2359
+ keychain
2360
+ });
2361
+ return;
2362
+ case "keep_keyring":
2363
+ await resolveKeepKeyringStore(ctx, adapter);
2364
+ return;
2365
+ case "keep_file":
2366
+ await resolveKeepFileStore(ctx, adapter);
2367
+ return;
2368
+ case "keep_legacy":
2369
+ await resolveKeepLegacyStore(ctx, adapter);
2370
+ return;
2371
+ }
2372
+ };
2373
+ for (const storeName of targets) {
2374
+ if (storeName === "auth") {
2375
+ await resolveOne(options.authAdapter);
2376
+ } else {
2377
+ await resolveOne(options.mcpAdapter);
2378
+ }
2379
+ }
2380
+ const targetActive = options.strategy === "keep_keyring" ? "keyring" : options.strategy === "keep_file" ? "file" : await resolveDefaultTargetBackend(configured, keychain);
2381
+ await writeAuthStorageState(
2382
+ paths.authStateFile,
2383
+ buildSteadyState(targetActive, existingState?.mcp_reauth_required)
2384
+ );
2385
+ return { active: targetActive, resolvedStores: targets };
2386
+ },
2387
+ options.lock
2388
+ );
2389
+ };
2390
+ var inspectCredentialStorageStatus = async (options) => {
2391
+ const paths = options.paths ?? resolveStoragePaths();
2392
+ const keychain = options.keychain ?? new MacOsKeychainClient({
2393
+ credentialsDir: paths.credentialsDir
2394
+ });
2395
+ const configured = resolveConfiguredAuthStorageMode(
2396
+ paths,
2397
+ options.storageMode
2398
+ );
2399
+ const account = keychainAccountForConfigDir(paths.configDir);
2400
+ let stateCorrupt = false;
2401
+ let storedState = null;
2402
+ try {
2403
+ storedState = await readAuthStorageState(paths.authStateFile);
2404
+ } catch {
2405
+ stateCorrupt = true;
2406
+ }
2407
+ const mcpReauthRequired = storedState?.mcp_reauth_required ?? [];
2408
+ const keyringOwned = isKeyringInvolved(storedState);
2409
+ const shouldProbeKeychain = configured !== "file" || keyringOwned;
2410
+ const probe = shouldProbeKeychain ? await keychain.probe() : {
2411
+ available: false,
2412
+ reason: "keychain_unavailable",
2413
+ message: "file mode selected"
2414
+ };
2415
+ const inspectStore = async (adapter) => {
2416
+ let issue;
2417
+ const inspectKeychain = async () => {
2418
+ if (!probe.available) {
2419
+ if (keyringOwned || configured === "keyring") {
2420
+ issue = probe.reason === "keychain_locked" ? "keychain_locked" : "keychain_unavailable";
2421
+ }
2422
+ return null;
2423
+ }
2424
+ try {
2425
+ return await readKeychainSlot(
2426
+ keychain,
2427
+ adapter.service,
2428
+ account,
2429
+ adapter
2430
+ );
2431
+ } catch (error) {
2432
+ if (!(error instanceof KeychainError)) throw error;
2433
+ issue = error.code === "keychain_locked" || error.code === "keychain_access_denied" ? error.code : "keychain_unavailable";
2434
+ return null;
2435
+ }
2436
+ };
2437
+ const [current, legacy, native] = await Promise.all([
2438
+ readFileSlot(adapter.filePath(paths), adapter),
2439
+ readFileSlot(adapter.legacyFilePath(paths), adapter, true),
2440
+ inspectKeychain()
2441
+ ]);
2442
+ const file = current.nonEmpty ? current : legacy;
2443
+ const conflict = current.nonEmpty && legacy.nonEmpty && !canonicalJsonEqual(current.normalized, legacy.normalized) || file.nonEmpty && native?.nonEmpty && !canonicalJsonEqual(file.normalized, native.normalized);
2444
+ return { file, native, conflict, issue };
2445
+ };
2446
+ const [auth, mcp] = await Promise.all([
2447
+ inspectStore(options.authAdapter).catch(() => null),
2448
+ inspectStore(options.mcpAdapter).catch(() => null)
2449
+ ]);
2450
+ const keychainIssue = auth?.issue ?? mcp?.issue;
2451
+ const unreadableStores = [];
2452
+ if (!auth) unreadableStores.push("auth");
2453
+ if (!mcp) unreadableStores.push("mcp_auth");
2454
+ if (stateCorrupt) unreadableStores.push("storage_state");
2455
+ const conflictStores = [];
2456
+ if (auth?.conflict) conflictStores.push("auth");
2457
+ if (mcp?.conflict) conflictStores.push("mcp_auth");
2458
+ const state = stateCorrupt || conflictStores.length > 0 ? "conflict" : storedState?.status ?? "steady";
2459
+ const active = storedState?.active_backend ?? (auth?.file.nonEmpty || mcp?.file.nonEmpty ? "file" : probe.available || configured === "keyring" ? "keyring" : "file");
2460
+ const fallbackReason = configured === "auto" && active === "file" && !probe.available ? probe.reason : void 0;
2461
+ if (state === "steady" && auth && !auth.issue) {
2462
+ const snapshot = active === "file" ? auth.file : auth.native;
2463
+ if (snapshot?.nonEmpty) options.onReadableAuth?.(snapshot.normalized);
273
2464
  }
2465
+ return {
2466
+ configured,
2467
+ active,
2468
+ state,
2469
+ ...fallbackReason ? { fallbackReason } : {},
2470
+ mcpReauthRequired,
2471
+ conflictStores,
2472
+ unreadableStores,
2473
+ ...keychainIssue ? { keychainIssue } : {}
2474
+ };
274
2475
  };
275
2476
 
276
2477
  // src/image-artifacts.ts
277
- var import_node_crypto4 = require("crypto");
278
- var import_promises4 = require("fs/promises");
279
- var import_node_path3 = __toESM(require("path"), 1);
2478
+ var import_node_crypto7 = require("crypto");
2479
+ var import_promises6 = require("fs/promises");
2480
+ var import_node_path9 = __toESM(require("path"), 1);
280
2481
 
281
2482
  // src/image-attachment.ts
282
2483
  var import_image_size = require("image-size");
283
2484
 
284
2485
  // src/image-png.ts
285
- var import_node_util = require("util");
2486
+ var import_node_util2 = require("util");
286
2487
  var import_node_zlib = require("zlib");
287
2488
  var IMAGE_MAX_BYTES = 32 * 1024 * 1024;
288
2489
  var IMAGE_MAX_SIDE = 12288;
289
2490
  var IMAGE_MAX_PIXELS = 2e7;
290
- var inflateAsync = (0, import_node_util.promisify)(import_node_zlib.inflate);
2491
+ var inflateAsync = (0, import_node_util2.promisify)(import_node_zlib.inflate);
291
2492
  var crcTable = Uint32Array.from({ length: 256 }, (_, n) => {
292
2493
  let c = n;
293
2494
  for (let i = 0; i < 8; i++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
@@ -457,22 +2658,22 @@ function parseImageMetadata(value) {
457
2658
  }
458
2659
 
459
2660
  // src/image-model-view.ts
460
- var import_node_crypto3 = require("crypto");
461
- var import_promises3 = require("fs/promises");
462
- var import_node_path2 = __toESM(require("path"), 1);
2661
+ var import_node_crypto6 = require("crypto");
2662
+ var import_promises5 = require("fs/promises");
2663
+ var import_node_path8 = __toESM(require("path"), 1);
463
2664
  var import_shared_types2 = require("@codelia/shared-types");
464
2665
  var import_image_size2 = require("image-size");
465
2666
  var VERSION = "jpeg-q90-444-v1";
466
- var directory = (root) => import_node_path2.default.join(root, VERSION);
2667
+ var directory = (root) => import_node_path8.default.join(root, VERSION);
467
2668
  var errorCode = (error) => error && typeof error === "object" && "code" in error ? error.code : void 0;
468
2669
  async function readModelView(root, original, expected) {
469
2670
  if (expected !== void 0 && !(0, import_shared_types2.isImageModelView)(expected))
470
2671
  throw new Error("Invalid image model view");
471
2672
  const dir = directory(root);
472
- if (!(await (0, import_promises3.lstat)(dir)).isDirectory())
2673
+ if (!(await (0, import_promises5.lstat)(dir)).isDirectory())
473
2674
  throw new Error("Invalid model view directory");
474
2675
  const record2 = JSON.parse(
475
- (await readImageFileBounded(import_node_path2.default.join(dir, "metadata.json"), 4096)).toString()
2676
+ (await readImageFileBounded(import_node_path8.default.join(dir, "metadata.json"), 4096)).toString()
476
2677
  );
477
2678
  if (!record2 || record2.original_sha256 !== original.sha256 || !(0, import_shared_types2.isImageModelView)(record2.view))
478
2679
  throw new Error("Invalid model view metadata");
@@ -480,7 +2681,7 @@ async function readModelView(root, original, expected) {
480
2681
  if (expected && (view.sha256 !== expected.sha256 || view.byte_size !== expected.byte_size))
481
2682
  throw new Error("Image model view reference mismatch");
482
2683
  const bytes = await readImageFileBounded(
483
- import_node_path2.default.join(dir, "view.jpg"),
2684
+ import_node_path8.default.join(dir, "view.jpg"),
484
2685
  32 * 1024 * 1024
485
2686
  );
486
2687
  const dims = (0, import_image_size2.imageSize)(bytes);
@@ -493,7 +2694,7 @@ async function prepareModelView(root, original, bytes) {
493
2694
  return void 0;
494
2695
  let exists = true;
495
2696
  try {
496
- await (0, import_promises3.lstat)(directory(root));
2697
+ await (0, import_promises5.lstat)(directory(root));
497
2698
  } catch (error) {
498
2699
  if (errorCode(error) !== "ENOENT") throw error;
499
2700
  exists = false;
@@ -515,27 +2716,27 @@ async function prepareModelView(root, original, bytes) {
515
2716
  sha256: imageHash(jpeg),
516
2717
  byte_size: jpeg.length
517
2718
  };
518
- const temporary = import_node_path2.default.join(root, `.model-view-${(0, import_node_crypto3.randomUUID)()}`);
519
- await (0, import_promises3.mkdir)(temporary, { mode: 448 });
2719
+ const temporary = import_node_path8.default.join(root, `.model-view-${(0, import_node_crypto6.randomUUID)()}`);
2720
+ await (0, import_promises5.mkdir)(temporary, { mode: 448 });
520
2721
  try {
521
- await (0, import_promises3.writeFile)(import_node_path2.default.join(temporary, "view.jpg"), jpeg, {
2722
+ await (0, import_promises5.writeFile)(import_node_path8.default.join(temporary, "view.jpg"), jpeg, {
522
2723
  flag: "wx",
523
2724
  mode: 384
524
2725
  });
525
- await (0, import_promises3.writeFile)(
526
- import_node_path2.default.join(temporary, "metadata.json"),
2726
+ await (0, import_promises5.writeFile)(
2727
+ import_node_path8.default.join(temporary, "metadata.json"),
527
2728
  JSON.stringify({ original_sha256: original.sha256, view }),
528
2729
  { flag: "wx", mode: 384 }
529
2730
  );
530
2731
  try {
531
- await (0, import_promises3.rename)(temporary, directory(root));
2732
+ await (0, import_promises5.rename)(temporary, directory(root));
532
2733
  } catch (error) {
533
2734
  if (!["EEXIST", "ENOTEMPTY"].includes(String(errorCode(error))))
534
2735
  throw error;
535
2736
  }
536
2737
  return (await readModelView(root, original)).view;
537
2738
  } finally {
538
- await (0, import_promises3.rm)(temporary, { recursive: true, force: true });
2739
+ await (0, import_promises5.rm)(temporary, { recursive: true, force: true });
539
2740
  }
540
2741
  }
541
2742
 
@@ -552,7 +2753,7 @@ var ImageArtifactStore = class {
552
2753
  const dimensions = mediaType === "image/png" ? await validateImagePng(bytes) : validateImageAttachment(bytes, "image/jpeg");
553
2754
  if (mediaType === "image/jpeg" && (bytes.at(-2) !== 255 || bytes.at(-1) !== 217))
554
2755
  throw new Error("Invalid generated JPEG: missing end marker");
555
- const artifact_id = `codelia-image-${(0, import_node_crypto4.randomUUID)()}`;
2756
+ const artifact_id = `codelia-image-${(0, import_node_crypto7.randomUUID)()}`;
556
2757
  const metadata = parseImageMetadata({
557
2758
  ...provenance,
558
2759
  ...dimensions,
@@ -568,7 +2769,7 @@ var ImageArtifactStore = class {
568
2769
  return metadata;
569
2770
  }
570
2771
  async saveAttachment(bytes, mediaType, {
571
- artifactId = `codelia-image-${(0, import_node_crypto4.randomUUID)()}`,
2772
+ artifactId = `codelia-image-${(0, import_node_crypto7.randomUUID)()}`,
572
2773
  ownerSessionId
573
2774
  } = {}) {
574
2775
  if (!ID2.test(artifactId)) throw new Error("Invalid image artifact id");
@@ -602,50 +2803,50 @@ var ImageArtifactStore = class {
602
2803
  const { metadata } = await this.read(ref.artifact_id, sessionId);
603
2804
  if (metadata.kind !== "attachment" || metadata.sha256 !== ref.sha256 || metadata.byte_size !== ref.byte_size)
604
2805
  throw new Error("Image attachment rollback reference mismatch");
605
- await (0, import_promises4.rm)(import_node_path3.default.join(this.root, ref.artifact_id), { recursive: true });
2806
+ await (0, import_promises6.rm)(import_node_path9.default.join(this.root, ref.artifact_id), { recursive: true });
606
2807
  }
607
2808
  async persist(bytes, metadata, ownerSessionId) {
608
- await (0, import_promises4.mkdir)(this.root, { recursive: true, mode: 448 });
609
- const temporary = import_node_path3.default.join(this.root, `.pending-${(0, import_node_crypto4.randomUUID)()}`);
610
- await (0, import_promises4.mkdir)(temporary, { mode: 448 });
2809
+ await (0, import_promises6.mkdir)(this.root, { recursive: true, mode: 448 });
2810
+ const temporary = import_node_path9.default.join(this.root, `.pending-${(0, import_node_crypto7.randomUUID)()}`);
2811
+ await (0, import_promises6.mkdir)(temporary, { mode: 448 });
611
2812
  try {
612
- await (0, import_promises4.writeFile)(
613
- import_node_path3.default.join(temporary, imageOriginalFilename(metadata.media_type)),
2813
+ await (0, import_promises6.writeFile)(
2814
+ import_node_path9.default.join(temporary, imageOriginalFilename(metadata.media_type)),
614
2815
  bytes,
615
2816
  {
616
2817
  flag: "wx",
617
2818
  mode: 384
618
2819
  }
619
2820
  );
620
- await (0, import_promises4.writeFile)(
621
- import_node_path3.default.join(temporary, "metadata.json"),
2821
+ await (0, import_promises6.writeFile)(
2822
+ import_node_path9.default.join(temporary, "metadata.json"),
622
2823
  JSON.stringify({
623
2824
  ...metadata,
624
2825
  ...ownerSessionId !== void 0 ? { owner_session_id: ownerSessionId } : {}
625
2826
  }),
626
2827
  { flag: "wx", mode: 384 }
627
2828
  );
628
- await (0, import_promises4.rename)(temporary, import_node_path3.default.join(this.root, metadata.artifact_id));
2829
+ await (0, import_promises6.rename)(temporary, import_node_path9.default.join(this.root, metadata.artifact_id));
629
2830
  } catch (error) {
630
- await (0, import_promises4.rm)(temporary, { recursive: true, force: true });
2831
+ await (0, import_promises6.rm)(temporary, { recursive: true, force: true });
631
2832
  throw error;
632
2833
  }
633
2834
  }
634
2835
  async read(artifactId, sessionId = this.getSessionId?.() ?? null) {
635
2836
  if (!ID2.test(artifactId)) throw new Error("Invalid image artifact id");
636
2837
  try {
637
- const dir = import_node_path3.default.join(this.root, artifactId);
638
- if (!(await (0, import_promises4.lstat)(dir)).isDirectory())
2838
+ const dir = import_node_path9.default.join(this.root, artifactId);
2839
+ if (!(await (0, import_promises6.lstat)(dir)).isDirectory())
639
2840
  throw new Error("Invalid artifact directory");
640
2841
  const rawMetadata = JSON.parse(
641
- (await readImageFileBounded(import_node_path3.default.join(dir, "metadata.json"), 16384)).toString()
2842
+ (await readImageFileBounded(import_node_path9.default.join(dir, "metadata.json"), 16384)).toString()
642
2843
  );
643
2844
  const metadata = parseImageMetadata(rawMetadata);
644
2845
  const owner = rawMetadata.owner_session_id;
645
2846
  if (owner !== void 0 && (metadata.kind !== "attachment" || typeof owner !== "string" || !owner || owner !== sessionId))
646
2847
  throw new Error("Image artifact owned by another session");
647
2848
  const bytes = await readImageFileBounded(
648
- import_node_path3.default.join(dir, imageOriginalFilename(metadata.media_type)),
2849
+ import_node_path9.default.join(dir, imageOriginalFilename(metadata.media_type)),
649
2850
  IMAGE_MAX_BYTES
650
2851
  );
651
2852
  const dims = metadata.kind === "attachment" ? validateImageAttachment(bytes, metadata.media_type) : metadata.media_type === "image/png" ? await validateImagePng(bytes) : validateImageAttachment(bytes, "image/jpeg");
@@ -674,7 +2875,7 @@ var ImageArtifactStore = class {
674
2875
  };
675
2876
  if (original) return ref;
676
2877
  const model_view = await prepareModelView(
677
- import_node_path3.default.join(this.root, artifactId),
2878
+ import_node_path9.default.join(this.root, artifactId),
678
2879
  metadata,
679
2880
  bytes
680
2881
  );
@@ -685,7 +2886,7 @@ var ImageArtifactStore = class {
685
2886
  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)
686
2887
  throw new Error("Image artifact reference mismatch");
687
2888
  const input = ref.model_view !== void 0 ? await readModelView(
688
- import_node_path3.default.join(this.root, ref.artifact_id),
2889
+ import_node_path9.default.join(this.root, ref.artifact_id),
689
2890
  metadata,
690
2891
  ref.model_view
691
2892
  ) : { bytes, view: metadata };
@@ -700,98 +2901,84 @@ var ImageArtifactStore = class {
700
2901
  };
701
2902
 
702
2903
  // src/mcp-auth-store.ts
703
- var import_node_fs3 = require("fs");
704
-
705
- // src/paths.ts
706
- var import_promises5 = require("fs/promises");
707
- var import_node_os = __toESM(require("os"), 1);
708
- var import_node_path4 = __toESM(require("path"), 1);
709
- var DEFAULT_ROOT_DIR = ".codelia";
710
- var LAYOUT_ENV = "CODELIA_LAYOUT";
711
- var XDG_DIR_NAME = "codelia";
712
- var CONFIG_FILENAME = "config.json";
713
- var AUTH_FILENAME = "auth.json";
714
- var MCP_AUTH_FILENAME = "mcp-auth.json";
715
- var PROJECTS_FILENAME = "projects.json";
716
- var CACHE_DIRNAME = "cache";
717
- var TOOL_OUTPUT_CACHE_DIRNAME = "tool-output";
718
- var SESSIONS_DIRNAME = "sessions";
719
- var LOGS_DIRNAME = "logs";
720
- function resolveStoragePaths(options = {}) {
721
- if (options.rootOverride) {
722
- return buildHomeLayout(options.rootOverride);
2904
+ var import_node_fs9 = require("fs");
2905
+ var MCP_AUTH_VERSION = 2;
2906
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2907
+ var pickString = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
2908
+ var pickNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
2909
+ var canonicalizeMcpUri = (raw) => {
2910
+ const parsed = new URL(raw.trim());
2911
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
2912
+ throw new Error(`Unsupported MCP URI scheme: ${parsed.protocol}`);
723
2913
  }
724
- const layoutValue = options.layout ?? process.env[LAYOUT_ENV];
725
- const layout = normalizeLayout(layoutValue);
726
- if (layout === "xdg") {
727
- return buildXdgLayout();
2914
+ parsed.hash = "";
2915
+ parsed.hostname = parsed.hostname.toLowerCase();
2916
+ if (parsed.protocol === "http:" && parsed.port === "80" || parsed.protocol === "https:" && parsed.port === "443") {
2917
+ parsed.port = "";
728
2918
  }
729
- return buildHomeLayout(defaultHomeRoot());
730
- }
731
- async function ensureStorageDirs(paths) {
732
- await Promise.all([
733
- (0, import_promises5.mkdir)(paths.configDir, { recursive: true }),
734
- (0, import_promises5.mkdir)(paths.cacheDir, { recursive: true }),
735
- (0, import_promises5.mkdir)(paths.toolOutputCacheDir, { recursive: true }),
736
- (0, import_promises5.mkdir)(paths.sessionsDir, { recursive: true }),
737
- (0, import_promises5.mkdir)(paths.logsDir, { recursive: true })
738
- ]);
739
- }
740
- function normalizeLayout(value) {
741
- if (value && value.toLowerCase() === "xdg") return "xdg";
742
- return "home";
743
- }
744
- function defaultHomeRoot() {
745
- return import_node_path4.default.join(import_node_os.default.homedir(), DEFAULT_ROOT_DIR);
746
- }
747
- function buildHomeLayout(root) {
748
- const configDir = root;
749
- return {
750
- root,
751
- configDir,
752
- configFile: import_node_path4.default.join(configDir, CONFIG_FILENAME),
753
- authFile: import_node_path4.default.join(configDir, AUTH_FILENAME),
754
- mcpAuthFile: import_node_path4.default.join(configDir, MCP_AUTH_FILENAME),
755
- projectsFile: import_node_path4.default.join(configDir, PROJECTS_FILENAME),
756
- cacheDir: import_node_path4.default.join(root, CACHE_DIRNAME),
757
- toolOutputCacheDir: import_node_path4.default.join(
758
- root,
759
- CACHE_DIRNAME,
760
- TOOL_OUTPUT_CACHE_DIRNAME
761
- ),
762
- sessionsDir: import_node_path4.default.join(root, SESSIONS_DIRNAME),
763
- logsDir: import_node_path4.default.join(root, LOGS_DIRNAME)
764
- };
765
- }
766
- function buildXdgLayout() {
767
- const home = import_node_os.default.homedir();
768
- const configRoot = process.env.XDG_CONFIG_HOME ?? import_node_path4.default.join(home, ".config");
769
- const cacheRoot = process.env.XDG_CACHE_HOME ?? import_node_path4.default.join(home, ".cache");
770
- const stateRoot = process.env.XDG_STATE_HOME ?? import_node_path4.default.join(home, ".local", "state");
771
- const configDir = import_node_path4.default.join(configRoot, XDG_DIR_NAME);
772
- const cacheDir = import_node_path4.default.join(cacheRoot, XDG_DIR_NAME);
773
- const stateDir = import_node_path4.default.join(stateRoot, XDG_DIR_NAME);
2919
+ return parsed.toString();
2920
+ };
2921
+ var deriveMcpIssuer = (options) => {
2922
+ if (options.issuer?.trim()) return options.issuer;
2923
+ const endpoint = options.tokenUrl ?? options.authorizationUrl;
2924
+ if (!endpoint?.trim()) return void 0;
2925
+ try {
2926
+ return new URL(canonicalizeMcpUri(endpoint)).origin;
2927
+ } catch {
2928
+ return void 0;
2929
+ }
2930
+ };
2931
+ var buildMcpAuthBinding = (options) => {
2932
+ const resource_uri = canonicalizeMcpUri(options.resourceUri);
2933
+ const issuer = deriveMcpIssuer({
2934
+ issuer: options.issuer,
2935
+ tokenUrl: options.tokenEndpoint
2936
+ });
2937
+ const token_endpoint = options.tokenEndpoint?.trim() ? canonicalizeMcpUri(options.tokenEndpoint) : void 0;
2938
+ const client_id = pickString(options.clientId);
774
2939
  return {
775
- root: stateDir,
776
- configDir,
777
- configFile: import_node_path4.default.join(configDir, CONFIG_FILENAME),
778
- authFile: import_node_path4.default.join(configDir, AUTH_FILENAME),
779
- mcpAuthFile: import_node_path4.default.join(configDir, MCP_AUTH_FILENAME),
780
- projectsFile: import_node_path4.default.join(configDir, PROJECTS_FILENAME),
781
- cacheDir,
782
- toolOutputCacheDir: import_node_path4.default.join(cacheDir, TOOL_OUTPUT_CACHE_DIRNAME),
783
- sessionsDir: import_node_path4.default.join(stateDir, SESSIONS_DIRNAME),
784
- logsDir: import_node_path4.default.join(stateDir, LOGS_DIRNAME)
2940
+ resource_uri,
2941
+ ...issuer ? { issuer } : {},
2942
+ ...token_endpoint ? { token_endpoint } : {},
2943
+ ...client_id ? { client_id } : {}
785
2944
  };
786
- }
787
-
788
- // src/mcp-auth-store.ts
789
- var MCP_AUTH_VERSION = 1;
790
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
791
- var pickString = (value) => typeof value === "string" ? value : void 0;
792
- var pickNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
2945
+ };
2946
+ var mcpAuthBindingMatches = (stored, resolved) => {
2947
+ let storedResource;
2948
+ let resolvedResource;
2949
+ try {
2950
+ storedResource = canonicalizeMcpUri(stored.resource_uri);
2951
+ resolvedResource = canonicalizeMcpUri(resolved.resource_uri);
2952
+ } catch {
2953
+ return false;
2954
+ }
2955
+ if (storedResource !== resolvedResource) return false;
2956
+ if (stored.issuer) {
2957
+ const normStored = deriveMcpIssuer({ issuer: stored.issuer });
2958
+ const normResolved = resolved.issuer ? deriveMcpIssuer({ issuer: resolved.issuer }) : resolved.token_endpoint ? deriveMcpIssuer({ tokenUrl: resolved.token_endpoint }) : void 0;
2959
+ if (!normStored || !normResolved || normStored !== normResolved) {
2960
+ return false;
2961
+ }
2962
+ }
2963
+ if (stored.token_endpoint) {
2964
+ if (!resolved.token_endpoint) return false;
2965
+ try {
2966
+ if (canonicalizeMcpUri(stored.token_endpoint) !== canonicalizeMcpUri(resolved.token_endpoint)) {
2967
+ return false;
2968
+ }
2969
+ } catch {
2970
+ return false;
2971
+ }
2972
+ }
2973
+ if (stored.client_id) {
2974
+ if (!resolved.client_id || stored.client_id !== resolved.client_id) {
2975
+ return false;
2976
+ }
2977
+ }
2978
+ return true;
2979
+ };
793
2980
  var normalizeTokens = (value) => {
794
- if (!isRecord(value)) return null;
2981
+ if (!isRecord4(value)) return null;
795
2982
  const accessToken = pickString(value.access_token);
796
2983
  if (!accessToken) return null;
797
2984
  return {
@@ -804,59 +2991,245 @@ var normalizeTokens = (value) => {
804
2991
  ...pickString(value.client_secret) ? { client_secret: pickString(value.client_secret) } : {}
805
2992
  };
806
2993
  };
2994
+ var normalizeBinding = (value) => {
2995
+ if (!isRecord4(value)) return null;
2996
+ const rawResource = pickString(value.resource_uri);
2997
+ if (!rawResource) return null;
2998
+ try {
2999
+ return buildMcpAuthBinding({
3000
+ resourceUri: rawResource,
3001
+ issuer: pickString(value.issuer),
3002
+ tokenEndpoint: pickString(value.token_endpoint),
3003
+ clientId: pickString(value.client_id)
3004
+ });
3005
+ } catch {
3006
+ return null;
3007
+ }
3008
+ };
3009
+ var parseMcpAuthDocument = (text) => {
3010
+ const parsed = JSON.parse(text);
3011
+ if (!isRecord4(parsed)) {
3012
+ throw new Error("mcp-auth.json has unsupported format");
3013
+ }
3014
+ if (parsed.version === 1) {
3015
+ const serversRaw2 = isRecord4(parsed.servers) ? parsed.servers : {};
3016
+ const droppedLegacyServers = Object.entries(serversRaw2).filter(([, entry]) => normalizeTokens(entry) !== null).map(([id2]) => id2).sort();
3017
+ return {
3018
+ normalized: { version: MCP_AUTH_VERSION, servers: {} },
3019
+ sourceVersion: 1,
3020
+ droppedLegacyServers
3021
+ };
3022
+ }
3023
+ if (parsed.version !== MCP_AUTH_VERSION) {
3024
+ throw new Error("mcp-auth.json has unsupported version");
3025
+ }
3026
+ if (parsed.servers !== void 0 && !isRecord4(parsed.servers)) {
3027
+ throw new Error("mcp-auth.json v2 has invalid servers map");
3028
+ }
3029
+ const serversRaw = isRecord4(parsed.servers) ? parsed.servers : {};
3030
+ const servers = {};
3031
+ for (const [id2, entry] of Object.entries(serversRaw)) {
3032
+ if (!isRecord4(entry)) {
3033
+ throw new Error(`mcp-auth.json v2 has invalid entry for '${id2}'`);
3034
+ }
3035
+ const binding = normalizeBinding(entry.binding);
3036
+ if (!binding) {
3037
+ throw new Error(`mcp-auth.json v2 has invalid binding for '${id2}'`);
3038
+ }
3039
+ const tokens = normalizeTokens(entry.tokens);
3040
+ if (!tokens) {
3041
+ throw new Error(`mcp-auth.json v2 has invalid tokens for '${id2}'`);
3042
+ }
3043
+ servers[id2] = { binding, tokens };
3044
+ }
3045
+ return {
3046
+ normalized: { version: MCP_AUTH_VERSION, servers },
3047
+ sourceVersion: 2,
3048
+ droppedLegacyServers: []
3049
+ };
3050
+ };
3051
+ var mcpAuthStoreAdapter = {
3052
+ name: "mcp_auth",
3053
+ service: CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
3054
+ filePath: (paths) => paths.mcpAuthFile,
3055
+ legacyFilePath: (paths) => paths.legacyMcpAuthFile,
3056
+ empty: () => ({ version: MCP_AUTH_VERSION, servers: {} }),
3057
+ isNonEmpty: (doc) => Object.keys(doc.servers).length > 0,
3058
+ parse: (text) => {
3059
+ const parsed = parseMcpAuthDocument(text);
3060
+ return {
3061
+ normalized: parsed.normalized,
3062
+ sourceVersion: parsed.sourceVersion,
3063
+ extraWarnings: parsed.droppedLegacyServers
3064
+ };
3065
+ }
3066
+ };
3067
+ var readTextIfPresent2 = async (filePath) => {
3068
+ if (!await verifyWindowsCredentialFileAcl(filePath)) return null;
3069
+ try {
3070
+ return await import_node_fs9.promises.readFile(filePath, "utf8");
3071
+ } catch (error) {
3072
+ if (error?.code === "ENOENT") return null;
3073
+ throw error;
3074
+ }
3075
+ };
807
3076
  var McpAuthStore = class {
808
3077
  paths;
809
- constructor(paths) {
3078
+ lockOptions;
3079
+ storageMode;
3080
+ keychain;
3081
+ constructor(paths, options) {
810
3082
  this.paths = paths ?? resolveStoragePaths();
3083
+ this.lockOptions = options?.lock;
3084
+ this.storageMode = options?.storageMode;
3085
+ this.keychain = options?.keychain ?? new MacOsKeychainClient({ credentialsDir: this.paths.credentialsDir });
3086
+ }
3087
+ lockPath() {
3088
+ return authLockPathFor(this.paths.credentialsDir);
3089
+ }
3090
+ keychainAccount() {
3091
+ return keychainAccountForConfigDir(this.paths.configDir);
3092
+ }
3093
+ resolveBackendUnlocked() {
3094
+ return coordinateCredentialBackendUnlocked({
3095
+ paths: this.paths,
3096
+ storageMode: this.storageMode,
3097
+ keychain: this.keychain,
3098
+ authAdapter: providerAuthStoreAdapter,
3099
+ mcpAdapter: mcpAuthStoreAdapter
3100
+ });
811
3101
  }
812
- async load() {
813
- try {
814
- const text = await import_node_fs3.promises.readFile(this.paths.mcpAuthFile, "utf8");
815
- const parsed = JSON.parse(text);
816
- if (!isRecord(parsed) || parsed.version !== MCP_AUTH_VERSION) {
817
- throw new Error("mcp-auth.json has unsupported version");
818
- }
819
- const serversRaw = isRecord(parsed.servers) ? parsed.servers : {};
820
- const servers = {};
821
- for (const [id2, entry] of Object.entries(serversRaw)) {
822
- const normalized = normalizeTokens(entry);
823
- if (normalized) {
824
- servers[id2] = normalized;
825
- }
826
- }
827
- return {
828
- version: MCP_AUTH_VERSION,
829
- servers
830
- };
831
- } catch (error) {
832
- const err = error;
833
- if (err?.code === "ENOENT") {
3102
+ async recordDroppedLegacyServers(dropped) {
3103
+ if (!dropped.length) return;
3104
+ await ensureStorageDirs(this.paths);
3105
+ const existing = await readAuthStorageState(this.paths.authStateFile).catch(
3106
+ () => null
3107
+ );
3108
+ const merged = [
3109
+ .../* @__PURE__ */ new Set([...existing?.mcp_reauth_required ?? [], ...dropped])
3110
+ ].sort();
3111
+ await writeAuthStorageState(this.paths.authStateFile, {
3112
+ version: 1,
3113
+ status: "steady",
3114
+ active_backend: existing?.active_backend ?? "file",
3115
+ mcp_reauth_required: merged
3116
+ });
3117
+ }
3118
+ async readFromBackend(active) {
3119
+ if (active === "keyring") {
3120
+ const text2 = await this.keychain.get(
3121
+ CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
3122
+ this.keychainAccount()
3123
+ );
3124
+ if (text2 === null) {
834
3125
  return { version: MCP_AUTH_VERSION, servers: {} };
835
3126
  }
836
- throw error;
3127
+ const parsed2 = parseMcpAuthDocument(text2);
3128
+ if (parsed2.sourceVersion === 1) {
3129
+ await this.writeToBackend("keyring", parsed2.normalized);
3130
+ await this.recordDroppedLegacyServers(parsed2.droppedLegacyServers);
3131
+ }
3132
+ return parsed2.normalized;
837
3133
  }
3134
+ const text = await readTextIfPresent2(this.paths.mcpAuthFile);
3135
+ if (text === null) {
3136
+ return { version: MCP_AUTH_VERSION, servers: {} };
3137
+ }
3138
+ const parsed = parseMcpAuthDocument(text);
3139
+ if (parsed.sourceVersion === 1) {
3140
+ await this.writeToBackend("file", parsed.normalized);
3141
+ await this.recordDroppedLegacyServers(parsed.droppedLegacyServers);
3142
+ }
3143
+ return parsed.normalized;
838
3144
  }
839
- async save(auth) {
3145
+ async clearReauthenticatedServers(authenticatedServers) {
3146
+ if (!authenticatedServers.length) return;
3147
+ const existing = await readAuthStorageState(this.paths.authStateFile).catch(
3148
+ () => null
3149
+ );
3150
+ if (!existing?.mcp_reauth_required?.length) return;
3151
+ const authenticated = new Set(authenticatedServers);
3152
+ const remaining = existing.mcp_reauth_required.filter(
3153
+ (id2) => !authenticated.has(id2)
3154
+ );
3155
+ if (remaining.length === existing.mcp_reauth_required.length) return;
3156
+ const { mcp_reauth_required: _prev, ...rest } = existing;
3157
+ await writeAuthStorageState(this.paths.authStateFile, {
3158
+ ...rest,
3159
+ ...remaining.length ? { mcp_reauth_required: remaining } : {}
3160
+ });
3161
+ }
3162
+ async writeToBackend(active, auth) {
3163
+ if (active === "keyring") {
3164
+ await this.keychain.set(
3165
+ CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
3166
+ this.keychainAccount(),
3167
+ JSON.stringify(auth)
3168
+ );
3169
+ await this.clearReauthenticatedServers(Object.keys(auth.servers));
3170
+ return;
3171
+ }
840
3172
  await ensureStorageDirs(this.paths);
841
3173
  const data = JSON.stringify(auth, null, 2);
842
- await import_node_fs3.promises.writeFile(this.paths.mcpAuthFile, data, { mode: 384 });
843
- try {
844
- await import_node_fs3.promises.chmod(this.paths.mcpAuthFile, 384);
845
- } catch {
846
- }
3174
+ await writeFileAtomic(this.paths.mcpAuthFile, data, { mode: 384 });
3175
+ await this.clearReauthenticatedServers(Object.keys(auth.servers));
3176
+ }
3177
+ /**
3178
+ * Load normalized v2 MCP auth from the active backend (macOS Keychain or
3179
+ * protected `credentials/` file), running safe two-phase migration if needed.
3180
+ */
3181
+ async load() {
3182
+ return withAuthStoreLock(
3183
+ this.lockPath(),
3184
+ async () => {
3185
+ const resolved = await this.resolveBackendUnlocked();
3186
+ return this.readFromBackend(resolved.active);
3187
+ },
3188
+ this.lockOptions
3189
+ );
3190
+ }
3191
+ /**
3192
+ * Reload, mutate, and atomically save under the interprocess auth lock.
3193
+ * Skips writing if the serialized document did not change.
3194
+ */
3195
+ update(mutate) {
3196
+ return withAuthStoreLock(
3197
+ this.lockPath(),
3198
+ async () => {
3199
+ const resolved = await this.resolveBackendUnlocked();
3200
+ const auth = await this.readFromBackend(resolved.active);
3201
+ const before = JSON.stringify(auth);
3202
+ const result = await mutate(auth);
3203
+ if (JSON.stringify(auth) !== before) {
3204
+ await this.writeToBackend(resolved.active, auth);
3205
+ }
3206
+ return result;
3207
+ },
3208
+ this.lockOptions
3209
+ );
3210
+ }
3211
+ async save(auth) {
3212
+ await withAuthStoreLock(
3213
+ this.lockPath(),
3214
+ async () => {
3215
+ const resolved = await this.resolveBackendUnlocked();
3216
+ await this.writeToBackend(resolved.active, auth);
3217
+ },
3218
+ this.lockOptions
3219
+ );
847
3220
  }
848
3221
  };
849
3222
 
850
3223
  // src/process-identity.ts
851
- var import_node_child_process = require("child_process");
852
- var import_node_fs4 = require("fs");
3224
+ var import_node_child_process3 = require("child_process");
3225
+ var import_node_fs10 = require("fs");
853
3226
  var getProcessIdentity = async (pid, options = {}) => {
854
3227
  if (!Number.isSafeInteger(pid) || pid <= 0) return null;
855
3228
  if (process.platform === "linux") {
856
3229
  try {
857
3230
  const [stat, boot] = await Promise.all([
858
- import_node_fs4.promises.readFile(`/proc/${pid}/stat`, "utf8"),
859
- import_node_fs4.promises.readFile("/proc/sys/kernel/random/boot_id", "utf8")
3231
+ import_node_fs10.promises.readFile(`/proc/${pid}/stat`, "utf8"),
3232
+ import_node_fs10.promises.readFile("/proc/sys/kernel/random/boot_id", "utf8")
860
3233
  ]);
861
3234
  return `${boot.trim()}:${stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]}`;
862
3235
  } catch {
@@ -865,7 +3238,7 @@ var getProcessIdentity = async (pid, options = {}) => {
865
3238
  }
866
3239
  if (process.platform === "darwin")
867
3240
  return new Promise((resolve) => {
868
- (0, import_node_child_process.execFile)(
3241
+ (0, import_node_child_process3.execFile)(
869
3242
  "/bin/ps",
870
3243
  ["-p", String(pid), "-o", "lstart="],
871
3244
  {
@@ -880,75 +3253,316 @@ var getProcessIdentity = async (pid, options = {}) => {
880
3253
  };
881
3254
 
882
3255
  // src/projects-store.ts
883
- var import_node_fs5 = require("fs");
884
- var import_node_path5 = __toESM(require("path"), 1);
3256
+ var import_node_crypto8 = require("crypto");
3257
+ var import_node_fs12 = require("fs");
3258
+ var import_node_path11 = __toESM(require("path"), 1);
3259
+ var import_promises7 = require("timers/promises");
885
3260
  var import_shared_types3 = require("@codelia/shared-types");
886
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
887
- var parseApprovalModeField = (fieldPath, value) => {
888
- const parsed = (0, import_shared_types3.parseApprovalMode)(value);
889
- if (!parsed) {
890
- throw new Error(`${fieldPath} is invalid`);
3261
+
3262
+ // src/user-storage-boundary.ts
3263
+ var import_node_fs11 = require("fs");
3264
+ var import_node_os3 = __toESM(require("os"), 1);
3265
+ var import_node_path10 = __toESM(require("path"), 1);
3266
+ var isWithinPath = (root, target) => {
3267
+ const relative = import_node_path10.default.relative(root, target);
3268
+ return !import_node_path10.default.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${import_node_path10.default.sep}`);
3269
+ };
3270
+ var canonicalPathOrResolvedSync = (target) => {
3271
+ const resolved = import_node_path10.default.resolve(target);
3272
+ try {
3273
+ return (0, import_node_fs11.realpathSync)(resolved);
3274
+ } catch (error) {
3275
+ if (error.code !== "ENOENT") return resolved;
3276
+ const parent = import_node_path10.default.dirname(resolved);
3277
+ if (parent === resolved) return resolved;
3278
+ return import_node_path10.default.join(
3279
+ canonicalPathOrResolvedSync(parent),
3280
+ import_node_path10.default.basename(resolved)
3281
+ );
891
3282
  }
892
- return parsed;
3283
+ };
3284
+ var isSameConfigFilePath = (leftPath, rightPath) => {
3285
+ const left = canonicalPathOrResolvedSync(leftPath);
3286
+ const right = canonicalPathOrResolvedSync(rightPath);
3287
+ const samePath = process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
3288
+ if (samePath) return true;
3289
+ const leftStat = (0, import_node_fs11.statSync)(left, { bigint: true, throwIfNoEntry: false });
3290
+ const rightStat = (0, import_node_fs11.statSync)(right, { bigint: true, throwIfNoEntry: false });
3291
+ return !!leftStat && !!rightStat && leftStat.ino !== 0n && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
3292
+ };
3293
+ var isCanonicalHomeWorkspaceSync = (workspace) => {
3294
+ try {
3295
+ const home = import_node_path10.default.resolve(import_node_os3.default.homedir());
3296
+ return (0, import_node_fs11.realpathSync)(workspace) === (0, import_node_fs11.realpathSync)(home);
3297
+ } catch {
3298
+ return false;
3299
+ }
3300
+ };
3301
+ var isOwnedAncestor = (info, uid) => info.isDirectory() && (info.uid === 0 || info.uid === uid) && ((info.mode & 18) === 0 || (info.mode & 512) !== 0);
3302
+ var isOwnedPrivateDirectory = (info, uid) => info.isDirectory() && info.uid === BigInt(uid) && (info.mode & 0o022n) === 0n;
3303
+ var verifyOwnedAncestors = async (directory2, uid, errorMessage = "unsafe_projects_policy_ancestor") => {
3304
+ let child = directory2;
3305
+ while (child !== import_node_path10.default.dirname(child)) {
3306
+ child = import_node_path10.default.dirname(child);
3307
+ const info = await import_node_fs11.promises.stat(child);
3308
+ if (!isOwnedAncestor(info, uid)) throw new Error(errorMessage);
3309
+ }
3310
+ };
3311
+ var verifyOwnedAncestorsSync = (directory2, uid, errorMessage = "unsafe_projects_policy_ancestor") => {
3312
+ let child = directory2;
3313
+ while (child !== import_node_path10.default.dirname(child)) {
3314
+ child = import_node_path10.default.dirname(child);
3315
+ const info = (0, import_node_fs11.statSync)(child);
3316
+ if (!isOwnedAncestor(info, uid)) throw new Error(errorMessage);
3317
+ }
3318
+ };
3319
+ var evaluateHomeReservedStorage = ({
3320
+ workspace,
3321
+ configured,
3322
+ resolved,
3323
+ relativePath,
3324
+ reservedOverride,
3325
+ home,
3326
+ canonicalHome,
3327
+ errorMessage,
3328
+ redirectErrorMessage
3329
+ }) => {
3330
+ const apparentHome = isWithinPath(home, configured) ? home : canonicalHome;
3331
+ const base = resolveDefaultHomeConfigDir(apparentHome);
3332
+ const expectedReserved = import_node_path10.default.resolve(
3333
+ reservedOverride ?? (relativePath ? import_node_path10.default.join(base, relativePath) : base)
3334
+ );
3335
+ if (workspace !== canonicalHome || configured !== expectedReserved || !isWithinPath(apparentHome, configured))
3336
+ throw new Error(errorMessage);
3337
+ const expectedResolved = import_node_path10.default.join(
3338
+ canonicalHome,
3339
+ import_node_path10.default.relative(apparentHome, configured)
3340
+ );
3341
+ if (resolved !== expectedResolved) throw new Error(redirectErrorMessage);
3342
+ };
3343
+ var verifyUserStorageLocation = async ({
3344
+ workspace,
3345
+ configured,
3346
+ resolved,
3347
+ relativePath = "",
3348
+ reservedOverride,
3349
+ errorMessage = "unsafe_projects_policy_path",
3350
+ redirectErrorMessage = errorMessage
3351
+ }) => {
3352
+ const resolvedConfigured = import_node_path10.default.resolve(configured);
3353
+ if (!isWithinPath(workspace, resolvedConfigured) && !isWithinPath(workspace, resolved))
3354
+ return { insideWorkspace: false };
3355
+ const home = import_node_path10.default.resolve(import_node_os3.default.homedir());
3356
+ let canonicalHome;
3357
+ try {
3358
+ canonicalHome = await import_node_fs11.promises.realpath(home);
3359
+ } catch {
3360
+ throw new Error(errorMessage);
3361
+ }
3362
+ evaluateHomeReservedStorage({
3363
+ workspace,
3364
+ configured: resolvedConfigured,
3365
+ resolved,
3366
+ relativePath,
3367
+ reservedOverride,
3368
+ home,
3369
+ canonicalHome,
3370
+ errorMessage,
3371
+ redirectErrorMessage
3372
+ });
3373
+ return { insideWorkspace: true };
3374
+ };
3375
+ var verifyUserStorageLocationSync = ({
3376
+ workspace,
3377
+ configured,
3378
+ resolved,
3379
+ relativePath = "",
3380
+ reservedOverride,
3381
+ errorMessage = "unsafe_projects_policy_path",
3382
+ redirectErrorMessage = errorMessage
3383
+ }) => {
3384
+ const resolvedConfigured = import_node_path10.default.resolve(configured);
3385
+ if (!isWithinPath(workspace, resolvedConfigured) && !isWithinPath(workspace, resolved))
3386
+ return { insideWorkspace: false };
3387
+ const home = import_node_path10.default.resolve(import_node_os3.default.homedir());
3388
+ let canonicalHome;
3389
+ try {
3390
+ canonicalHome = (0, import_node_fs11.realpathSync)(home);
3391
+ } catch {
3392
+ throw new Error(errorMessage);
3393
+ }
3394
+ evaluateHomeReservedStorage({
3395
+ workspace,
3396
+ configured: resolvedConfigured,
3397
+ resolved,
3398
+ relativePath,
3399
+ reservedOverride,
3400
+ home,
3401
+ canonicalHome,
3402
+ errorMessage,
3403
+ redirectErrorMessage
3404
+ });
3405
+ return { insideWorkspace: true };
3406
+ };
3407
+ var isTrustedGlobalConfigLocationSync = (workingDir, configPath) => {
3408
+ try {
3409
+ const workspace = (0, import_node_fs11.realpathSync)(workingDir);
3410
+ const configured = import_node_path10.default.resolve(configPath);
3411
+ const resolved = canonicalPathOrResolvedSync(configured);
3412
+ const { insideWorkspace } = verifyUserStorageLocationSync({
3413
+ workspace,
3414
+ configured,
3415
+ resolved,
3416
+ relativePath: "config.json",
3417
+ errorMessage: "untrusted_global_config_path"
3418
+ });
3419
+ if (!insideWorkspace) return true;
3420
+ if (typeof process.geteuid !== "function") return false;
3421
+ const uid = process.geteuid();
3422
+ const dir = import_node_path10.default.dirname(resolved);
3423
+ if (!isOwnedPrivateDirectory((0, import_node_fs11.lstatSync)(dir, { bigint: true }), uid))
3424
+ return false;
3425
+ verifyOwnedAncestorsSync(dir, uid, "untrusted_global_config_path");
3426
+ const fileInfo = (0, import_node_fs11.lstatSync)(resolved, {
3427
+ bigint: true,
3428
+ throwIfNoEntry: false
3429
+ });
3430
+ if (fileInfo && (!fileInfo.isFile() || fileInfo.nlink !== 1n || fileInfo.uid !== BigInt(uid) || (fileInfo.mode & 0o022n) !== 0n))
3431
+ return false;
3432
+ return true;
3433
+ } catch {
3434
+ return false;
3435
+ }
3436
+ };
3437
+
3438
+ // src/projects-store.ts
3439
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3440
+ var missing = (error) => error.code === "ENOENT";
3441
+ var lockFileFor = (file) => import_node_path11.default.join(import_node_path11.default.dirname(file), ".projects-policy-lock.sqlite");
3442
+ var lstatIfPresent2 = (file) => import_node_fs12.promises.lstat(file).catch((error) => {
3443
+ if (!missing(error)) throw error;
3444
+ return void 0;
3445
+ });
3446
+ var verifyLockFile2 = async (file) => {
3447
+ const info = await lstatIfPresent2(file);
3448
+ if (info && (!info.isFile() || info.uid !== process.geteuid?.() || info.size === 0 || (info.mode & 18) !== 0))
3449
+ throw new Error("unsafe_projects_policy_lock");
3450
+ };
3451
+ var initializeUpdateLock = async (lockPath) => {
3452
+ if (await lstatIfPresent2(lockPath)) return;
3453
+ const temporary = `${lockPath}.${(0, import_node_crypto8.randomUUID)()}.tmp`;
3454
+ try {
3455
+ const file = await import_node_fs12.promises.open(temporary, "wx", 384);
3456
+ await file.close();
3457
+ const db = await openSqlite(temporary);
3458
+ try {
3459
+ db.exec("PRAGMA user_version = 1");
3460
+ } finally {
3461
+ db.close();
3462
+ }
3463
+ try {
3464
+ await import_node_fs12.promises.link(temporary, lockPath);
3465
+ } catch (error) {
3466
+ if (error.code !== "EEXIST") throw error;
3467
+ }
3468
+ } finally {
3469
+ await import_node_fs12.promises.unlink(temporary).catch(() => void 0);
3470
+ }
3471
+ };
3472
+ var openUpdateLock = async (lockPath) => {
3473
+ await initializeUpdateLock(lockPath);
3474
+ await verifyLockFile2(lockPath);
3475
+ const db = await openSqlite(lockPath);
3476
+ const deadline = performance.now() + 1e3;
3477
+ try {
3478
+ db.exec("PRAGMA busy_timeout = 0");
3479
+ for (; ; ) {
3480
+ try {
3481
+ db.exec("BEGIN IMMEDIATE");
3482
+ return db;
3483
+ } catch (error) {
3484
+ if (error.code !== "SQLITE_BUSY" || performance.now() >= deadline)
3485
+ throw error;
3486
+ await (0, import_promises7.setTimeout)(20);
3487
+ }
3488
+ }
3489
+ } catch (error) {
3490
+ db.close();
3491
+ throw error;
3492
+ }
3493
+ };
3494
+ var normalizeProjectPolicy = (value, field) => {
3495
+ if (!isRecord5(value)) throw new Error(`${field} must be an object`);
3496
+ const { approval_mode, sandbox_mode, protected_paths, trust_project_allows } = value;
3497
+ if (trust_project_allows !== void 0 && typeof trust_project_allows !== "boolean")
3498
+ throw new Error(`${field}.trust_project_allows must be boolean`);
3499
+ const approvalMode = (0, import_shared_types3.parseApprovalMode)(approval_mode);
3500
+ const sandboxMode = (0, import_shared_types3.parseSandboxMode)(sandbox_mode);
3501
+ const toolAllows = value.remembered_tool_allows;
3502
+ if (toolAllows !== void 0 && (!Array.isArray(toolAllows) || toolAllows.some(
3503
+ (rule) => !isRecord5(rule) || Object.keys(rule).length !== 1 || typeof rule.tool !== "string" || !/^[a-z][a-z0-9_]*$/.test(rule.tool)
3504
+ )))
3505
+ throw new Error(
3506
+ `${field}.remembered_tool_allows must contain tool-only rules`
3507
+ );
3508
+ if (approval_mode !== void 0 && !approvalMode)
3509
+ throw new Error(`${field}.approval_mode is invalid`);
3510
+ if (sandbox_mode !== void 0 && !sandboxMode)
3511
+ throw new Error(`${field}.sandbox_mode is invalid`);
3512
+ if (protected_paths !== void 0 && (!Array.isArray(protected_paths) || protected_paths.some(
3513
+ (entry) => typeof entry !== "string" || !import_node_path11.default.isAbsolute(entry) || [...entry].some(
3514
+ (character) => character < " " || character === "\x7F"
3515
+ )
3516
+ )))
3517
+ throw new Error(`${field}.protected_paths must contain absolute paths`);
3518
+ return {
3519
+ ...Array.isArray(toolAllows) ? { remembered_tool_allows: toolAllows.map(({ tool }) => ({ tool })) } : {},
3520
+ ...typeof trust_project_allows === "boolean" ? { trust_project_allows } : {},
3521
+ ...approvalMode ? { approval_mode: approvalMode } : {},
3522
+ ...sandboxMode ? { sandbox_mode: sandboxMode } : {},
3523
+ ...Array.isArray(protected_paths) ? { protected_paths: [...new Set(protected_paths)] } : {}
3524
+ };
893
3525
  };
894
3526
  var normalizeProjectsPolicyFile = (value) => {
895
- if (!isRecord2(value)) {
3527
+ if (!isRecord5(value)) {
896
3528
  throw new Error("projects policy must be an object");
897
3529
  }
898
3530
  if (value.version !== 1) {
899
3531
  throw new Error("projects policy version must be 1");
900
3532
  }
901
3533
  const normalized = { version: 1 };
902
- const defaultValue = value.default;
903
- if (defaultValue !== void 0) {
904
- if (!isRecord2(defaultValue)) {
905
- throw new Error("projects policy default must be an object");
906
- }
907
- if (defaultValue.approval_mode !== void 0) {
908
- normalized.default = {
909
- approval_mode: parseApprovalModeField(
910
- "projects policy default.approval_mode",
911
- defaultValue.approval_mode
912
- )
913
- };
914
- }
3534
+ if (value.default !== void 0) {
3535
+ const entry = normalizeProjectPolicy(
3536
+ value.default,
3537
+ "projects policy default"
3538
+ );
3539
+ if (Object.keys(entry).length) normalized.default = entry;
915
3540
  }
916
- const projectsValue = value.projects;
917
- if (projectsValue !== void 0) {
918
- if (!isRecord2(projectsValue)) {
3541
+ if (value.projects !== void 0) {
3542
+ if (!isRecord5(value.projects))
919
3543
  throw new Error("projects policy projects must be an object");
920
- }
921
- const entries2 = {};
922
- for (const [key, projectValue] of Object.entries(projectsValue)) {
923
- if (!isRecord2(projectValue)) {
924
- throw new Error(`projects policy projects['${key}'] must be an object`);
925
- }
926
- if (projectValue.approval_mode !== void 0) {
927
- entries2[key] = {
928
- approval_mode: parseApprovalModeField(
929
- `projects policy projects['${key}'].approval_mode`,
930
- projectValue.approval_mode
931
- )
932
- };
933
- }
934
- }
935
- if (Object.keys(entries2).length > 0) {
936
- normalized.projects = entries2;
937
- }
3544
+ const entries2 = Object.entries(value.projects).flatMap(([key, value2]) => {
3545
+ const entry = normalizeProjectPolicy(
3546
+ value2,
3547
+ `projects policy projects['${key}']`
3548
+ );
3549
+ return Object.keys(entry).length ? [[key, entry]] : [];
3550
+ });
3551
+ if (entries2.length) normalized.projects = Object.fromEntries(entries2);
938
3552
  }
939
3553
  return normalized;
940
3554
  };
941
3555
  var atomicWriteFile = async (filePath, content) => {
942
- const dirPath = import_node_path5.default.dirname(filePath);
943
- const fileName = import_node_path5.default.basename(filePath);
944
- const tempPath = import_node_path5.default.join(
3556
+ const dirPath = import_node_path11.default.dirname(filePath);
3557
+ const fileName = import_node_path11.default.basename(filePath);
3558
+ const tempPath = import_node_path11.default.join(
945
3559
  dirPath,
946
3560
  `.${fileName}.${process.pid}.${Date.now()}.tmp`
947
3561
  );
948
- await import_node_fs5.promises.writeFile(tempPath, content, { mode: 384 });
949
- await import_node_fs5.promises.rename(tempPath, filePath);
3562
+ await import_node_fs12.promises.writeFile(tempPath, content, { mode: 384 });
3563
+ await import_node_fs12.promises.rename(tempPath, filePath);
950
3564
  if (process.platform !== "win32") {
951
- await import_node_fs5.promises.chmod(filePath, 384);
3565
+ await import_node_fs12.promises.chmod(filePath, 384);
952
3566
  }
953
3567
  };
954
3568
  var ProjectsPolicyStore = class {
@@ -959,10 +3573,229 @@ var ProjectsPolicyStore = class {
959
3573
  getFilePath() {
960
3574
  return this.paths.projectsFile;
961
3575
  }
962
- async load() {
3576
+ async verifyWorkspaceLocation(workspace, configured, file, access, relativePath = "projects.json", reservedFile = resolveStoragePaths().projectsFile) {
3577
+ await verifyUserStorageLocation({
3578
+ workspace,
3579
+ configured,
3580
+ resolved: file,
3581
+ relativePath,
3582
+ // Preserve existing read compatibility for owner-verified custom
3583
+ // XDG_CONFIG_HOME paths inside ~ so stored readonly/protected_paths are
3584
+ // never silently dropped, while restricting writes to default layouts.
3585
+ ...access === "read" ? { reservedOverride: reservedFile } : {},
3586
+ errorMessage: "unsafe_projects_policy_path"
3587
+ });
3588
+ }
3589
+ async trustedPath(workspace, access, configured = import_node_path11.default.resolve(this.paths.projectsFile), relativePath = "projects.json", reservedFile = resolveStoragePaths().projectsFile) {
3590
+ const uid = process.geteuid?.();
3591
+ if (uid === void 0) throw new Error("unsafe_projects_policy_path");
3592
+ const destination = import_node_path11.default.dirname(configured);
3593
+ let ancestor = destination;
3594
+ let canonical;
3595
+ for (; ; ) {
3596
+ try {
3597
+ canonical = await import_node_fs12.promises.realpath(ancestor);
3598
+ break;
3599
+ } catch (error) {
3600
+ if (!missing(error) || ancestor === import_node_path11.default.dirname(ancestor)) throw error;
3601
+ if (await lstatIfPresent2(ancestor))
3602
+ throw new Error("unsafe_projects_policy_path");
3603
+ ancestor = import_node_path11.default.dirname(ancestor);
3604
+ }
3605
+ }
3606
+ const directory2 = import_node_path11.default.join(
3607
+ canonical,
3608
+ import_node_path11.default.relative(ancestor, destination)
3609
+ );
3610
+ const file = import_node_path11.default.join(directory2, import_node_path11.default.basename(configured));
3611
+ await this.verifyWorkspaceLocation(
3612
+ workspace,
3613
+ configured,
3614
+ file,
3615
+ access,
3616
+ relativePath,
3617
+ reservedFile
3618
+ );
3619
+ const owner = await import_node_fs12.promises.stat(canonical);
3620
+ if (!owner.isDirectory() || owner.uid !== uid || (owner.mode & 18) !== 0)
3621
+ throw new Error("unsafe_projects_policy_directory");
3622
+ await verifyOwnedAncestors(canonical, uid);
3623
+ if (ancestor !== canonical) await verifyOwnedAncestors(ancestor, uid);
3624
+ if (access !== "read")
3625
+ await import_node_fs12.promises.access(canonical, import_node_fs12.constants.W_OK | import_node_fs12.constants.X_OK);
3626
+ if (access === "create" && ancestor !== destination) {
3627
+ await import_node_fs12.promises.mkdir(directory2, { recursive: true, mode: 448 });
3628
+ if (await import_node_fs12.promises.realpath(directory2) !== directory2)
3629
+ throw new Error("unsafe_projects_policy_directory");
3630
+ return this.trustedPath(workspace, "write");
3631
+ }
3632
+ return file;
3633
+ }
3634
+ async readUserFile(file, owner) {
3635
+ const info = await lstatIfPresent2(file);
3636
+ if (!info) return void 0;
3637
+ if (!info.isFile() || info.nlink !== 1)
3638
+ throw new Error("unsafe_projects_policy_file");
3639
+ const handle = await import_node_fs12.promises.open(
3640
+ file,
3641
+ import_node_fs12.constants.O_RDONLY | (import_node_fs12.constants.O_NOFOLLOW ?? 0) | (import_node_fs12.constants.O_NONBLOCK ?? 0)
3642
+ );
3643
+ try {
3644
+ const current = await handle.stat();
3645
+ if (!current.isFile() || current.dev !== info.dev || current.ino !== info.ino || current.nlink !== 1 || owner !== null && (current.uid !== owner || (current.mode & 18) !== 0))
3646
+ throw new Error("unsafe_projects_policy_file");
3647
+ return await handle.readFile("utf8");
3648
+ } finally {
3649
+ await handle.close();
3650
+ }
3651
+ }
3652
+ /** Read user-authored permission settings through the same private-file boundary as project trust. */
3653
+ async readUserConfig(workspace, configured) {
3654
+ const uid = process.geteuid?.();
3655
+ if (uid === void 0) throw new Error("unsafe_projects_policy_path");
3656
+ const file = await this.trustedPath(
3657
+ workspace,
3658
+ "read",
3659
+ import_node_path11.default.resolve(configured),
3660
+ "config.json",
3661
+ this.paths.configFile
3662
+ );
3663
+ return this.readUserFile(file, uid);
3664
+ }
3665
+ async readPolicyFile(file, owner) {
3666
+ const text = await this.readUserFile(file, owner);
3667
+ const raw = text === void 0 ? { version: 1 } : JSON.parse(text);
3668
+ const normalized = normalizeProjectsPolicyFile(raw);
3669
+ return { raw, normalized };
3670
+ }
3671
+ readTrusted(file) {
3672
+ const owner = process.geteuid?.();
3673
+ if (owner === void 0) throw new Error("unsafe_projects_policy_path");
3674
+ return this.readPolicyFile(file, owner);
3675
+ }
3676
+ async hasUnverifiableProtectedPaths(workspace) {
3677
+ const configured = import_node_path11.default.resolve(this.paths.projectsFile);
3678
+ const canonicalParent = await import_node_fs12.promises.realpath(import_node_path11.default.dirname(configured));
3679
+ const file = import_node_path11.default.join(canonicalParent, import_node_path11.default.basename(configured));
3680
+ await this.verifyWorkspaceLocation(workspace, configured, file, "read");
3681
+ const { normalized: policy } = await this.readPolicyFile(file, null);
3682
+ return Boolean(
3683
+ policy.default?.protected_paths?.length || Object.entries(policy.projects ?? {}).some(
3684
+ ([root, entry]) => entry.protected_paths?.length && import_node_path11.default.isAbsolute(root) && import_node_path11.default.relative(workspace, root) === ""
3685
+ )
3686
+ );
3687
+ }
3688
+ async loadUserOwned(workspace, { strict = false } = {}) {
3689
+ let hasUnverifiablePaths;
963
3690
  try {
964
- const raw = await import_node_fs5.promises.readFile(this.paths.projectsFile, "utf8");
965
- const parsed = JSON.parse(raw);
3691
+ if (strict && !await lstatIfPresent2(this.paths.projectsFile))
3692
+ return null;
3693
+ if (strict && process.geteuid?.() === void 0) {
3694
+ hasUnverifiablePaths = await this.hasUnverifiableProtectedPaths(workspace);
3695
+ } else {
3696
+ const file = await this.trustedPath(workspace, "read");
3697
+ return (await this.readTrusted(file)).normalized;
3698
+ }
3699
+ } catch (error) {
3700
+ if (strict)
3701
+ throw new Error("untrusted_projects_policy", { cause: error });
3702
+ return null;
3703
+ }
3704
+ if (hasUnverifiablePaths)
3705
+ throw new Error("protected_paths_owner_verification_unavailable");
3706
+ return null;
3707
+ }
3708
+ async verifyProjectModeWritable(workspace) {
3709
+ const file = await this.trustedPath(workspace, "write");
3710
+ await this.readTrusted(file);
3711
+ await verifyLockFile2(lockFileFor(file));
3712
+ }
3713
+ /** Merge into a private user policy while other runtimes are excluded. */
3714
+ async writeProjectMode(workspace, mode) {
3715
+ return this.updateProject(workspace, { sandbox_mode: mode });
3716
+ }
3717
+ async writeProjectAllowTrust(workspace, trusted, verify) {
3718
+ return this.updateProject(
3719
+ workspace,
3720
+ { trust_project_allows: trusted },
3721
+ verify
3722
+ );
3723
+ }
3724
+ async updateRememberedTool(workspace, tool, allow, verify) {
3725
+ if (!/^[a-z][a-z0-9_]*$/.test(tool))
3726
+ throw new Error("invalid_remembered_tool");
3727
+ let changed = false;
3728
+ await this.updateProject(
3729
+ workspace,
3730
+ (current) => {
3731
+ const exists = current.remembered_tool_allows?.some((rule) => rule.tool === tool) ?? false;
3732
+ if (exists === allow) return void 0;
3733
+ changed = true;
3734
+ return {
3735
+ remembered_tool_allows: [
3736
+ ...(current.remembered_tool_allows ?? []).filter(
3737
+ (rule) => rule.tool !== tool
3738
+ ),
3739
+ ...allow ? [{ tool }] : []
3740
+ ]
3741
+ };
3742
+ },
3743
+ verify
3744
+ );
3745
+ return changed;
3746
+ }
3747
+ async updateProject(workspace, patch, verify) {
3748
+ const file = await this.trustedPath(workspace, "create");
3749
+ const lock = await openUpdateLock(lockFileFor(file));
3750
+ const temporary = `${file}.${(0, import_node_crypto8.randomUUID)()}.tmp`;
3751
+ try {
3752
+ const { raw: policy } = await this.readTrusted(file);
3753
+ const projects = policy.projects;
3754
+ const changes = typeof patch === "function" ? patch(projects?.[workspace] ?? {}) : patch;
3755
+ if (!changes) {
3756
+ verify?.();
3757
+ return;
3758
+ }
3759
+ const next = {
3760
+ ...policy,
3761
+ projects: {
3762
+ ...projects,
3763
+ [workspace]: { ...projects?.[workspace], ...changes }
3764
+ }
3765
+ };
3766
+ await import_node_fs12.promises.writeFile(temporary, `${JSON.stringify(next, null, 2)}
3767
+ `, {
3768
+ mode: 384,
3769
+ flag: "wx"
3770
+ });
3771
+ await import_node_fs12.promises.chmod(temporary, 384);
3772
+ if (await this.trustedPath(workspace, "write") !== file)
3773
+ throw new Error("unsafe_projects_policy_path");
3774
+ verify?.();
3775
+ await import_node_fs12.promises.rename(temporary, file);
3776
+ } finally {
3777
+ lock.close();
3778
+ await import_node_fs12.promises.unlink(temporary).catch(() => void 0);
3779
+ }
3780
+ }
3781
+ async load(canonicalPath) {
3782
+ try {
3783
+ const handle = await import_node_fs12.promises.open(
3784
+ canonicalPath ?? this.paths.projectsFile,
3785
+ canonicalPath ? import_node_fs12.constants.O_RDONLY | (import_node_fs12.constants.O_NOFOLLOW ?? 0) | (import_node_fs12.constants.O_NONBLOCK ?? 0) : "r"
3786
+ );
3787
+ let parsed;
3788
+ try {
3789
+ if (canonicalPath) {
3790
+ const info = await handle.stat();
3791
+ const uid = process.geteuid?.();
3792
+ if (!info.isFile() || info.nlink !== 1 || uid !== void 0 && (info.uid !== uid || (info.mode & 18) !== 0))
3793
+ return null;
3794
+ }
3795
+ parsed = JSON.parse(await handle.readFile("utf8"));
3796
+ } finally {
3797
+ await handle.close();
3798
+ }
966
3799
  return normalizeProjectsPolicyFile(parsed);
967
3800
  } catch (error) {
968
3801
  if (error.code === "ENOENT") {
@@ -983,55 +3816,55 @@ var ProjectsPolicyStore = class {
983
3816
  };
984
3817
 
985
3818
  // src/session-store.ts
986
- var import_node_fs8 = require("fs");
987
- var import_node_path8 = __toESM(require("path"), 1);
3819
+ var import_node_fs15 = require("fs");
3820
+ var import_node_path14 = __toESM(require("path"), 1);
988
3821
 
989
3822
  // src/run-log-paths.ts
990
- var import_node_crypto5 = require("crypto");
991
- var import_node_path6 = __toESM(require("path"), 1);
3823
+ var import_node_crypto9 = require("crypto");
3824
+ var import_node_path12 = __toESM(require("path"), 1);
992
3825
  var runDatePath = (startedAt) => {
993
3826
  const date = new Date(startedAt);
994
3827
  if (!Number.isFinite(date.getTime()))
995
3828
  throw new Error("Invalid run start time");
996
- return [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join(import_node_path6.default.sep);
3829
+ return [date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate()].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join(import_node_path12.default.sep);
997
3830
  };
998
3831
  var validateRunLogId = (id2) => {
999
3832
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(id2))
1000
3833
  throw new Error("Invalid run/session log id");
1001
3834
  return id2;
1002
3835
  };
1003
- var activeRunDirectory = (paths, sessionId) => import_node_path6.default.join(
3836
+ var activeRunDirectory = (paths, sessionId) => import_node_path12.default.join(
1004
3837
  paths.sessionsDir,
1005
3838
  "active-runs",
1006
- (0, import_node_crypto5.createHash)("sha256").update(sessionId).digest("hex")
3839
+ (0, import_node_crypto9.createHash)("sha256").update(sessionId).digest("hex")
1007
3840
  );
1008
- var usageLogPath = (paths, datePath, runId) => import_node_path6.default.join(paths.root, "usage", datePath, `${validateRunLogId(runId)}.jsonl`);
3841
+ var usageLogPath = (paths, datePath, runId) => import_node_path12.default.join(paths.root, "usage", datePath, `${validateRunLogId(runId)}.jsonl`);
1009
3842
 
1010
3843
  // src/session-run-index.ts
1011
- var import_node_fs7 = require("fs");
1012
- var import_node_path7 = __toESM(require("path"), 1);
3844
+ var import_node_fs14 = require("fs");
3845
+ var import_node_path13 = __toESM(require("path"), 1);
1013
3846
 
1014
3847
  // src/run-log-reader.ts
1015
- var import_node_fs6 = require("fs");
3848
+ var import_node_fs13 = require("fs");
1016
3849
  var import_node_readline = require("readline");
1017
3850
  var import_node_stream = require("stream");
1018
3851
  var import_node_zlib2 = require("zlib");
1019
- var resolveRunLogPath = (file) => (0, import_node_fs6.existsSync)(file) ? file : file.endsWith(".gz") ? file : `${file}.gz`;
3852
+ var resolveRunLogPath = (file) => (0, import_node_fs13.existsSync)(file) ? file : file.endsWith(".gz") ? file : `${file}.gz`;
1020
3853
  async function* readRunLogChunks(file) {
1021
3854
  let resolved = resolveRunLogPath(file);
1022
3855
  let handle;
1023
3856
  try {
1024
- handle = await import_node_fs6.promises.open(
3857
+ handle = await import_node_fs13.promises.open(
1025
3858
  resolved,
1026
- import_node_fs6.constants.O_RDONLY | (import_node_fs6.constants.O_NOFOLLOW ?? 0)
3859
+ import_node_fs13.constants.O_RDONLY | (import_node_fs13.constants.O_NOFOLLOW ?? 0)
1027
3860
  );
1028
3861
  } catch (error) {
1029
3862
  if (error.code !== "ENOENT" || file.endsWith(".gz"))
1030
3863
  throw error;
1031
3864
  resolved = `${file}.gz`;
1032
- handle = await import_node_fs6.promises.open(
3865
+ handle = await import_node_fs13.promises.open(
1033
3866
  resolved,
1034
- import_node_fs6.constants.O_RDONLY | (import_node_fs6.constants.O_NOFOLLOW ?? 0)
3867
+ import_node_fs13.constants.O_RDONLY | (import_node_fs13.constants.O_NOFOLLOW ?? 0)
1035
3868
  );
1036
3869
  }
1037
3870
  const source = handle.createReadStream();
@@ -1066,18 +3899,18 @@ var normalizeRunStartedAt = (startedAt) => {
1066
3899
  };
1067
3900
  var isRegularFile = (file) => {
1068
3901
  try {
1069
- return (0, import_node_fs7.lstatSync)(file).isFile();
3902
+ return (0, import_node_fs14.lstatSync)(file).isFile();
1070
3903
  } catch {
1071
3904
  return false;
1072
3905
  }
1073
3906
  };
1074
3907
  var toRunLogRelPath = (sessionsDir, file) => {
1075
- const relative = import_node_path7.default.relative(sessionsDir, file).split(import_node_path7.default.sep).join("/").replace(/\.gz$/, "");
3908
+ const relative = import_node_path13.default.relative(sessionsDir, file).split(import_node_path13.default.sep).join("/").replace(/\.gz$/, "");
1076
3909
  return REL_PATH_PATTERN.test(relative) ? relative : void 0;
1077
3910
  };
1078
3911
  var resolveIndexedRunLog = (sessionsDir, relPath) => {
1079
3912
  if (!REL_PATH_PATTERN.test(relPath)) return void 0;
1080
- const plain = import_node_path7.default.join(sessionsDir, ...relPath.split("/"));
3913
+ const plain = import_node_path13.default.join(sessionsDir, ...relPath.split("/"));
1081
3914
  if (isRegularFile(plain)) return plain;
1082
3915
  if (isRegularFile(`${plain}.gz`)) return `${plain}.gz`;
1083
3916
  return void 0;
@@ -1097,7 +3930,7 @@ var readHeader = async (file) => {
1097
3930
  var errorCode2 = (error) => error?.code;
1098
3931
  var readDirs = async (directory2) => {
1099
3932
  try {
1100
- return await import_node_fs7.promises.readdir(directory2, {
3933
+ return await import_node_fs14.promises.readdir(directory2, {
1101
3934
  withFileTypes: true,
1102
3935
  encoding: "utf8"
1103
3936
  });
@@ -1115,13 +3948,13 @@ var listRunLogFiles = async (sessionsDir) => {
1115
3948
  const files = [];
1116
3949
  for (const year of await readDirs(sessionsDir)) {
1117
3950
  if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
1118
- const yearPath = import_node_path7.default.join(sessionsDir, year.name);
3951
+ const yearPath = import_node_path13.default.join(sessionsDir, year.name);
1119
3952
  for (const month of await readDirs(yearPath)) {
1120
3953
  if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
1121
- const monthPath = import_node_path7.default.join(yearPath, month.name);
3954
+ const monthPath = import_node_path13.default.join(yearPath, month.name);
1122
3955
  for (const day of await readDirs(monthPath)) {
1123
3956
  if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
1124
- const dayPath = import_node_path7.default.join(monthPath, day.name);
3957
+ const dayPath = import_node_path13.default.join(monthPath, day.name);
1125
3958
  const entries2 = (await readDirs(dayPath)).filter(
1126
3959
  (entry) => entry.isFile() && /\.jsonl(?:\.gz)?$/.test(entry.name)
1127
3960
  );
@@ -1131,7 +3964,7 @@ var listRunLogFiles = async (sessionsDir) => {
1131
3964
  for (const entry of entries2) {
1132
3965
  if (entry.name.endsWith(".gz") && plain.has(entry.name.slice(0, -3)))
1133
3966
  continue;
1134
- files.push(import_node_path7.default.join(dayPath, entry.name));
3967
+ files.push(import_node_path13.default.join(dayPath, entry.name));
1135
3968
  }
1136
3969
  }
1137
3970
  }
@@ -1151,10 +3984,10 @@ var scanSessionRunLogs = async (sessionsDir) => {
1151
3984
  try {
1152
3985
  const header = await readHeader(file);
1153
3986
  if (!header || typeof header.session_id !== "string") continue;
1154
- const startedAt = typeof header.started_at === "string" ? header.started_at : new Date((await import_node_fs7.promises.stat(file)).mtimeMs).toISOString();
3987
+ const startedAt = typeof header.started_at === "string" ? header.started_at : new Date((await import_node_fs14.promises.stat(file)).mtimeMs).toISOString();
1155
3988
  entries2.push({
1156
3989
  session_id: header.session_id,
1157
- run_id: typeof header.run_id === "string" ? header.run_id : import_node_path7.default.posix.basename(relPath, ".jsonl"),
3990
+ run_id: typeof header.run_id === "string" ? header.run_id : import_node_path13.default.posix.basename(relPath, ".jsonl"),
1158
3991
  rel_path: relPath,
1159
3992
  started_at: normalizeRunStartedAt(startedAt)
1160
3993
  });
@@ -1227,7 +4060,7 @@ var SessionStoreWriterImpl = class {
1227
4060
  this.runId = validateRunLogId(options.runId);
1228
4061
  this.startedAt = options.startedAt;
1229
4062
  const datePath = runDatePath(options.startedAt);
1230
- this.filePath = import_node_path8.default.join(
4063
+ this.filePath = import_node_path14.default.join(
1231
4064
  paths.sessionsDir,
1232
4065
  datePath,
1233
4066
  `${this.runId}.jsonl`
@@ -1235,7 +4068,7 @@ var SessionStoreWriterImpl = class {
1235
4068
  this.usageFilePath = usageLogPath(paths, datePath, this.runId);
1236
4069
  const dump = options.dump ?? /^(1|true)$/i.test(process.env.CODELIA_SESSION_DUMP ?? "");
1237
4070
  if (dump)
1238
- this.diagnosticFilePath = import_node_path8.default.join(
4071
+ this.diagnosticFilePath = import_node_path14.default.join(
1239
4072
  paths.sessionsDir,
1240
4073
  "diagnostics",
1241
4074
  datePath,
@@ -1310,9 +4143,9 @@ var SessionStoreWriterImpl = class {
1310
4143
  if (markerSessionId) {
1311
4144
  await this.recordRun(markerSessionId, startedAt ?? this.startedAt);
1312
4145
  const directory2 = activeRunDirectory(this.paths, markerSessionId);
1313
- await import_node_fs8.promises.mkdir(directory2, { recursive: true });
1314
- this.activePath = import_node_path8.default.join(directory2, `${this.runId}.json`);
1315
- await import_node_fs8.promises.writeFile(
4146
+ await import_node_fs15.promises.mkdir(directory2, { recursive: true });
4147
+ this.activePath = import_node_path14.default.join(directory2, `${this.runId}.json`);
4148
+ await import_node_fs15.promises.writeFile(
1316
4149
  this.activePath,
1317
4150
  JSON.stringify({
1318
4151
  pid: process.pid,
@@ -1329,11 +4162,11 @@ var SessionStoreWriterImpl = class {
1329
4162
  [this.diagnosticFilePath, dump]
1330
4163
  ]) {
1331
4164
  if (!file || line === void 0) continue;
1332
- await import_node_fs8.promises.mkdir(import_node_path8.default.dirname(file), { recursive: true });
1333
- await import_node_fs8.promises.appendFile(file, line, { encoding: "utf8", mode: 384 });
4165
+ await import_node_fs15.promises.mkdir(import_node_path14.default.dirname(file), { recursive: true });
4166
+ await import_node_fs15.promises.appendFile(file, line, { encoding: "utf8", mode: 384 });
1334
4167
  }
1335
4168
  if (terminal && this.activePath) {
1336
- await import_node_fs8.promises.unlink(this.activePath);
4169
+ await import_node_fs15.promises.unlink(this.activePath);
1337
4170
  this.activePath = void 0;
1338
4171
  }
1339
4172
  });
@@ -1344,28 +4177,32 @@ var SessionStoreWriterImpl = class {
1344
4177
  };
1345
4178
 
1346
4179
  // src/session-state.ts
1347
- var import_node_fs10 = require("fs");
1348
- var import_node_path9 = __toESM(require("path"), 1);
4180
+ var import_node_fs17 = require("fs");
4181
+ var import_node_path15 = __toESM(require("path"), 1);
1349
4182
  var import_core2 = require("@codelia/core");
1350
4183
 
1351
4184
  // src/conversation-archive.ts
1352
- var import_node_fs9 = require("fs");
4185
+ var import_node_fs16 = require("fs");
1353
4186
  var import_core = require("@codelia/core");
1354
- function appendOriginalMessages(file, messages) {
4187
+ function appendOriginalMessages(file, messages, provenance) {
1355
4188
  const data = Buffer.from(
1356
- messages.map((message) => JSON.stringify(message)).join("\n") + (messages.length ? "\n" : "")
4189
+ messages.map(
4190
+ (message, index) => JSON.stringify(
4191
+ provenance?.[index] ? { ...message, approval_provenance: provenance[index] } : message
4192
+ )
4193
+ ).join("\n") + (messages.length ? "\n" : "")
1357
4194
  );
1358
- const fd = (0, import_node_fs9.openSync)(
4195
+ const fd = (0, import_node_fs16.openSync)(
1359
4196
  file,
1360
- import_node_fs9.constants.O_RDWR | import_node_fs9.constants.O_CREAT | import_node_fs9.constants.O_APPEND | (import_node_fs9.constants.O_NOFOLLOW ?? 0),
4197
+ import_node_fs16.constants.O_RDWR | import_node_fs16.constants.O_CREAT | import_node_fs16.constants.O_APPEND | (import_node_fs16.constants.O_NOFOLLOW ?? 0),
1361
4198
  384
1362
4199
  );
1363
4200
  try {
1364
- const stat = (0, import_node_fs9.fstatSync)(fd);
4201
+ const stat = (0, import_node_fs16.fstatSync)(fd);
1365
4202
  if (!stat.isFile()) throw new Error("Invalid conversation archive");
1366
4203
  if (stat.size) {
1367
4204
  const last = Buffer.alloc(1);
1368
- (0, import_node_fs9.readSync)(fd, last, 0, 1, stat.size - 1);
4205
+ (0, import_node_fs16.readSync)(fd, last, 0, 1, stat.size - 1);
1369
4206
  if (last[0] !== 10)
1370
4207
  throw new Error(
1371
4208
  "Incomplete conversation archive; original bytes retained"
@@ -1373,10 +4210,10 @@ function appendOriginalMessages(file, messages) {
1373
4210
  }
1374
4211
  let written = 0;
1375
4212
  while (written < data.length)
1376
- written += (0, import_node_fs9.writeSync)(fd, data, written, data.length - written);
1377
- (0, import_node_fs9.fsyncSync)(fd);
4213
+ written += (0, import_node_fs16.writeSync)(fd, data, written, data.length - written);
4214
+ (0, import_node_fs16.fsyncSync)(fd);
1378
4215
  } finally {
1379
- (0, import_node_fs9.closeSync)(fd);
4216
+ (0, import_node_fs16.closeSync)(fd);
1380
4217
  }
1381
4218
  }
1382
4219
  var parseId = (id2) => {
@@ -1395,22 +4232,24 @@ var textOf = (message) => {
1395
4232
  return message.role === "assistant" && message.tool_calls?.length ? `${text}
1396
4233
  ${JSON.stringify(message.tool_calls.map((call) => ({ id: call.id, function: call.function })))}` : text;
1397
4234
  };
1398
- async function* entries(file, start) {
1399
- const fd = (0, import_node_fs9.openSync)(file, import_node_fs9.constants.O_RDONLY | (import_node_fs9.constants.O_NOFOLLOW ?? 0));
4235
+ async function* entries(file, start, maxBytes) {
4236
+ const fd = (0, import_node_fs16.openSync)(file, import_node_fs16.constants.O_RDONLY | (import_node_fs16.constants.O_NOFOLLOW ?? 0));
1400
4237
  let stream;
1401
4238
  try {
1402
- const stat = (0, import_node_fs9.fstatSync)(fd);
4239
+ const stat = (0, import_node_fs16.fstatSync)(fd);
1403
4240
  if (!stat.isFile()) throw new Error("Invalid conversation archive");
1404
4241
  if (start > stat.size)
1405
4242
  throw new Error("Conversation cursor is beyond the archive");
4243
+ if (maxBytes !== void 0 && stat.size - start > maxBytes)
4244
+ throw new Error("Approval conversation window is too large");
1406
4245
  if (start === stat.size) return;
1407
4246
  if (start > 0) {
1408
4247
  const previous = Buffer.alloc(1);
1409
- (0, import_node_fs9.readSync)(fd, previous, 0, 1, start - 1);
4248
+ (0, import_node_fs16.readSync)(fd, previous, 0, 1, start - 1);
1410
4249
  if (previous[0] !== 10)
1411
4250
  throw new Error("Conversation cursor is not a message boundary");
1412
4251
  }
1413
- stream = (0, import_node_fs9.createReadStream)(file, {
4252
+ stream = (0, import_node_fs16.createReadStream)(file, {
1414
4253
  fd,
1415
4254
  autoClose: true,
1416
4255
  start,
@@ -1442,8 +4281,10 @@ async function* entries(file, start) {
1442
4281
  position = end;
1443
4282
  }
1444
4283
  }
4284
+ if (maxBytes !== void 0 && length > 0)
4285
+ throw new Error("Incomplete approval conversation window");
1445
4286
  } finally {
1446
- if (!stream) (0, import_node_fs9.closeSync)(fd);
4287
+ if (!stream) (0, import_node_fs16.closeSync)(fd);
1447
4288
  else if (!stream.closed) {
1448
4289
  const closed = new Promise(
1449
4290
  (resolve) => stream?.once("close", resolve)
@@ -1453,6 +4294,47 @@ async function* entries(file, start) {
1453
4294
  }
1454
4295
  }
1455
4296
  }
4297
+ async function readOriginalApprovalContext(file, {
4298
+ userMessageId,
4299
+ proposalMessageId,
4300
+ workspace,
4301
+ cwd,
4302
+ workspaceIdentity,
4303
+ cwdIdentity
4304
+ }, isAppliedSteer) {
4305
+ const first = parseId(proposalMessageId ?? userMessageId);
4306
+ if (proposalMessageId && first >= parseId(userMessageId)) return null;
4307
+ const matchesScope = (scope) => scope.workspace === workspace && scope.cwd === cwd && scope.workspaceIdentity === workspaceIdentity && scope.cwdIdentity === cwdIdentity;
4308
+ let proposal;
4309
+ const userMessages = [];
4310
+ for await (const { id: id2, message } of entries(file, first, 2 * 1024 * 1024)) {
4311
+ const source = message.approval_provenance;
4312
+ if (message.role === "assistant") {
4313
+ if (!proposalMessageId || userMessages.length > 0) continue;
4314
+ const text = (0, import_core.stringifyContent)(message.content, { mode: "display" });
4315
+ if (!text.trim() && !message.refusal) continue;
4316
+ if (id2 !== proposalMessageId || message.tool_calls?.length || message.refusal || source?.source !== "assistant" || !matchesScope(source) || text.length > 1800)
4317
+ return null;
4318
+ proposal = { id: id2, role: "assistant", text, truncated: false };
4319
+ continue;
4320
+ }
4321
+ if (message.role !== "user" || source?.source === "internal_input")
4322
+ continue;
4323
+ if (source?.source !== "user_input" && source?.source !== "user_steer" || !matchesScope(source) || !source.text.trim() || source.text.includes("<shell_result>") || source.text.length > 1800)
4324
+ return null;
4325
+ if (userMessages.length === 0 && id2 !== userMessageId) return null;
4326
+ if (source.source === "user_steer" && !isAppliedSteer(source.runId, source.steerId))
4327
+ return null;
4328
+ userMessages.push({
4329
+ id: id2,
4330
+ role: "user",
4331
+ text: source.text,
4332
+ truncated: false
4333
+ });
4334
+ if (userMessages.length > 8) return null;
4335
+ }
4336
+ return userMessages.length && (!proposalMessageId || proposal) ? { userMessages, proposal } : null;
4337
+ }
1456
4338
  async function searchOriginalMessages(file, options) {
1457
4339
  const query = options.query.trim().toLowerCase();
1458
4340
  if (!query || query.length > 200)
@@ -1575,9 +4457,9 @@ var MESSAGES_DIRNAME = "messages";
1575
4457
  var STATE_DB_FILENAME = "state.db";
1576
4458
  var SESSION_WORKSPACE_ROOT_META_KEY = "codelia_workspace_root";
1577
4459
  var RUN_INDEX_BACKFILL_KEY = "session_runs_backfilled_at";
1578
- var resolveLegacyStateDir = (paths) => import_node_path9.default.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
1579
- var resolveMessagesDir = (paths) => import_node_path9.default.join(paths.sessionsDir, MESSAGES_DIRNAME);
1580
- var resolveStateDbPath = (paths) => import_node_path9.default.join(paths.sessionsDir, STATE_DB_FILENAME);
4460
+ var resolveLegacyStateDir = (paths) => import_node_path15.default.join(paths.sessionsDir, LEGACY_STATE_DIRNAME);
4461
+ var resolveMessagesDir = (paths) => import_node_path15.default.join(paths.sessionsDir, MESSAGES_DIRNAME);
4462
+ var resolveStateDbPath = (paths) => import_node_path15.default.join(paths.sessionsDir, STATE_DB_FILENAME);
1581
4463
  var extractLastUserMessage = (messages) => {
1582
4464
  for (let idx = messages.length - 1; idx >= 0; idx -= 1) {
1583
4465
  const message = messages[idx];
@@ -1648,13 +4530,13 @@ var SessionStateStoreImpl = class {
1648
4530
  this.sessionsDir = paths.sessionsDir;
1649
4531
  this.legacyStateDir = resolveLegacyStateDir(paths);
1650
4532
  this.messagesDir = resolveMessagesDir(paths);
1651
- this.contextsDir = import_node_path9.default.join(paths.sessionsDir, "contexts");
4533
+ this.contextsDir = import_node_path15.default.join(paths.sessionsDir, "contexts");
1652
4534
  this.stateDbPath = resolveStateDbPath(paths);
1653
4535
  this.ensureDirs = Promise.all([
1654
- import_node_fs10.promises.mkdir(paths.sessionsDir, { recursive: true }),
1655
- import_node_fs10.promises.mkdir(this.legacyStateDir, { recursive: true }),
1656
- import_node_fs10.promises.mkdir(this.messagesDir, { recursive: true }),
1657
- import_node_fs10.promises.mkdir(this.contextsDir, { recursive: true })
4536
+ import_node_fs17.promises.mkdir(paths.sessionsDir, { recursive: true }),
4537
+ import_node_fs17.promises.mkdir(this.legacyStateDir, { recursive: true }),
4538
+ import_node_fs17.promises.mkdir(this.messagesDir, { recursive: true }),
4539
+ import_node_fs17.promises.mkdir(this.contextsDir, { recursive: true })
1658
4540
  ]).then(() => {
1659
4541
  });
1660
4542
  this.onError = options.onError;
@@ -1669,32 +4551,32 @@ var SessionStateStoreImpl = class {
1669
4551
  return this.db;
1670
4552
  }
1671
4553
  resolveLegacyPath(sessionId) {
1672
- return import_node_path9.default.join(this.legacyStateDir, `${sessionId}.json`);
4554
+ return import_node_path15.default.join(this.legacyStateDir, `${sessionId}.json`);
1673
4555
  }
1674
4556
  resolveMessagePath(sessionId) {
1675
- return import_node_path9.default.join(this.messagesDir, `${validateRunLogId(sessionId)}.jsonl`);
4557
+ return import_node_path15.default.join(this.messagesDir, `${validateRunLogId(sessionId)}.jsonl`);
1676
4558
  }
1677
4559
  contextPath(sessionId) {
1678
- return import_node_path9.default.join(this.contextsDir, `${validateRunLogId(sessionId)}.json`);
4560
+ return import_node_path15.default.join(this.contextsDir, `${validateRunLogId(sessionId)}.json`);
1679
4561
  }
1680
4562
  writeContext(sessionId, messages) {
1681
4563
  const target = this.contextPath(sessionId);
1682
4564
  const temporary = `${target}.${crypto.randomUUID()}.tmp`;
1683
- const archiveBytes = (0, import_node_fs10.lstatSync)(this.resolveMessagePath(sessionId)).size;
4565
+ const archiveBytes = (0, import_node_fs17.lstatSync)(this.resolveMessagePath(sessionId)).size;
1684
4566
  try {
1685
- const fd = (0, import_node_fs10.openSync)(temporary, "wx", 384);
4567
+ const fd = (0, import_node_fs17.openSync)(temporary, "wx", 384);
1686
4568
  try {
1687
- (0, import_node_fs10.writeFileSync)(
4569
+ (0, import_node_fs17.writeFileSync)(
1688
4570
  fd,
1689
4571
  JSON.stringify({ version: 1, archive_bytes: archiveBytes, messages })
1690
4572
  );
1691
- (0, import_node_fs10.fsyncSync)(fd);
4573
+ (0, import_node_fs17.fsyncSync)(fd);
1692
4574
  } finally {
1693
- (0, import_node_fs10.closeSync)(fd);
4575
+ (0, import_node_fs17.closeSync)(fd);
1694
4576
  }
1695
- (0, import_node_fs10.renameSync)(temporary, target);
4577
+ (0, import_node_fs17.renameSync)(temporary, target);
1696
4578
  } finally {
1697
- if ((0, import_node_fs10.existsSync)(temporary)) (0, import_node_fs10.unlinkSync)(temporary);
4579
+ if ((0, import_node_fs17.existsSync)(temporary)) (0, import_node_fs17.unlinkSync)(temporary);
1698
4580
  }
1699
4581
  }
1700
4582
  ensureArchive(sessionId, db) {
@@ -1703,16 +4585,16 @@ var SessionStateStoreImpl = class {
1703
4585
  [sessionId]
1704
4586
  );
1705
4587
  if (row?.archive_version === 1) {
1706
- if (!(0, import_node_fs10.lstatSync)(this.resolveMessagePath(sessionId)).isFile())
4588
+ if (!(0, import_node_fs17.lstatSync)(this.resolveMessagePath(sessionId)).isFile())
1707
4589
  throw new Error("Invalid original conversation archive");
1708
4590
  return false;
1709
4591
  }
1710
4592
  const file = this.resolveMessagePath(sessionId);
1711
4593
  let messages = [];
1712
- if ((0, import_node_fs10.existsSync)(file)) {
1713
- if (!(0, import_node_fs10.lstatSync)(file).isFile())
4594
+ if ((0, import_node_fs17.existsSync)(file)) {
4595
+ if (!(0, import_node_fs17.lstatSync)(file).isFile())
1714
4596
  throw new Error("Invalid legacy conversation file");
1715
- messages = deserializeMessages((0, import_node_fs10.readFileSync)(file, "utf8"));
4597
+ messages = deserializeMessages((0, import_node_fs17.readFileSync)(file, "utf8"));
1716
4598
  } else appendOriginalMessages(file, []);
1717
4599
  this.writeContext(sessionId, messages);
1718
4600
  db.run(
@@ -1724,41 +4606,7 @@ var SessionStateStoreImpl = class {
1724
4606
  }
1725
4607
  async openDatabase() {
1726
4608
  await this.ensureDirs;
1727
- if (process.versions.bun) {
1728
- const bunSqliteSpecifier = "bun:sqlite";
1729
- const { Database } = await import(bunSqliteSpecifier);
1730
- const db2 = new Database(this.stateDbPath, { create: true });
1731
- return {
1732
- exec: (sql) => {
1733
- db2.exec(sql);
1734
- },
1735
- run: (sql, params = []) => {
1736
- db2.query(sql).run(...params);
1737
- },
1738
- get: (sql, params = []) => {
1739
- const row = db2.query(sql).get(...params);
1740
- return row ?? void 0;
1741
- },
1742
- all: (sql, params = []) => db2.query(sql).all(...params)
1743
- };
1744
- }
1745
- const betterSqliteSpecifier = "better-sqlite3";
1746
- const betterSqliteModule = await import(betterSqliteSpecifier);
1747
- const BetterSqlite3 = betterSqliteModule.default ?? betterSqliteModule;
1748
- const db = new BetterSqlite3(this.stateDbPath);
1749
- return {
1750
- exec: (sql) => {
1751
- db.exec(sql);
1752
- },
1753
- run: (sql, params = []) => {
1754
- db.prepare(sql).run(...params);
1755
- },
1756
- get: (sql, params = []) => {
1757
- const row = db.prepare(sql).get(...params);
1758
- return row ?? void 0;
1759
- },
1760
- all: (sql, params = []) => db.prepare(sql).all(...params)
1761
- };
4609
+ return openSqlite(this.stateDbPath);
1762
4610
  }
1763
4611
  initDatabaseSchema(db) {
1764
4612
  db.exec("PRAGMA busy_timeout = 5000;");
@@ -1800,6 +4648,12 @@ var SessionStateStoreImpl = class {
1800
4648
  db.exec(`
1801
4649
  CREATE INDEX IF NOT EXISTS idx_session_state_updated_at
1802
4650
  ON session_state(updated_at DESC);
4651
+ CREATE TABLE IF NOT EXISTS session_approval_steers (
4652
+ session_id TEXT NOT NULL,
4653
+ run_id TEXT NOT NULL,
4654
+ steer_id TEXT NOT NULL,
4655
+ PRIMARY KEY (session_id, run_id, steer_id)
4656
+ );
1803
4657
  `);
1804
4658
  db.exec(`
1805
4659
  CREATE TABLE IF NOT EXISTS session_runs (
@@ -1868,7 +4722,7 @@ var SessionStateStoreImpl = class {
1868
4722
  }
1869
4723
  async loadLegacy(sessionId) {
1870
4724
  try {
1871
- const file = await import_node_fs10.promises.readFile(this.resolveLegacyPath(sessionId), "utf8");
4725
+ const file = await import_node_fs17.promises.readFile(this.resolveLegacyPath(sessionId), "utf8");
1872
4726
  const parsed = JSON.parse(file);
1873
4727
  if (!parsed || typeof parsed !== "object") return null;
1874
4728
  if (!parsed.session_id || !parsed.updated_at) return null;
@@ -1908,14 +4762,14 @@ var SessionStateStoreImpl = class {
1908
4762
  try {
1909
4763
  if (row.archive_version === 1) {
1910
4764
  const checkpoint = JSON.parse(
1911
- await import_node_fs10.promises.readFile(this.contextPath(sessionId), "utf8")
4765
+ await import_node_fs17.promises.readFile(this.contextPath(sessionId), "utf8")
1912
4766
  );
1913
4767
  if (checkpoint.version !== 1 || !Array.isArray(checkpoint.messages))
1914
4768
  throw new Error("Invalid active conversation checkpoint");
1915
4769
  messages = checkpoint.messages;
1916
4770
  } else
1917
4771
  messages = deserializeMessages(
1918
- await import_node_fs10.promises.readFile(this.resolveMessagePath(sessionId), "utf8")
4772
+ await import_node_fs17.promises.readFile(this.resolveMessagePath(sessionId), "utf8")
1919
4773
  );
1920
4774
  } catch (error) {
1921
4775
  if (error.code === "ENOENT" && row.archive_version !== 1) {
@@ -1995,12 +4849,16 @@ var SessionStateStoreImpl = class {
1995
4849
  );
1996
4850
  });
1997
4851
  }
1998
- async appendMessages(sessionId, messages) {
4852
+ async appendMessages(sessionId, messages, origins) {
1999
4853
  const db = await this.requireDb("archive.append", sessionId);
2000
4854
  if (!await this.getSummary(sessionId)) await this.load(sessionId);
2001
4855
  await this.withRetentionGuard(sessionId, () => {
2002
4856
  this.ensureArchive(sessionId, db);
2003
- appendOriginalMessages(this.resolveMessagePath(sessionId), messages);
4857
+ appendOriginalMessages(
4858
+ this.resolveMessagePath(sessionId),
4859
+ messages,
4860
+ origins
4861
+ );
2004
4862
  });
2005
4863
  }
2006
4864
  async searchMessages(sessionId, options) {
@@ -2011,6 +4869,25 @@ var SessionStateStoreImpl = class {
2011
4869
  if (!await this.getSummary(sessionId)) await this.load(sessionId);
2012
4870
  return readOriginalMessage(this.resolveMessagePath(sessionId), options);
2013
4871
  }
4872
+ async readApprovalContext(sessionId, references) {
4873
+ if (!await this.getSummary(sessionId)) return null;
4874
+ const db = await this.requireDb("archive.approval", sessionId);
4875
+ return readOriginalApprovalContext(
4876
+ this.resolveMessagePath(sessionId),
4877
+ references,
4878
+ (runId, steerId) => !!db.get(
4879
+ "SELECT 1 AS applied FROM session_approval_steers WHERE session_id = ? AND run_id = ? AND steer_id = ?",
4880
+ [sessionId, runId, steerId]
4881
+ )
4882
+ );
4883
+ }
4884
+ async confirmApprovalSteer(sessionId, runId, steerId) {
4885
+ const db = await this.requireDb("archive.steer", sessionId);
4886
+ db.run(
4887
+ "INSERT OR IGNORE INTO session_approval_steers (session_id, run_id, steer_id) VALUES (?, ?, ?)",
4888
+ [sessionId, runId, steerId]
4889
+ );
4890
+ }
2014
4891
  async load(sessionId) {
2015
4892
  const db = await this.requireDb("load", sessionId);
2016
4893
  try {
@@ -2230,7 +5107,7 @@ var SessionStateStoreImpl = class {
2230
5107
  async listLegacySummaries() {
2231
5108
  let entries2;
2232
5109
  try {
2233
- entries2 = await import_node_fs10.promises.readdir(this.legacyStateDir, {
5110
+ entries2 = await import_node_fs17.promises.readdir(this.legacyStateDir, {
2234
5111
  withFileTypes: true,
2235
5112
  encoding: "utf8"
2236
5113
  });
@@ -2242,9 +5119,9 @@ var SessionStateStoreImpl = class {
2242
5119
  for (const entry of entries2) {
2243
5120
  if (!entry.isFile()) continue;
2244
5121
  if (!entry.name.endsWith(".json")) continue;
2245
- const filePath = import_node_path9.default.join(this.legacyStateDir, entry.name);
5122
+ const filePath = import_node_path15.default.join(this.legacyStateDir, entry.name);
2246
5123
  try {
2247
- const contents = await import_node_fs10.promises.readFile(filePath, "utf8");
5124
+ const contents = await import_node_fs17.promises.readFile(filePath, "utf8");
2248
5125
  const parsed = JSON.parse(contents);
2249
5126
  if (!parsed || typeof parsed !== "object") continue;
2250
5127
  if (!parsed.session_id || !parsed.updated_at) continue;
@@ -2313,14 +5190,14 @@ var RunEventStoreFactoryImpl = class {
2313
5190
  };
2314
5191
 
2315
5192
  // src/run-log-retention.ts
2316
- var import_node_fs14 = require("fs");
2317
- var import_node_path12 = __toESM(require("path"), 1);
5193
+ var import_node_fs21 = require("fs");
5194
+ var import_node_path18 = __toESM(require("path"), 1);
2318
5195
 
2319
5196
  // src/run-log-compression.ts
2320
- var import_node_crypto6 = require("crypto");
2321
- var import_node_fs11 = require("fs");
5197
+ var import_node_crypto10 = require("crypto");
5198
+ var import_node_fs18 = require("fs");
2322
5199
  var import_node_stream2 = require("stream");
2323
- var import_promises6 = require("stream/promises");
5200
+ var import_promises8 = require("stream/promises");
2324
5201
  var import_node_zlib3 = require("zlib");
2325
5202
 
2326
5203
  // src/run-log-records.ts
@@ -2418,10 +5295,10 @@ async function* projectArchivedRunLog(file, usage) {
2418
5295
  // src/run-log-compression.ts
2419
5296
  async function prepareCompressedLog(file, usage) {
2420
5297
  const temporary = `${file}.${crypto.randomUUID()}.gz.tmp`;
2421
- const hash = (0, import_node_crypto6.createHash)("sha256");
5298
+ const hash = (0, import_node_crypto10.createHash)("sha256");
2422
5299
  let bytes = 0;
2423
5300
  try {
2424
- await (0, import_promises6.pipeline)(
5301
+ await (0, import_promises8.pipeline)(
2425
5302
  import_node_stream2.Readable.from(projectArchivedRunLog(file, usage)),
2426
5303
  new import_node_stream2.Transform({
2427
5304
  transform(chunk, _encoding, callback) {
@@ -2431,13 +5308,13 @@ async function prepareCompressedLog(file, usage) {
2431
5308
  }
2432
5309
  }),
2433
5310
  (0, import_node_zlib3.createGzip)(),
2434
- (0, import_node_fs11.createWriteStream)(temporary, { flags: "wx", mode: 384 })
5311
+ (0, import_node_fs18.createWriteStream)(temporary, { flags: "wx", mode: 384 })
2435
5312
  );
2436
5313
  const expected = hash.digest("hex");
2437
- const verification = (0, import_node_crypto6.createHash)("sha256");
5314
+ const verification = (0, import_node_crypto10.createHash)("sha256");
2438
5315
  let decoded = 0;
2439
- await (0, import_promises6.pipeline)(
2440
- (0, import_node_fs11.createReadStream)(temporary),
5316
+ await (0, import_promises8.pipeline)(
5317
+ (0, import_node_fs18.createReadStream)(temporary),
2441
5318
  (0, import_node_zlib3.createGunzip)(),
2442
5319
  new import_node_stream2.Transform({
2443
5320
  transform(chunk, _encoding, callback) {
@@ -2449,26 +5326,26 @@ async function prepareCompressedLog(file, usage) {
2449
5326
  );
2450
5327
  if (decoded !== bytes || verification.digest("hex") !== expected)
2451
5328
  throw new Error("Compressed run log verification failed");
2452
- const persisted = await import_node_fs11.promises.open(temporary, "r+");
5329
+ const persisted = await import_node_fs18.promises.open(temporary, "r+");
2453
5330
  try {
2454
5331
  await persisted.sync();
2455
5332
  } finally {
2456
5333
  await persisted.close();
2457
5334
  }
2458
- return { temporary, size: (await import_node_fs11.promises.stat(temporary)).size };
5335
+ return { temporary, size: (await import_node_fs18.promises.stat(temporary)).size };
2459
5336
  } catch (error) {
2460
- await import_node_fs11.promises.rm(temporary, { force: true });
5337
+ await import_node_fs18.promises.rm(temporary, { force: true });
2461
5338
  throw error;
2462
5339
  }
2463
5340
  }
2464
5341
 
2465
5342
  // src/run-log-files.ts
2466
- var import_node_fs12 = require("fs");
2467
- var import_node_path10 = __toESM(require("path"), 1);
5343
+ var import_node_fs19 = require("fs");
5344
+ var import_node_path16 = __toESM(require("path"), 1);
2468
5345
  var MAX_ACTIVE_RUN_MARKER_BYTES = 256;
2469
5346
  var isRegularDirectory = async (directory2) => {
2470
5347
  try {
2471
- return (await import_node_fs12.promises.lstat(directory2)).isDirectory();
5348
+ return (await import_node_fs19.promises.lstat(directory2)).isDirectory();
2472
5349
  } catch {
2473
5350
  return false;
2474
5351
  }
@@ -2494,9 +5371,9 @@ async function readHeader2(file) {
2494
5371
  }
2495
5372
  async function inspectCandidate(root, datePath, name, diagnostic) {
2496
5373
  const compressed = name.endsWith(".jsonl.gz");
2497
- const file = import_node_path10.default.join(root, datePath, name);
5374
+ const file = import_node_path16.default.join(root, datePath, name);
2498
5375
  try {
2499
- const stat = await import_node_fs12.promises.lstat(file);
5376
+ const stat = await import_node_fs19.promises.lstat(file);
2500
5377
  if (!stat.isFile()) return void 0;
2501
5378
  const header = await readHeader2(file);
2502
5379
  if (!header || name !== `${header.run_id}.jsonl${compressed ? ".gz" : ""}` || compressed && header.meta?.codelia_log_archive_version === RUN_LOG_ARCHIVE_VERSION)
@@ -2521,19 +5398,19 @@ async function inspectCandidate(root, datePath, name, diagnostic) {
2521
5398
  async function collectRunLogCandidates(root, diagnostic = false) {
2522
5399
  if (!await isRegularDirectory(root)) return [];
2523
5400
  const candidates = [];
2524
- for (const year of await import_node_fs12.promises.readdir(root, { withFileTypes: true })) {
5401
+ for (const year of await import_node_fs19.promises.readdir(root, { withFileTypes: true })) {
2525
5402
  if (!year.isDirectory() || !/^\d{4}$/.test(year.name)) continue;
2526
- for (const month of await import_node_fs12.promises.readdir(import_node_path10.default.join(root, year.name), {
5403
+ for (const month of await import_node_fs19.promises.readdir(import_node_path16.default.join(root, year.name), {
2527
5404
  withFileTypes: true
2528
5405
  })) {
2529
5406
  if (!month.isDirectory() || !/^\d{2}$/.test(month.name)) continue;
2530
- for (const day of await import_node_fs12.promises.readdir(
2531
- import_node_path10.default.join(root, year.name, month.name),
5407
+ for (const day of await import_node_fs19.promises.readdir(
5408
+ import_node_path16.default.join(root, year.name, month.name),
2532
5409
  { withFileTypes: true }
2533
5410
  )) {
2534
5411
  if (!day.isDirectory() || !/^\d{2}$/.test(day.name)) continue;
2535
- const datePath = import_node_path10.default.join(year.name, month.name, day.name);
2536
- const entries2 = await import_node_fs12.promises.readdir(import_node_path10.default.join(root, datePath), {
5412
+ const datePath = import_node_path16.default.join(year.name, month.name, day.name);
5413
+ const entries2 = await import_node_fs19.promises.readdir(import_node_path16.default.join(root, datePath), {
2537
5414
  withFileTypes: true
2538
5415
  });
2539
5416
  const plain = new Set(
@@ -2565,10 +5442,10 @@ async function collectRunLogCandidatesAt(root, relPaths, diagnostic = false) {
2565
5442
  const name = parts.pop();
2566
5443
  if (!name?.endsWith(".jsonl") || parts.length !== 3 || !/^\d{4}$/.test(parts[0] ?? "") || !/^\d{2}$/.test(parts[1] ?? "") || !/^\d{2}$/.test(parts[2] ?? "") || name.includes("\\"))
2567
5444
  continue;
2568
- const datePath = import_node_path10.default.join(...parts);
5445
+ const datePath = import_node_path16.default.join(...parts);
2569
5446
  let selected = name;
2570
5447
  try {
2571
- await import_node_fs12.promises.lstat(import_node_path10.default.join(root, datePath, name));
5448
+ await import_node_fs19.promises.lstat(import_node_path16.default.join(root, datePath, name));
2572
5449
  } catch {
2573
5450
  if (diagnostic) continue;
2574
5451
  selected = `${name}.gz`;
@@ -2587,25 +5464,25 @@ async function removeReusedProcessMarkers(paths, sessionId, identify = (pid) =>
2587
5464
  const directory2 = activeRunDirectory(paths, sessionId);
2588
5465
  let entries2;
2589
5466
  try {
2590
- entries2 = (0, import_node_fs12.readdirSync)(directory2);
5467
+ entries2 = (0, import_node_fs19.readdirSync)(directory2);
2591
5468
  } catch {
2592
5469
  return;
2593
5470
  }
2594
5471
  for (const entry of entries2) {
2595
- const file = import_node_path10.default.join(directory2, entry);
5472
+ const file = import_node_path16.default.join(directory2, entry);
2596
5473
  try {
2597
- const before = (0, import_node_fs12.lstatSync)(file);
5474
+ const before = (0, import_node_fs19.lstatSync)(file);
2598
5475
  if (!before.isFile() || before.size > MAX_ACTIVE_RUN_MARKER_BYTES)
2599
5476
  continue;
2600
- const contents = (0, import_node_fs12.readFileSync)(file, "utf8");
5477
+ const contents = (0, import_node_fs19.readFileSync)(file, "utf8");
2601
5478
  const { pid, identity } = JSON.parse(contents);
2602
5479
  if (!Number.isSafeInteger(pid) || pid < 1 || typeof identity !== "string" || !identity)
2603
5480
  continue;
2604
5481
  const current = await identify(pid);
2605
5482
  if (!current || current === identity) continue;
2606
- const after = (0, import_node_fs12.lstatSync)(file);
2607
- if (after.isFile() && after.ino === before.ino && after.dev === before.dev && after.size === before.size && after.mtimeMs === before.mtimeMs && (0, import_node_fs12.readFileSync)(file, "utf8") === contents)
2608
- (0, import_node_fs12.unlinkSync)(file);
5483
+ const after = (0, import_node_fs19.lstatSync)(file);
5484
+ if (after.isFile() && after.ino === before.ino && after.dev === before.dev && after.size === before.size && after.mtimeMs === before.mtimeMs && (0, import_node_fs19.readFileSync)(file, "utf8") === contents)
5485
+ (0, import_node_fs19.unlinkSync)(file);
2609
5486
  } catch {
2610
5487
  }
2611
5488
  }
@@ -2613,12 +5490,12 @@ async function removeReusedProcessMarkers(paths, sessionId, identify = (pid) =>
2613
5490
  function hasActiveRunWriter(paths, sessionId) {
2614
5491
  try {
2615
5492
  const directory2 = activeRunDirectory(paths, sessionId);
2616
- for (const entry of (0, import_node_fs12.readdirSync)(directory2, { withFileTypes: true })) {
5493
+ for (const entry of (0, import_node_fs19.readdirSync)(directory2, { withFileTypes: true })) {
2617
5494
  if (!entry.isFile()) return true;
2618
5495
  try {
2619
- const file = import_node_path10.default.join(directory2, entry.name);
2620
- if ((0, import_node_fs12.lstatSync)(file).size > MAX_ACTIVE_RUN_MARKER_BYTES) return true;
2621
- const { pid } = JSON.parse((0, import_node_fs12.readFileSync)(file, "utf8"));
5496
+ const file = import_node_path16.default.join(directory2, entry.name);
5497
+ if ((0, import_node_fs19.lstatSync)(file).size > MAX_ACTIVE_RUN_MARKER_BYTES) return true;
5498
+ const { pid } = JSON.parse((0, import_node_fs19.readFileSync)(file, "utf8"));
2622
5499
  if (!Number.isSafeInteger(pid) || pid < 1) return true;
2623
5500
  try {
2624
5501
  process.kill(pid, 0);
@@ -2637,8 +5514,8 @@ function hasActiveRunWriter(paths, sessionId) {
2637
5514
  }
2638
5515
 
2639
5516
  // src/run-log-usage.ts
2640
- var import_node_fs13 = require("fs");
2641
- var import_node_path11 = __toESM(require("path"), 1);
5517
+ var import_node_fs20 = require("fs");
5518
+ var import_node_path17 = __toESM(require("path"), 1);
2642
5519
 
2643
5520
  // src/run-log-request-model.ts
2644
5521
  var TOKENS = /["\\{}[\]:,]/g;
@@ -2785,7 +5662,7 @@ async function preserveRunUsage(paths, source) {
2785
5662
  const records = /* @__PURE__ */ new Map();
2786
5663
  const requestModels = /* @__PURE__ */ new Map();
2787
5664
  try {
2788
- const stat = await import_node_fs13.promises.lstat(destination);
5665
+ const stat = await import_node_fs20.promises.lstat(destination);
2789
5666
  if (!stat.isFile()) throw new Error("Invalid usage log");
2790
5667
  for await (const record2 of readUsageRecords(destination))
2791
5668
  if (record2.type === "llm.usage")
@@ -2826,15 +5703,15 @@ async function preserveRunUsage(paths, source) {
2826
5703
  name: record2.model?.name ?? source.model?.name
2827
5704
  })
2828
5705
  );
2829
- await import_node_fs13.promises.mkdir(import_node_path11.default.dirname(destination), { recursive: true });
5706
+ await import_node_fs20.promises.mkdir(import_node_path17.default.dirname(destination), { recursive: true });
2830
5707
  const temporary = `${destination}.${process.pid}.${crypto.randomUUID()}.tmp`;
2831
5708
  try {
2832
5709
  const lines = ordered.map((record2) => JSON.stringify(record2)).join("\n");
2833
- await import_node_fs13.promises.writeFile(temporary, `${lines}
5710
+ await import_node_fs20.promises.writeFile(temporary, `${lines}
2834
5711
  `, { mode: 384 });
2835
- await import_node_fs13.promises.rename(temporary, destination);
5712
+ await import_node_fs20.promises.rename(temporary, destination);
2836
5713
  } finally {
2837
- await import_node_fs13.promises.rm(temporary, { force: true });
5714
+ await import_node_fs20.promises.rm(temporary, { force: true });
2838
5715
  }
2839
5716
  return ordered;
2840
5717
  }
@@ -2849,21 +5726,21 @@ var eligible = (summary, newestMtime, now) => {
2849
5726
  };
2850
5727
  function commitCandidate(candidate, compressed, result) {
2851
5728
  try {
2852
- const stat = (0, import_node_fs14.lstatSync)(candidate.file);
5729
+ const stat = (0, import_node_fs21.lstatSync)(candidate.file);
2853
5730
  if (!stat.isFile() || stat.ino !== candidate.ino || stat.dev !== candidate.dev || stat.size !== candidate.size || stat.mtimeMs !== candidate.mtimeMs) {
2854
5731
  result.skipped++;
2855
5732
  return;
2856
5733
  }
2857
5734
  if (compressed) {
2858
5735
  const target = candidate.compressed ? candidate.file : `${candidate.file}.gz`;
2859
- if (candidate.compressed) (0, import_node_fs14.renameSync)(compressed.temporary, target);
2860
- else (0, import_node_fs14.linkSync)(compressed.temporary, target);
2861
- (0, import_node_fs14.utimesSync)(target, stat.atime, stat.mtime);
2862
- if (!candidate.compressed) (0, import_node_fs14.unlinkSync)(candidate.file);
5736
+ if (candidate.compressed) (0, import_node_fs21.renameSync)(compressed.temporary, target);
5737
+ else (0, import_node_fs21.linkSync)(compressed.temporary, target);
5738
+ (0, import_node_fs21.utimesSync)(target, stat.atime, stat.mtime);
5739
+ if (!candidate.compressed) (0, import_node_fs21.unlinkSync)(candidate.file);
2863
5740
  result.compressed++;
2864
5741
  result.reclaimed_bytes += Math.max(0, stat.size - compressed.size);
2865
5742
  } else {
2866
- (0, import_node_fs14.unlinkSync)(candidate.file);
5743
+ (0, import_node_fs21.unlinkSync)(candidate.file);
2867
5744
  result.deleted++;
2868
5745
  result.reclaimed_bytes += stat.size;
2869
5746
  }
@@ -2887,7 +5764,7 @@ async function processCandidate(context, candidate, newestMtime, usage) {
2887
5764
  } catch {
2888
5765
  result.failed++;
2889
5766
  } finally {
2890
- if (compressed) await import_node_fs14.promises.rm(compressed.temporary, { force: true });
5767
+ if (compressed) await import_node_fs21.promises.rm(compressed.temporary, { force: true });
2891
5768
  }
2892
5769
  }
2893
5770
  async function cleanupRunLogs(options) {
@@ -2902,7 +5779,7 @@ async function cleanupRunLogs(options) {
2902
5779
  };
2903
5780
  const context = { paths, sessions, now, result };
2904
5781
  if (!await isRegularDirectory(paths.sessionsDir)) return result;
2905
- const diagnosticsDir = import_node_path12.default.join(paths.sessionsDir, "diagnostics");
5782
+ const diagnosticsDir = import_node_path18.default.join(paths.sessionsDir, "diagnostics");
2906
5783
  let relPaths;
2907
5784
  if (options.sessionId) {
2908
5785
  try {
@@ -2951,8 +5828,8 @@ async function cleanupRunLogs(options) {
2951
5828
  result.skipped += group.length - selected.length;
2952
5829
  if (selected.length === 0) continue;
2953
5830
  try {
2954
- const snapshot = await import_node_fs14.promises.lstat(
2955
- import_node_path12.default.join(paths.sessionsDir, "messages", `${sessionId}.jsonl`)
5831
+ const snapshot = await import_node_fs21.promises.lstat(
5832
+ import_node_path18.default.join(paths.sessionsDir, "messages", `${sessionId}.jsonl`)
2956
5833
  );
2957
5834
  if (!snapshot.isFile() || snapshot.size === 0) {
2958
5835
  result.skipped += selected.length;
@@ -2988,8 +5865,8 @@ var StoragePathServiceImpl = class {
2988
5865
  };
2989
5866
 
2990
5867
  // src/task-registry.ts
2991
- var import_node_fs15 = require("fs");
2992
- var import_node_path13 = __toESM(require("path"), 1);
5868
+ var import_node_fs22 = require("fs");
5869
+ var import_node_path19 = __toESM(require("path"), 1);
2993
5870
  var TASKS_DIRNAME = "tasks";
2994
5871
  var sortByUpdatedDesc = (tasks) => [...tasks].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
2995
5872
  var toShellKeyBase = (label2) => {
@@ -3047,14 +5924,14 @@ var assignMissingShellKeys = (tasks) => {
3047
5924
  return updates;
3048
5925
  };
3049
5926
  var atomicWrite = async (filePath, payload) => {
3050
- const dir = import_node_path13.default.dirname(filePath);
3051
- const base = import_node_path13.default.basename(filePath);
3052
- const tmp = import_node_path13.default.join(
5927
+ const dir = import_node_path19.default.dirname(filePath);
5928
+ const base = import_node_path19.default.basename(filePath);
5929
+ const tmp = import_node_path19.default.join(
3053
5930
  dir,
3054
5931
  `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
3055
5932
  );
3056
- await import_node_fs15.promises.writeFile(tmp, payload, "utf8");
3057
- await import_node_fs15.promises.rename(tmp, filePath);
5933
+ await import_node_fs22.promises.writeFile(tmp, payload, "utf8");
5934
+ await import_node_fs22.promises.rename(tmp, filePath);
3058
5935
  };
3059
5936
  var isTaskState = (value) => value === "queued" || value === "running" || value === "completed" || value === "failed" || value === "cancelled";
3060
5937
  var isTaskKind = (value) => value === "shell" || value === "subagent";
@@ -3165,7 +6042,7 @@ var normalizeTaskRecord = (value) => {
3165
6042
  };
3166
6043
  var readTaskFile = async (filePath) => {
3167
6044
  try {
3168
- const raw = await import_node_fs15.promises.readFile(filePath, "utf8");
6045
+ const raw = await import_node_fs22.promises.readFile(filePath, "utf8");
3169
6046
  return normalizeTaskRecord(JSON.parse(raw));
3170
6047
  } catch {
3171
6048
  return null;
@@ -3180,19 +6057,19 @@ var TaskRegistryStore = class {
3180
6057
  return;
3181
6058
  }
3182
6059
  const root = resolveStoragePaths().root;
3183
- this.tasksDir = import_node_path13.default.join(root, TASKS_DIRNAME);
6060
+ this.tasksDir = import_node_path19.default.join(root, TASKS_DIRNAME);
3184
6061
  }
3185
6062
  async ensureDir() {
3186
- await import_node_fs15.promises.mkdir(this.tasksDir, { recursive: true });
6063
+ await import_node_fs22.promises.mkdir(this.tasksDir, { recursive: true });
3187
6064
  }
3188
6065
  taskPath(taskId) {
3189
- return import_node_path13.default.join(this.tasksDir, taskFileName(taskId));
6066
+ return import_node_path19.default.join(this.tasksDir, taskFileName(taskId));
3190
6067
  }
3191
6068
  async list() {
3192
6069
  await this.ensureDir();
3193
- const entries2 = await import_node_fs15.promises.readdir(this.tasksDir, { withFileTypes: true });
6070
+ const entries2 = await import_node_fs22.promises.readdir(this.tasksDir, { withFileTypes: true });
3194
6071
  const tasks = (await Promise.all(
3195
- entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(import_node_path13.default.join(this.tasksDir, entry.name)))
6072
+ entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => readTaskFile(import_node_path19.default.join(this.tasksDir, entry.name)))
3196
6073
  )).filter((task) => task !== null);
3197
6074
  const keyBackfills = assignMissingShellKeys(tasks);
3198
6075
  if (keyBackfills.length > 0) {
@@ -3234,8 +6111,8 @@ var TaskRegistryStore = class {
3234
6111
  };
3235
6112
 
3236
6113
  // src/tool-output-cache.ts
3237
- var import_node_fs16 = require("fs");
3238
- var import_node_path14 = __toESM(require("path"), 1);
6114
+ var import_node_fs23 = require("fs");
6115
+ var import_node_path20 = __toESM(require("path"), 1);
3239
6116
  var DEFAULT_MAX_MATCHES = 50;
3240
6117
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
3241
6118
  var DEFAULT_MAX_READ_BYTES = 64 * 1024;
@@ -3347,15 +6224,15 @@ var ToolOutputCacheStoreImpl = class {
3347
6224
  async save(record2) {
3348
6225
  const refId = normalizeRefId(record2.tool_call_id);
3349
6226
  const filePath = this.resolvePath(refId);
3350
- await import_node_fs16.promises.mkdir(this.baseDir, { recursive: true });
3351
- await import_node_fs16.promises.writeFile(filePath, record2.content, "utf8");
6227
+ await import_node_fs23.promises.mkdir(this.baseDir, { recursive: true });
6228
+ await import_node_fs23.promises.writeFile(filePath, record2.content, "utf8");
3352
6229
  const byteSize = Buffer.byteLength(record2.content, "utf8");
3353
6230
  const lineCount = record2.content.split(/\r?\n/).length;
3354
6231
  return { id: refId, byte_size: byteSize, line_count: lineCount };
3355
6232
  }
3356
6233
  async read(refId, options = {}) {
3357
6234
  const filePath = this.resolvePath(refId);
3358
- const content = await import_node_fs16.promises.readFile(filePath, "utf8");
6235
+ const content = await import_node_fs23.promises.readFile(filePath, "utf8");
3359
6236
  const lines = content.split(/\r?\n/);
3360
6237
  const offset = options.offset ?? 0;
3361
6238
  const limit = options.limit ?? lines.length;
@@ -3414,7 +6291,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
3414
6291
  }
3415
6292
  async readTail(refId, options) {
3416
6293
  const filePath = this.resolvePath(refId);
3417
- const content = await import_node_fs16.promises.readFile(filePath, "utf8");
6294
+ const content = await import_node_fs23.promises.readFile(filePath, "utf8");
3418
6295
  const lines = content.split(/\r?\n/);
3419
6296
  const tailLines = Math.max(1, Math.trunc(options.tail_lines));
3420
6297
  const start = Math.max(0, lines.length - tailLines);
@@ -3426,7 +6303,7 @@ For full long-line content, use tool_output_cache_line({"ref_id":"${normalizeRef
3426
6303
  }
3427
6304
  async readLine(refId, options) {
3428
6305
  const filePath = this.resolvePath(refId);
3429
- const content = await import_node_fs16.promises.readFile(filePath, "utf8");
6306
+ const content = await import_node_fs23.promises.readFile(filePath, "utf8");
3430
6307
  const lines = content.split(/\r?\n/);
3431
6308
  const lineIndex = options.line_number - 1;
3432
6309
  if (lineIndex < 0 || lineIndex >= lines.length) {
@@ -3467,7 +6344,7 @@ tool_output_cache_line({"ref_id":"${normalizeRefId(refId)}","line_number":${opti
3467
6344
  }
3468
6345
  async grep(refId, options) {
3469
6346
  const filePath = this.resolvePath(refId);
3470
- const content = await import_node_fs16.promises.readFile(filePath, "utf8");
6347
+ const content = await import_node_fs23.promises.readFile(filePath, "utf8");
3471
6348
  const lines = content.split(/\r?\n/);
3472
6349
  const regex = options.regex ? new RegExp(options.pattern) : new RegExp(options.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
3473
6350
  const before = Math.max(0, options.before ?? 0);
@@ -3518,14 +6395,24 @@ ${snippet}`;
3518
6395
  return output;
3519
6396
  }
3520
6397
  resolvePath(refId) {
3521
- return import_node_path14.default.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
6398
+ return import_node_path20.default.join(this.baseDir, `${normalizeRefId(refId)}.txt`);
3522
6399
  }
3523
6400
  };
3524
6401
  // Annotate the CommonJS export names for ESM import in node:
3525
6402
  0 && (module.exports = {
6403
+ AUTH_VERSION_V1,
6404
+ AUTH_VERSION_V2,
6405
+ CODELIA_AUTH_KEYCHAIN_SERVICE,
6406
+ CODELIA_MCP_AUTH_KEYCHAIN_SERVICE,
6407
+ CredentialConflictError,
6408
+ DEFAULT_AUTH_LOCK_TIMEOUT_MS,
6409
+ DEFAULT_OAUTH_REFRESH_TIMEOUT_MS,
3526
6410
  FileAttachmentStore,
3527
6411
  IMAGE_MAX_BYTES,
3528
6412
  ImageArtifactStore,
6413
+ KeychainError,
6414
+ MCP_AUTH_VERSION,
6415
+ MacOsKeychainClient,
3529
6416
  McpAuthStore,
3530
6417
  ProjectsPolicyStore,
3531
6418
  RUN_LOG_RETENTION_MS,
@@ -3536,17 +6423,57 @@ ${snippet}`;
3536
6423
  StoragePathServiceImpl,
3537
6424
  TaskRegistryStore,
3538
6425
  ToolOutputCacheStoreImpl,
6426
+ authLockPathFor,
6427
+ buildMcpAuthBinding,
6428
+ canonicalJsonEqual,
6429
+ canonicalJsonStringify,
6430
+ canonicalPathOrResolvedSync,
6431
+ canonicalizeMcpUri,
3539
6432
  cleanupRunLogs,
6433
+ clearStoreAcrossAllLocationsUnlocked,
6434
+ coordinateCredentialBackend,
6435
+ coordinateCredentialBackendUnlocked,
3540
6436
  createAttachmentId,
6437
+ deriveMcpIssuer,
3541
6438
  detectImageAttachmentType,
6439
+ enforceWindowsOwnerOnlyDacl,
6440
+ ensureCredentialsDirectory,
3542
6441
  ensureStorageDirs,
3543
6442
  getProcessIdentity,
6443
+ inspectCredentialStorageStatus,
3544
6444
  isAttachmentId,
6445
+ isCanonicalHomeWorkspaceSync,
6446
+ isSameConfigFilePath,
6447
+ isTrustedGlobalConfigLocationSync,
6448
+ isWithinPath,
6449
+ keychainAccountForConfigDir,
6450
+ mcpAuthBindingMatches,
6451
+ mcpAuthStoreAdapter,
6452
+ openSqlite,
6453
+ parseAuthDocument,
6454
+ parseAuthStorageState,
6455
+ parseMcpAuthDocument,
6456
+ providerAuthStoreAdapter,
6457
+ readAuthStorageState,
6458
+ readAuthStorageStateSync,
3545
6459
  readRunLogLines,
6460
+ resolveConfiguredAuthStorageMode,
6461
+ resolveCredentialConflict,
3546
6462
  resolveIndexedRunLog,
3547
6463
  resolveRunLogPath,
3548
6464
  resolveStoragePaths,
6465
+ resolveWindowsSystem32Dir,
6466
+ runTwoPhaseMigration,
3549
6467
  scanSessionRunLogs,
3550
6468
  validateImageAttachment,
3551
- validateImagePng
6469
+ validateImagePng,
6470
+ verifyOwnedAncestors,
6471
+ verifyOwnedAncestorsSync,
6472
+ verifyUserStorageLocation,
6473
+ verifyUserStorageLocationSync,
6474
+ verifyWindowsCredentialFileAcl,
6475
+ verifyWindowsCredentialFileAclSync,
6476
+ withAuthStoreLock,
6477
+ writeAuthStorageState,
6478
+ writeFileAtomic
3552
6479
  });